<?php
/**
 * Kitchen Update Order Status API
 * Allows kitchen staff to update order/item status (preparing, ready, etc.)
 */

session_start();
header('Content-Type: application/json');
require_once 'config.php';

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['order_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request. Missing order_id.']);
    exit;
}

$order_id = (int)$input['order_id'];
$action = isset($input['action']) ? $input['action'] : null;
$item_id = isset($input['item_id']) ? (int)$input['item_id'] : null;
$new_status = isset($input['status']) ? $input['status'] : null;

if (!$action) {
    echo json_encode(['success' => false, 'message' => 'Action not specified']);
    exit;
}

try {
    $valid_statuses = ['pending', 'preparing', 'ready'];
    
    if ($action === 'start_preparation') {
        // Start preparing the order - update order status to 'preparing'
        $verify_sql = "SELECT id, status FROM dine_in_orders WHERE id = $order_id";
        $verify_result = $conn->query($verify_sql);
        
        if (!$verify_result || $verify_result->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Order not found']);
            exit;
        }
        
        // Update order status to preparing
        $update_order_sql = "UPDATE dine_in_orders SET status = 'preparing' WHERE id = $order_id";
        
        if (!$conn->query($update_order_sql)) {
            throw new Exception('Failed to update order status: ' . $conn->error);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Order preparation started',
            'order_id' => $order_id,
            'status' => 'preparing'
        ]);
        
    } elseif ($action === 'update_item_status') {
        // Update individual item status
        if (!$item_id || !$new_status) {
            echo json_encode(['success' => false, 'message' => 'Missing item_id or status']);
            exit;
        }
        
        if (!in_array($new_status, $valid_statuses)) {
            echo json_encode(['success' => false, 'message' => 'Invalid status value']);
            exit;
        }
        
        // Verify item belongs to this order
        $verify_sql = "SELECT id, item_name, quantity FROM dine_in_order_items WHERE id = $item_id AND dine_in_order_id = $order_id";
        $verify_result = $conn->query($verify_sql);
        
        if (!$verify_result || $verify_result->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Item not found in this order']);
            exit;
        }
        
        $item_data = $verify_result->fetch_assoc();
        
        // Update item status
        $update_sql = "UPDATE dine_in_order_items SET status = '$new_status' WHERE id = $item_id";
        
        if (!$conn->query($update_sql)) {
            throw new Exception('Failed to update item status: ' . $conn->error);
        }
        
        // Check if all items are ready
        $check_ready_sql = "SELECT COUNT(*) as pending_count FROM dine_in_order_items WHERE dine_in_order_id = $order_id AND status != 'ready'";
        $check_result = $conn->query($check_ready_sql);
        $check_data = $check_result->fetch_assoc();
        
        $order_status = $check_data['pending_count'] > 0 ? 'preparing' : 'ready';
        
        // Update order status accordingly
        $update_order_sql = "UPDATE dine_in_orders SET status = '$order_status' WHERE id = $order_id";
        $conn->query($update_order_sql);
        
        // Send notification to server when item becomes ready
        if ($new_status === 'ready') {
            $order_sql = "SELECT server_id FROM dine_in_orders WHERE id = $order_id";
            $order_result = $conn->query($order_sql);
            if ($order_result && $order_result->num_rows > 0) {
                $order_data = $order_result->fetch_assoc();
                $server_id = $order_data['server_id'];
                
                // Ensure notification table exists
                $create_table_sql = "CREATE TABLE IF NOT EXISTS order_notifications (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    order_id INT NOT NULL,
                    server_id INT NOT NULL,
                    item_id INT,
                    notification_type VARCHAR(50) DEFAULT 'item_ready',
                    message TEXT,
                    is_read INT DEFAULT 0,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (order_id) REFERENCES dine_in_orders(id) ON DELETE CASCADE,
                    FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE
                )";
                $conn->query($create_table_sql);
                
                // Insert notification for individual item ready
                $item_name_safe = addslashes($item_data['item_name']);
                $message = "Item \"{$item_name_safe}\" is ready for serving!";
                $notification_sql = "INSERT INTO order_notifications (order_id, server_id, item_id, notification_type, message, is_read) 
                                     VALUES ($order_id, $server_id, $item_id, 'item_ready', '$message', 0)";
                $conn->query($notification_sql);
            }
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Item status updated successfully',
            'item_id' => $item_id,
            'item_name' => $item_data['item_name'],
            'item_status' => $new_status,
            'order_status' => $order_status
        ]);
        
    } elseif ($action === 'mark_order_ready') {
        // Mark entire order as ready
        // First verify order exists
        $verify_sql = "SELECT id, status FROM dine_in_orders WHERE id = $order_id";
        $verify_result = $conn->query($verify_sql);
        
        if (!$verify_result || $verify_result->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'Order not found']);
            exit;
        }
        
        $order_data = $verify_result->fetch_assoc();
        
        // Update all items to ready
        $update_items_sql = "UPDATE dine_in_order_items SET status = 'ready' WHERE dine_in_order_id = $order_id AND status != 'ready'";
        $conn->query($update_items_sql);
        
        // Update order status to ready
        $update_order_sql = "UPDATE dine_in_orders SET status = 'ready' WHERE id = $order_id";
        
        if (!$conn->query($update_order_sql)) {
            throw new Exception('Failed to update order status: ' . $conn->error);
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Order marked as ready for serving',
            'order_id' => $order_id,
            'status' => 'ready'
        ]);
        
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
