<?php
/**
 * Server API
 * Handles server-specific operations: viewing assigned tables, taking orders, etc.
 */

session_start();
require 'config.php';

header('Content-Type: application/json');

// Check server authentication
if (!isset($_SESSION['server_id'])) {
    http_response_code(401);
    sendResponse(false, 'Unauthorized access', null);
}

$server_id = $_SESSION['server_id'];
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {
    case 'get_assigned_tables':
        getAssignedTables();
        break;
    case 'get_table_orders':
        getTableOrders();
        break;
    case 'get_table_details':
        getTableDetails();
        break;
    case 'update_table_status':
        updateTableStatus();
        break;
    case 'get_order_statistics':
        getOrderStatistics();
        break;
    default:
        sendResponse(false, 'Invalid action', null);
}

/**
 * Get all tables assigned to the server
 */
function getAssignedTables() {
    global $conn, $server_id;
    
    $sql = "SELECT DISTINCT 
            rt.id,
            rt.table_number,
            rt.capacity,
            rt.floor,
            rt.section,
            rt.status,
            ta.status as assignment_status,
            ta.number_of_guests,
            ta.assigned_at,
            COUNT(DISTINCT o.id) as order_count,
            SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
            SUM(CASE WHEN o.status = 'completed' THEN 1 ELSE 0 END) as completed_orders
            FROM table_assignments ta
            INNER JOIN restaurant_tables rt ON ta.table_id = rt.id
            LEFT JOIN orders o ON o.table_id = rt.id AND o.status IN ('pending', 'completed')
            WHERE ta.server_id = " . intval($server_id) . " AND ta.status = 'assigned'
            GROUP BY rt.id
            ORDER BY rt.table_number";

    $result = $conn->query($sql);

    if ($result && $result->num_rows > 0) {
        $tables = [];
        while ($row = $result->fetch_assoc()) {
            // Convert numeric strings to integers
            $row['capacity'] = intval($row['capacity']);
            $row['floor'] = intval($row['floor']);
            $row['number_of_guests'] = intval($row['number_of_guests'] ?? 0);
            $row['order_count'] = intval($row['order_count'] ?? 0);
            $row['pending_orders'] = intval($row['pending_orders'] ?? 0);
            $row['completed_orders'] = intval($row['completed_orders'] ?? 0);
            
            $tables[] = $row;
        }
        sendResponse(true, 'Tables retrieved', $tables);
    } else {
        sendResponse(true, 'No tables assigned', []);
    }
}

/**
 * Get orders for a specific table
 */
function getTableOrders() {
    global $conn, $server_id;
    
    $table_id = isset($_GET['table_id']) ? intval($_GET['table_id']) : 0;
    
    if (!$table_id) {
        sendResponse(false, 'Table ID is required', null);
    }

    // Verify server has access to this table
    $verify_sql = "SELECT id FROM table_assignments 
                   WHERE table_id = " . $table_id . " 
                   AND server_id = " . $server_id . " 
                   AND status = 'assigned'";
    $verify_result = $conn->query($verify_sql);

    if (!$verify_result || $verify_result->num_rows === 0) {
        http_response_code(403);
        sendResponse(false, 'Access denied to this table', null);
    }

    $sql = "SELECT o.* FROM orders o
            WHERE o.table_id = " . $table_id . "
            ORDER BY o.created_at DESC
            LIMIT 50";

    $result = $conn->query($sql);

    if ($result) {
        $orders = [];
        while ($row = $result->fetch_assoc()) {
            $orders[] = $row;
        }
        sendResponse(true, 'Orders retrieved', $orders);
    } else {
        sendResponse(false, 'Error retrieving orders', null);
    }
}

/**
 * Get detailed information about a specific table
 */
