<?php
$page_title = 'Input Order';
require_once('includes/load.php');
page_require_level(1);

$products = find_all('products'); // Retrieve products for dropdown

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selected_product = $db->escape($_POST['product']);
    $order_quantity = (int)$_POST['order_quantity'];

    // Calculate MRP using the existing function
    $mrp_results = calculate_material_requirements($selected_product, $order_quantity);

    // Calculate production schedule (you need to implement this)

    // Check if stock is available and adjust accordingly
    // (you need to implement this as well)

    // Save order details to database (you need to implement this)

    // Display results
    $msg = "Order placed successfully!<br>";
    $msg .= "Product: " . htmlspecialchars($selected_product) . "<br>";
    $msg .= "Order Quantity: " . $order_quantity . "<br>";
    $msg .= "Total MRP: " . $mrp_results['total_mrp'] . "<br>";
    // Display production schedule and other details here
}
include_once('layouts/header.php');
?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Input Order</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="input_order.php" class="clearfix">
                    <div class="form-group">
                        <label for="product">Select Product:</label>
                        <select class="form-control" name="product" id="product">
                            <option value="">Select Product</option>
                            <?php foreach ($products as $product) : ?>
                                <option value="<?php echo htmlspecialchars($product['part_number']); ?>"><?php echo htmlspecialchars($product['part_number'] . ' - ' . $product['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="order_quantity">Order Quantity:</label>
                        <input type="number" class="form-control" name="order_quantity" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Place Order</button>
                </form>
            </div>
        </div>
    </div>
</div>

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