<?php
require('connection.inc.php');

date_default_timezone_set('Asia/Kolkata');


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $order_id = $_POST['order_id'];
    $order_status = $_POST['status'];
    $datetimeNow = date('Y-m-d H:i:s');

    // Build base query and parameters
    $sql = "UPDATE orders SET status = ?";
    $params = [$order_status];
    $types = "s";

    // Append shipped_on or delivered_on if status matches
    if ($order_status === 'Shipped') {
        $sql .= ", shipped_on = ?";
        $params[] = $datetimeNow;
        $types .= "s";
    }

    if ($order_status === 'Delivered') {
        $sql .= ", delivered_on = ?";
        $params[] = $datetimeNow;
        $types .= "s";
    }

    // Add WHERE clause
    $sql .= " WHERE order_id = ?";
    $params[] = $order_id;
    $types .= "s";

    // Prepare and bind
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);

    if ($stmt->execute()) {
        header("Location: orders.php?order_id=" . urlencode($order_id));
        exit;
    } else {
        echo "Failed to update order status.";
    }

    $stmt->close();
}
?>
