<?php
$page_title = 'Material Requirements Planning (MRP)';
require_once('includes/load.php');
page_require_level(3);

$selected_product_name = ''; // Initialize the selected product name

// Retrieve part numbers and total quantity orders from production_schedule table
$partNumbersResult = $db->query("SELECT part_number, SUM(quantity_order) AS total_quantity_order FROM production_schedule GROUP BY part_number");

$partNumbers = array();
while ($row = $db->fetch_assoc($partNumbersResult)) {
    $partNumber = $row['part_number'];
    $totalQuantityOrder = $row['total_quantity_order'];
    $partNumbers[$partNumber] = $totalQuantityOrder;
}

include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Material Requirements Planning (MRP)</h3>
            </div>
            <div class="panel-body">
                <p>Calculation Date: <?php echo date('Y-m-d'); ?></p>
            </div>
        </div>
    </div>
</div>

<?php if (isset($partNumbers)) : ?>
    <?php foreach ($partNumbers as $partNumber => $totalQuantityOrder) : ?>
        <?php
        $bom_structure = get_bom_structure($partNumber);
        $selected_product_name = get_product_name_by_part_number($partNumber);
        $calculationDate = date('Y-m-d'); // Current date

        // Loop through the BOM structure
        foreach ($bom_structure as $bom_item) {
            $childPartNumber = $bom_item['child_bom'];
            $childTotalRequirement = $bom_item['qty'] * $totalQuantityOrder;
            $childTotalRequirementKG = $childTotalRequirement / 1000;

            // Check if data for this child BOM already exists for the current date
            $checkExistingMRP = $db->query("SELECT * FROM mrp WHERE part_number = '{$childPartNumber}' AND calculation_date = '{$calculationDate}' LIMIT 1");

            if ($db->num_rows($checkExistingMRP) > 0) {
                // If data for this child BOM exists, UPDATE it
                $sql = "UPDATE mrp SET total_requirement = {$childTotalRequirement}, uom = '{$bom_item['uom']}', total_requirement_kg = {$childTotalRequirementKG} WHERE part_number = '{$childPartNumber}' AND calculation_date = '{$calculationDate}'";
                $db->query($sql);
            } else {
                // If data for this child BOM doesn't exist, INSERT it
                $sql = "INSERT INTO mrp (part_number, calculation_date, total_requirement, uom, total_requirement_kg) VALUES ('$childPartNumber', '$calculationDate', $childTotalRequirement, '{$bom_item['uom']}', $childTotalRequirementKG)";
                $db->query($sql);
            }
        }
        ?>

        <!-- Display MRP data for this part number -->
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">MRP for <?php echo htmlspecialchars($partNumber); ?> - <?php echo htmlspecialchars($selected_product_name); ?></h3>
                    </div>
                    <div class="panel-body">
<a href="#" id="exportCsvBtn" class="btn btn-primary">Export to CSV</a>
                        <table class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Child BOM</th>
                                    <th>Child Name</th>
                                    <th>Level</th>
                                    <th>Quantity</th>
                                    <th>Quantity Order</th>
                                    <th>Total Requirement</th>
                                    <th>UoM</th>
                                    <th>Total Requirement (KG)</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($bom_structure as $bom_item) : ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($bom_item['child_bom']); ?></td>
                                        <td><?php echo htmlspecialchars($bom_item['child_name']); ?></td>
                                        <td><?php echo htmlspecialchars($bom_item['level']); ?></td>
                                        <td><?php echo htmlspecialchars($bom_item['qty']); ?></td>
                                        <td><?php echo htmlspecialchars(number_format($totalQuantityOrder, 0, ',', '.')); ?></td>
                                        <td><?php echo htmlspecialchars(number_format($bom_item['qty'] * $totalQuantityOrder, 0, ',', '.')); ?></td>
                                        <td><?php echo htmlspecialchars($bom_item['uom']); ?></td>
                                        <td><?php echo htmlspecialchars(number_format(($bom_item['qty'] * $totalQuantityOrder) / 1000, 1, '.', '')); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
<?php endif; ?>


<script>
$(document).ready(function() {
    // Inisialisasi DataTables
    var table = $('#mrpTable').DataTable();

    // Tambahkan event listener ke tombol ekspor
    $('#exportCsvBtn').on('click', function() {
        // Ambil data dari tabel
        var data = table.data().toArray();

        // Buat data dalam format CSV
        var csvData = [];
        var headers = [];
        table.columns().every(function() {
            headers.push(this.header().textContent);
        });
        csvData.push(headers);
        $.each(data, function(index, value) {
            csvData.push(value);
        });

        // Konversi ke format CSV
        var csv = csvData.map(function(row) {
            return row.join(',');
        }).join('\n');

        // Buat tautan unduhan
        var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
        var url = window.URL.createObjectURL(blob);

        // Buat elemen tautan dan klik secara otomatis
        var a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = 'mrp_data.csv';
        document.body.appendChild(a);
        a.click();

        // Hapus elemen tautan
        window.URL.revokeObjectURL(url);
    });
});
</script>


<?php include_once('layouts/footer.php'); ?>
