<?php
include 'header.php';
require_once '../db/config.php';

// Check if the user is logged in as an admin
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$pdo = db();

// Handle status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order_id']) && isset($_POST['status'])) {
    $order_id = $_POST['order_id'];
    $status = $_POST['status'];

    $update_stmt = $pdo->prepare("UPDATE orders SET status = :status WHERE id = :order_id");
    $update_stmt->execute(['status' => $status, 'order_id' => $order_id]);

    // Redirect to the same page to prevent form resubmission
    header('Location: orders.php');
    exit;
}

// Fetch all orders with user information
$stmt = $pdo->query("
    SELECT o.id, o.total_price, o.status, o.created_at, u.name as user_name
    FROM orders o
    JOIN users u ON o.user_id = u.id
    ORDER BY o.created_at DESC
");
$orders = $stmt->fetchAll();

// Fetch all approved drivers
$driver_stmt = $pdo->query("SELECT id, full_name FROM drivers WHERE approval_status = 'approved'");
$approved_drivers = $driver_stmt->fetchAll();

$possible_statuses = ['Pending', 'Confirmed', 'Preparing', 'Out for Delivery', 'Delivered', 'Cancelled'];
?>

<div class="container mt-4">
    <h2>Order Management</h2>

    <table class="table table-striped">
        <thead>
            <tr>
                <th>Order ID</th>
                <th>Customer</th>
                <th>Total Price</th>
                <th>Order Date</th>
                <th>Status</th>
                <th>Update Status</th>
                <th>Assign Driver</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($orders as $order): ?>
                <tr>
                    <td><?php echo $order['id']; ?></td>
                    <td><?php echo htmlspecialchars($order['user_name']); ?></td>
                    <td>$<?php echo number_format($order['total_price'], 2); ?></td>
                    <td><?php echo $order['created_at']; ?></td>
                    <td><?php echo htmlspecialchars($order['status']); ?></td>
                    <td>
                        <form action="orders.php" method="POST" class="form-inline">
                            <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                            <div class="form-group">
                                <select name="status" class="form-control form-control-sm">
                                    <?php foreach ($possible_statuses as $status): ?>
                                        <option value="<?php echo $status; ?>" <?php echo ($order['status'] === $status) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($status); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary btn-sm ml-2">Update</button>
                        </form>
                    </td>
                    <td>
                        <?php
                        // Check if a driver is already assigned
                        $assignment_stmt = $pdo->prepare("SELECT d.full_name FROM driver_assignments da JOIN drivers d ON da.driver_id = d.id WHERE da.order_id = ?");
                        $assignment_stmt->execute([$order['id']]);
                        $assigned_driver = $assignment_stmt->fetch();
                        ?>
                        <?php if ($assigned_driver): ?>
                            <?php echo htmlspecialchars($assigned_driver['full_name']); ?>
                        <?php else: ?>
                            <form action="assign_driver.php" method="POST" class="form-inline">
                                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                <div class="form-group">
                                    <select name="driver_id" class="form-control form-control-sm">
                                        <option value="">Select Driver</option>
                                        <?php foreach ($approved_drivers as $driver): ?>
                                            <option value="<?php echo $driver['id']; ?>">
                                                <?php echo htmlspecialchars($driver['full_name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <button type="submit" class="btn btn-success btn-sm ml-2">Assign</button>
                            </form>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include 'footer.php'; ?>
