<?php
require_once('includes/load.php');
page_require_level(3);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $noOrder = $db->escape($_POST['no_order']);
    $partNumber = $db->escape($_POST['part_number']);
    $output = $db->escape($_POST['output']);
    $outputDate = $db->escape($_POST['output_date']);

    // Mengambil balance dari database
    $balanceQuery = "SELECT ps.quantity_order - IFNULL(os.output, 0) AS balance
                     FROM production_schedule ps
                     LEFT JOIN (
                         SELECT part_number, SUM(output) AS output
                         FROM output_schedule
                         GROUP BY part_number
                     ) os ON ps.part_number = os.part_number
                     WHERE ps.part_number = '$partNumber'";
    $balanceResult = $db->query($balanceQuery);
    $balanceRow = $balanceResult->fetch_assoc();
    $balance = $balanceRow['balance'];

    if ($output <= $balance) {
        $query = "INSERT INTO output_schedule (no_order, part_number, output, output_date) VALUES ('$noOrder', '$partNumber', '$output', '$outputDate')";
        $result = $db->query($query);

        if ($result) {
            header("Location: output_schedule.php?success=1");
            exit();
        } else {
            // Penanganan kesalahan jika diperlukan
            echo "Error: " . $db->error;
        }
    } else {
        $errorMsg = "Output cannot exceed the available balance.";
    }
}

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

<div class="row">
    <div class="col-md-12">
        <h2>Input Output Progress</h2>
        <?php
        if (isset($_GET['success'])) {
            echo '<div class="alert alert-success">Output added successfully.</div>';
        }
        if (isset($errorMsg)) {
            echo '<div class="alert alert-danger">' . htmlspecialchars($errorMsg) . '</div>';
        }
        ?>
        <form method="post" action="output_schedule.php">
            <div class="form-group">
                <label for="no_order">No Order</label>
                <input type="text" class="form-control" id="no_order" name="no_order" required>
            </div>
            <div class="form-group">
                <label for="part_number">Part Number</label>
                <select class="form-control" id="part_number" name="part_number" required>
                    <option value="">Select Part Number</option>
                    <?php
                    $query = "SELECT ps.no_order, ps.part_number, p.name, ps.quantity_order, (ps.quantity_order - IFNULL(os.output, 0)) AS balance
                              FROM production_schedule ps
                              JOIN products p ON ps.part_number = p.part_number
                              LEFT JOIN (
                                  SELECT part_number, SUM(output) AS output
                                  FROM output_schedule
                                  GROUP BY part_number
                              ) os ON ps.part_number = os.part_number";
                    $result = $db->query($query);
                    while ($row = $result->fetch_assoc()) {
                        if ($row['balance'] > 0) {
                            echo '<option value="' . htmlspecialchars($row['part_number']) . '">' .
                                htmlspecialchars($row['no_order']) . ' - ' . htmlspecialchars($row['part_number']) . ' - ' .
                                htmlspecialchars($row['name']) .
                                ' (Quantity: ' . htmlspecialchars($row['quantity_order']) . ', Balance: ' . htmlspecialchars($row['balance']) . ')' .
                                '</option>';
                        }
                    }
                    ?>
                </select>
            </div>
            <div class="form-group">
                <label for="output">Output</label>
                <input type="number" class="form-control" id="output" name="output" required>
            </div>
            <div class="form-group">
                <label for="output_date">Output Date</label>
                <input type="date" class="form-control" id="output_date" name="output_date" required>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</div>

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