<?php
/**
 * Server Pickup Order API
 * Called when server picks up a ready order from the kitchen
 * Updates order status to served/collected
 */

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);

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

$order_id = (int)$input['order_id'];

try {
    // Verify order exists and belongs to this server
    $stmt = $conn->prepare("
        SELECT id, server_id, status FROM dine_in_orders WHERE id = ? AND server_id = ?
    ");
    $stmt->bind_param("ii", $order_id, $server_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Order not found or you do not have permission to pick up this order'
        ]);
        $stmt->close();
        exit;
    }
    
    $order = $result->fetch_assoc();
    $stmt->close();
    
    // Check if order has any ready items
    $items_stmt = $conn->prepare("
        SELECT COUNT(*) as ready_count FROM dine_in_order_items WHERE dine_in_order_id = ? AND status = 'ready'
    ");
    $items_stmt->bind_param("i", $order_id);
    $items_stmt->execute();
    $items_result = $items_stmt->get_result();
    $items_data = $items_result->fetch_assoc();
    $items_stmt->close();
    
    // If no ready items, don't allow pickup
    if ($items_data['ready_count'] === 0) {
        echo json_encode([
            'success' => false,
            'message' => 'Order has no items ready for pickup. Current status: ' . $order['status']
        ]);
        exit;
    }
    
    // Update only ready items to served status
    $stmt = $conn->prepare("
        UPDATE dine_in_order_items SET status = 'served' WHERE dine_in_order_id = ? AND status = 'ready'
    ");
    $stmt->bind_param("i", $order_id);
    $stmt->execute();
    $stmt->close();
    
    // Keep the order in kitchen flow while there are outstanding dishes.
    // Once all non-cancelled dishes are served, leave it ready for the billing flow.
    $check_stmt = $conn->prepare("
        SELECT COUNT(*) as remaining FROM dine_in_order_items WHERE dine_in_order_id = ? AND status NOT IN ('served', 'cancelled')
    ");
    $check_stmt->bind_param("i", $order_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    $check_data = $check_result->fetch_assoc();
    $check_stmt->close();
    
    $new_status = $check_data['remaining'] > 0 ? 'preparing' : 'ready';

    // Update order status without auto-completing the order here
    $stmt = $conn->prepare("
        UPDATE dine_in_orders SET status = ? WHERE id = ?
    ");
    $stmt->bind_param("si", $new_status, $order_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update order status: ' . $stmt->error);
    }
    
    $stmt->close();
    
    // Mark notifications as read
    $notif_stmt = $conn->prepare("
        UPDATE order_notifications SET is_read = 1 WHERE order_id = ? AND server_id = ?
    ");
    $notif_stmt->bind_param("ii", $order_id, $server_id);
    $notif_stmt->execute();
    $notif_stmt->close();
    
    echo json_encode([
        'success' => true,
        'message' => $new_status === 'ready'
            ? 'Items picked up successfully.'
            : 'Items picked up. More items are still being prepared.',
        'order_id' => $order_id,
        'status' => $new_status
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
