<?php
// Enable error reporting (optional)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include "db.php";

// Save AWB Number
if (isset($_POST['update_awb'])) {

    $order_id = $_POST['order_id'];
    $awb_number = $_POST['awb_number'];

    if ($order_id != "" && $awb_number != "") {

        $stmt = $pdo->prepare("UPDATE orders SET awb_number=? WHERE id=?");
        $stmt->execute([$awb_number, $order_id]);

        $msg = "<p style='color:green;'>AWB Number updated successfully!</p>";

    } else {
        $msg = "<p style='color:red;'>All fields are required!</p>";
    }
}

/* Fetch paid orders */
$paidOrders = $pdo->query("
    SELECT id, first_name, last_name, total_amount 
    FROM orders 
    WHERE payment_status = 'paid'
    ORDER BY id DESC
")->fetchAll(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>
<html>
<head>
    <title>Manual AWB Entry</title>
    <style>
        body {
            font-family: Arial;
            max-width: 500px;
            margin: 50px auto;
        }
        input, select, button {
            width: 100%;
            padding: 12px;
            margin: 8px 0;
        }
        button {
            background: #002344;
            color: #fff;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background: #003566;
        }
        h2 {
            text-align:center;
        }
    </style>
</head>
<body>

<h2>Manual AWB Number Update</h2>

<?php if (!empty($msg)) echo $msg; ?>

<form method="POST">

    <!-- Order selection dropdown -->
    <label>Select Paid Order</label>
    <select name="order_id" required>
        <option value="">-- Select Order --</option>

        <?php foreach ($paidOrders as $o) { ?>
            <option value="<?= $o['id'] ?>">
                Order #<?= $o['id'] ?> — <?= $o['first_name'] . " " . $o['last_name'] ?> — ₹<?= $o['total_amount'] ?>
            </option>
        <?php } ?>

    </select>

    <label>AWB Number</label>
    <input type="text" name="awb_number" required placeholder="Enter Blue Dart AWB Number">

    <button type="submit" name="update_awb">Save AWB Number</button>

</form>

</body>
</html>
