<?php
$page_title = 'View BOM';
require_once('includes/load.php');
page_require_level(3);
include_once('layouts/header.php');

$part_number = isset($_GET['part_number']) ? $db->escape($_GET['part_number']) : '';

if ($part_number) {
    // Fetch order quantity for the part number
    $order_query = "SELECT quantity_order FROM production_schedule WHERE part_number = '{$part_number}'";
    $order_result = $db->query($order_query);
    $order_data = $order_result->fetch_assoc();
    $order_quantity = $order_data['quantity_order'];

    // Fetch BOM details along with the product name
    $query = "SELECT b.child_bom, b.phantom_bom, b.level, b.qty, b.location, p.name 
              FROM bom_level b 
              LEFT JOIN products p ON b.child_bom = p.part_number 
              WHERE b.parent_bom = '{$part_number}'";
    $result = $db->query($query);

    echo "<h2>BOM for Part Number: {$part_number}</h2>";
    echo "<h3>Order Quantity: {$order_quantity}</h3>";
    echo "<table class='table table-bordered table-striped'>";
    echo "<thead>
            <tr>
                <th>Child BOM</th>
                <th>Name</th>
                <th>Quantity</th>
                <th>Requirement</th>
            </tr>
          </thead>
          <tbody>";

    while ($bom = $result->fetch_assoc()) {
        $child_bom = htmlspecialchars($bom['child_bom']);
        $name = htmlspecialchars($bom['name']);
        $phantom_bom = htmlspecialchars($bom['phantom_bom']);
        $level = htmlspecialchars($bom['level']);
        $qty = htmlspecialchars($bom['qty']);
        $location = htmlspecialchars($bom['location']);
        $requirement = $qty * $order_quantity;

        echo "<tr>
                <td>{$child_bom}</td>
                <td>{$name}</td>
                <td>{$qty}</td>
                <td>{$requirement}</td>
              </tr>";
    }

    echo "</tbody></table>";
} else {
    echo "<div class='alert alert-danger'>Invalid part number.</div>";
}

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