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

// Retrieve data MRP_SO from the database (assuming you have a table named mrp_so)
$mrpSoResult = $db->query("SELECT * FROM mrp_so");

// Initialize array to store total material requirements
$totalMaterialRequirements = array();

// Loop through each MRP_SO entry to calculate total material requirements
while ($row = $db->fetch_assoc($mrpSoResult)) {
    $partNumber = $row['part_number'];
    $quantityOrder = $row['quantity_order'];
    $deliveryDate = $row['delivery_date'];

    // Retrieve BOM structure for the part number
    $bomStructure = get_bom_structure($partNumber);

    // Calculate material requirements based on BOM and quantity order
    foreach ($bomStructure as $bomItem) {
        $childPartNumber = $bomItem['child_bom'];
        $qty = $bomItem['qty'];

        // Calculate material requirements based on quantity order and BOM quantity
        $materialRequirement = $quantityOrder * $qty;

        // Add material requirement to totalMaterialRequirements array
        if (!isset($totalMaterialRequirements[$childPartNumber])) {
            $totalMaterialRequirements[$childPartNumber] = 0;
        }
        $totalMaterialRequirements[$childPartNumber] += $materialRequirement;
    }
}

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 Summary</h3>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>Part Number</th>
                            <th>Total Requirement</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($totalMaterialRequirements as $partNumber => $totalRequirement) : ?>
                            <tr>
                                <td><?php echo htmlspecialchars($partNumber); ?></td>
                                <td><?php echo htmlspecialchars(number_format($totalRequirement, 0, ',', '.')); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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