<?php
include 'includes/auth.php';
include 'db.php';

$order_id = intval($_GET['order_id'] ?? 0);
$new_status = $_GET['status'] ?? '';

if(!$order_id || !$new_status){
    echo "<script>alert('Invalid request'); window.location='restaurant_orders_list.php';</script>";
    exit;
}

// Allowed statuses
$allowed_status = ['IN_KITCHEN', 'READY', 'SERVED'];
if(!in_array($new_status, $allowed_status)){
    echo "<script>alert('Invalid status'); window.location='restaurant_orders_list.php';</script>";
    exit;
}

// Update order status
$conn->query("UPDATE restaurant_orders SET status='$new_status' WHERE id=$order_id");

// Optionally, notify back office or waiter
// Example notification (optional)
/*
$conn->query("INSERT INTO notifications(order_id, message, created_at) 
              VALUES($order_id, 'Order status updated to $new_status', NOW())");
*/

// If order is served, redirect to payment processing
if($new_status === 'SERVED'){
    header("Location: restaurant_order_payment.php?order_id=$order_id");
    exit;
}

// Otherwise, go back to order view
echo "<script>alert('✅ Order status updated to $new_status'); window.location='restaurant_order_view.php?order_id=$order_id';</script>";
exit;
