<?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';

        if ($current_status === 'served') {
            echo json_encode(['success' => false, 'message' => 'Served items cannot be changed']);
            exit;
        }
        
        // 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);
    }
    
    $status_summary_sql = "
        SELECT
            SUM(CASE WHEN status IN ('pending', 'preparing') THEN 1 ELSE 0 END) AS preparing_count
        FROM dine_in_order_items
        WHERE dine_in_order_id = $order_id
    ";
    $status_summary_result = $conn->query($status_summary_sql);
    $status_summary = $status_summary_result ? $status_summary_result->fetch_assoc() : null;

    $order_status = 'ready';
    if ($status_summary) {
        $preparing_count = (int)($status_summary['preparing_count'] ?? 0);
        if ($preparing_count > 0) {
            $order_status = 'preparing';
        }
    }

    $update_order_sql = "UPDATE dine_in_orders SET status = '$order_status', updated_at = NOW() WHERE id = $order_id";
    if (!$conn->query($update_order_sql)) {
        throw new Exception('Failed to update order status: ' . $conn->error);
    }

    error_log("Order $order_id: Item status updated to $new_status (served=$served).");
    
    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()
    ]);
}
?>
