<?php
session_start();
include_once('../includes/db.php');

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = intval($_POST['order_id']);
    $new_status = $_POST['new_status'] ?? '';

    $valid_statuses = ['placed', 'shipped', 'delivered'];

    if (!in_array($new_status, $valid_statuses)) {
        header("Location: manage_orders.php?error=Invalid status value.");
        exit;
    }

    $stmt = $conn->prepare("UPDATE orders SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $new_status, $order_id);

    if ($stmt->execute()) {
        $stmt->close();
        header("Location: manage_orders.php?success=Order status updated.");
        exit;
    } else {
        $stmt->close();
        header("Location: manage_orders.php?error=Failed to update status.");
        exit;
    }
} else {
    header("Location: manage_orders.php?error=Invalid request.");
    exit;
}
