<?php
/**
 * Server Update Item Served Status API
 * Allows servers to toggle the served status of order items
 * Updates the 'status' field in dine_in_order_items to 'served' or 'pending'
 * IMPORTANT: Now uses specific row ID to handle reorders correctly
 */

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

// Check server authentication
if (!isset($_SESSION['server_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$server_id = $_SESSION['server_id'];
$input = json_decode(file_get_contents('php://input'), true);

// Support both old (item_id only) and new (row_id specific) formats for backwards compatibility
$has_row_id = isset($input['row_id']);
if (!$input || !isset($input['order_id']) || !isset($input['served']) || (!isset($input['item_id']) && !$has_row_id)) {
    echo json_encode(['success' => false, 'message' => 'Invalid request. Missing required fields.']);
    exit;
}

$order_id = (int)$input['order_id'];
$served = (bool)$input['served'];
$row_id = $has_row_id ? (int)$input['row_id'] : null;
$item_id = isset($input['item_id']) ? (int)$input['item_id'] : null;

try {
    // Verify order ownership
    $verify_sql = "SELECT id FROM dine_in_orders WHERE id = $order_id AND server_id = $server_id";
    $result = $conn->query($verify_sql);
    
    if (!$result || $result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Order not found or not assigned to you']);
        exit;
    }
    
    // Update item status based on served flag
    // When marking as served: set to 'served'
    // When marking as not served: keep it in its previous non-served status
    
    if ($row_id) {
        // Get current status first to handle transitions properly
        $status_check_sql = "SELECT status FROM dine_in_order_items WHERE id = $row_id AND dine_in_order_id = $order_id";
        $status_result = $conn->query($status_check_sql);
        $current_status_data = $status_result->fetch_assoc();
        $current_status = $current_status_data ? $current_status_data['status'] : 'pending';
        
        // When served=true, set to 'served'
        // When served=false, revert to 'pending' (unless it's 'ready' or 'preparing', then keep it)
        if ($served) {
            $new_status = 'served';
        } else {
            // If currently served, mark as pending; otherwise keep current status
            $new_status = ($current_status === 'served') ? 'pending' : $current_status;
        }
        
        // Update ONLY the specific row by its primary key
        // This prevents updating served items when reordering the same item
        $update_sql = "UPDATE dine_in_order_items SET status = '$new_status' WHERE id = $row_id AND dine_in_order_id = $order_id";
        error_log("Updating specific row $row_id in order $order_id from status $current_status to $new_status");
    } else {
        // Backwards compatibility: update all items with this item_id
        $new_status = $served ? 'served' : 'pending';
        $update_sql = "UPDATE dine_in_order_items SET status = '$new_status' WHERE dine_in_order_id = $order_id AND item_id = $item_id";
        error_log("Updating all rows with item_id $item_id in order $order_id to status $new_status (legacy mode)");
    }
    
    if (!$conn->query($update_sql)) {
        throw new Exception('Failed to update item status: ' . $conn->error);
    }
    
    // IMPORTANT: Do NOT mark order as 'completed' when items are served
    // Order should only be marked as 'completed' AFTER billing is done and payment confirmed
    // The order will be marked as 'completed' by the billing system (manager_pos_api.php)
    // 
    // Items can be toggled between 'served' and 'pending' for correction purposes,
    // but this does NOT affect the order completion status
    error_log("Order $order_id: Item status updated to $new_status (served=$served). Order will be completed during billing process.");
    
    echo json_encode([
        'success' => true,
        'message' => 'Item status updated successfully',
        'order_id' => $order_id,
        'item_id' => $item_id,
        'row_id' => $row_id,
        'served' => $served,
        'status' => $new_status
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