function getTableDetails() {
    global $conn, $server_id;
    
    $table_id = isset($_GET['table_id']) ? intval($_GET['table_id']) : 0;
    
    if (!$table_id) {
        sendResponse(false, 'Table ID is required', null);
    }

    // Verify server has access to this table
    $verify_sql = "SELECT id FROM table_assignments 
                   WHERE table_id = " . $table_id . " 
                   AND server_id = " . $server_id . " 
                   AND status = 'assigned'";
    $verify_result = $conn->query($verify_sql);

    if (!$verify_result || $verify_result->num_rows === 0) {
        http_response_code(403);
        sendResponse(false, 'Access denied to this table', null);
    }

    $sql = "SELECT rt.*, 
            ta.number_of_guests,
            ta.assigned_at,
            COUNT(DISTINCT o.id) as total_orders,
            SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) as pending_orders
            FROM restaurant_tables rt
            LEFT JOIN table_assignments ta ON rt.id = ta.table_id AND ta.server_id = " . $server_id . "
            LEFT JOIN orders o ON rt.id = o.table_id
            WHERE rt.id = " . $table_id . "
            GROUP BY rt.id";

    $result = $conn->query($sql);

    if ($result && $result->num_rows > 0) {
        $table = $result->fetch_assoc();
        sendResponse(true, 'Table details retrieved', $table);
    } else {
        sendResponse(false, 'Table not found', null);
    }
}

/**
 * Update table status
 */
function updateTableStatus() {
    global $conn, $server_id;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'Only POST method allowed', null);
    }

    $data = json_decode(file_get_contents("php://input"), true);
    
    $table_id = isset($data['table_id']) ? intval($data['table_id']) : 0;
    $new_status = isset($data['status']) ? $conn->real_escape_string($data['status']) : '';
    
    if (!$table_id || !$new_status) {
        sendResponse(false, 'Table ID and status are required', null);
    }

    // Verify server has access to this table
    $verify_sql = "SELECT id FROM table_assignments 
                   WHERE table_id = " . $table_id . " 
                   AND server_id = " . $server_id . " 
                   AND status = 'assigned'";
    $verify_result = $conn->query($verify_sql);

    if (!$verify_result || $verify_result->num_rows === 0) {
        http_response_code(403);
        sendResponse(false, 'Access denied to this table', null);
    }

    // Valid statuses
    $valid_statuses = ['available', 'occupied', 'reserved', 'maintenance'];
    if (!in_array($new_status, $valid_statuses)) {
        sendResponse(false, 'Invalid status', null);
    }

    $sql = "UPDATE restaurant_tables 
            SET status = '" . $new_status . "', updated_at = NOW()
            WHERE id = " . $table_id;

    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Table status updated', null);
    } else {
        sendResponse(false, 'Error updating table status: ' . $conn->error, null);
    }
}

/**
 * Get order statistics for the server
 */
function getOrderStatistics() {
    global $conn, $server_id;
    
    $sql = "SELECT 
            COUNT(DISTINCT ta.table_id) as assigned_tables,
            COUNT(DISTINCT o.id) as total_orders,
            SUM(CASE WHEN o.status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
            SUM(CASE WHEN o.status = 'completed' THEN 1 ELSE 0 END) as completed_orders,
            SUM(CASE WHEN o.status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_orders,
            COUNT(DISTINCT CASE WHEN ta.status = 'assigned' THEN ta.table_id END) as active_tables
            FROM table_assignments ta
            LEFT JOIN orders o ON o.table_id IN (
                SELECT table_id FROM table_assignments 
                WHERE server_id = " . intval($server_id) . " AND status = 'assigned'
            )
            WHERE ta.server_id = " . intval($server_id);

    $result = $conn->query($sql);

    if ($result && $result->num_rows > 0) {
        $stats = $result->fetch_assoc();
        
        // Convert to integers
        $stats['assigned_tables'] = intval($stats['assigned_tables'] ?? 0);
        $stats['total_orders'] = intval($stats['total_orders'] ?? 0);
        $stats['pending_orders'] = intval($stats['pending_orders'] ?? 0);
        $stats['completed_orders'] = intval($stats['completed_orders'] ?? 0);
        $stats['cancelled_orders'] = intval($stats['cancelled_orders'] ?? 0);
        $stats['active_tables'] = intval($stats['active_tables'] ?? 0);
        
        sendResponse(true, 'Statistics retrieved', $stats);
    } else {
        sendResponse(false, 'Error retrieving statistics', null);
    }
}

?>
