<?php
/**
 * Admin Servers API
 * Handles CRUD operations for server management
 */

session_start();
require 'config.php';

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

function hasColumn($table, $column) {
    global $conn;
    $tableEsc = $conn->real_escape_string($table);
    $columnEsc = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `" . $tableEsc . "` LIKE '" . $columnEsc . "'");
    return ($res && $res->num_rows > 0);
}

function ensureServerOrderLimitColumn() {
    global $conn;
    if (!hasColumn('servers', 'max_active_orders')) {
        @$conn->query("ALTER TABLE servers ADD COLUMN max_active_orders INT NOT NULL DEFAULT 1 AFTER shift_end");
    }
}

function supportsOnlineAssignmentTracking() {
    global $conn;
    return hasColumn('online_table_bookings', 'assigned_server_id');
}

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

ensureServerOrderLimitColumn();

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Fetch all servers
    $action = isset($_GET['action']) ? $_GET['action'] : 'list';
    
    if ($action === 'list') {
        try {
            $onlineCountExpr = "0";
            if (supportsOnlineAssignmentTracking()) {
                $onlineCountExpr = "(SELECT COUNT(*) 
                                     FROM online_table_bookings otb 
                                     LEFT JOIN bookings b ON b.id = otb.booking_id
                                     WHERE otb.assigned_server_id = servers.id
                                     AND otb.allocation_status = 'allocated'
                                     AND (b.id IS NULL OR b.status IN ('pending', 'confirmed', 'checked_in')))";
            }

            $sql = "SELECT id, name, employee_id, phone, status, shift_start, shift_end, rating, created_at,
                           COALESCE(max_active_orders, 1) AS max_active_orders,
                           (
                               (SELECT COUNT(*) FROM table_assignments ta WHERE ta.server_id = servers.id AND ta.status = 'assigned')
                               + " . $onlineCountExpr . "
                           ) AS active_orders_count
                    FROM servers 
                    ORDER BY name ASC";
            
            $result = $conn->query($sql);
            
            if ($result) {
                $servers = [];
                while ($row = $result->fetch_assoc()) {
                    $servers[] = $row;
                }
                
                echo json_encode([
                    'success' => true,
                    'data' => $servers,
                    'count' => count($servers)
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Database error: ' . $conn->error
                ]);
            }
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
    } elseif ($action === 'get' && isset($_GET['id'])) {
        $server_id = intval($_GET['id']);
        
        try {
            $sql = "SELECT *, COALESCE(max_active_orders, 1) AS max_active_orders FROM servers WHERE id = " . $server_id;
            $result = $conn->query($sql);
            
            if ($result && $result->num_rows > 0) {
                $server = $result->fetch_assoc();
                echo json_encode([
                    'success' => true,
                    'data' => $server
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Server not found'
                ]);
            }
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
    } elseif ($action === 'get_next_id') {
        // Get the next employee ID to be generated
        try {
            $count_sql = "SELECT COUNT(*) as count FROM servers";
            $count_result = $conn->query($count_sql);
            $count_row = $count_result->fetch_assoc();
            $next_id = $count_row['count'] + 1;
            $next_employee_id = 'SRV' . str_pad($next_id, 3, '0', STR_PAD_LEFT);
            
            echo json_encode([
                'success' => true,
                'next_id' => $next_employee_id,
                'count' => $count_row['count']
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error: ' . $e->getMessage()
            ]);
        }
    }
} elseif ($method === 'POST') {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($input['action'])) {
            echo json_encode([
                'success' => false,
                'message' => 'Action is required'
            ]);
            exit;
        }
        
        $action = $input['action'];
        
        if ($action === 'create') {
            // Validate required fields
            if (!isset($input['name'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Server name is required'
                ]);
                exit;
            }
            
            $name = trim($input['name']);
            $phone = isset($input['phone']) ? trim($input['phone']) : null;
            $status = isset($input['status']) ? trim($input['status']) : 'available';
            $shift_start = isset($input['shift_start']) ? trim($input['shift_start']) : null;
            $shift_end = isset($input['shift_end']) ? trim($input['shift_end']) : null;
            $max_active_orders = isset($input['max_active_orders']) ? intval($input['max_active_orders']) : 1;
            $password = isset($input['password']) ? trim($input['password']) : null;
            
            // Validate input
            if (empty($name)) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Server name is required'
                ]);
                exit;
            }
            if ($max_active_orders <= 0) {
                $max_active_orders = 1;
            }
            
            // Auto-generate employee_id (SRV001, SRV002, etc.)
            $count_sql = "SELECT COUNT(*) as count FROM servers";
            $count_result = $conn->query($count_sql);
            $count_row = $count_result->fetch_assoc();
            $next_id = $count_row['count'] + 1;
            $employee_id = 'SRV' . str_pad($next_id, 3, '0', STR_PAD_LEFT);
            
            // Hash password if provided
            $hashed_password = null;
            if ($password && !empty($password)) {
                $hashed_password = password_hash($password, PASSWORD_BCRYPT);
            }
            
            // Insert new server
            if ($hashed_password) {
                $sql = "INSERT INTO servers (name, employee_id, phone, status, shift_start, shift_end, max_active_orders, password) 
                        VALUES ('" . $conn->real_escape_string($name) . "', 
                                '" . $conn->real_escape_string($employee_id) . "', 
                                " . ($phone ? "'" . $conn->real_escape_string($phone) . "'" : "NULL") . ", 
                                '" . $conn->real_escape_string($status) . "',
                                " . ($shift_start ? "'" . $conn->real_escape_string($shift_start) . "'" : "NULL") . ",
                                " . ($shift_end ? "'" . $conn->real_escape_string($shift_end) . "'" : "NULL") . ",
                                " . $max_active_orders . ",
                                '" . $conn->real_escape_string($hashed_password) . "')";
            } else {
                $sql = "INSERT INTO servers (name, employee_id, phone, status, shift_start, shift_end, max_active_orders) 
                        VALUES ('" . $conn->real_escape_string($name) . "', 
                                '" . $conn->real_escape_string($employee_id) . "', 
                                " . ($phone ? "'" . $conn->real_escape_string($phone) . "'" : "NULL") . ", 
                                '" . $conn->real_escape_string($status) . "',
                                " . ($shift_start ? "'" . $conn->real_escape_string($shift_start) . "'" : "NULL") . ",
                                " . ($shift_end ? "'" . $conn->real_escape_string($shift_end) . "'" : "NULL") . ",
                                " . $max_active_orders . ")";
            }
            
            if ($conn->query($sql)) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Server created successfully',
                    'server_id' => $conn->insert_id
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error creating server: ' . $conn->error
                ]);
            }
            
        } elseif ($action === 'edit') {
            // Validate required fields
            if (!isset($input['server_id'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Server ID is required'
                ]);
                exit;
            }
            
            $server_id = intval($input['server_id']);
            $name = isset($input['name']) ? trim($input['name']) : null;
            $phone = isset($input['phone']) ? trim($input['phone']) : null;
            $status = isset($input['status']) ? trim($input['status']) : null;
            $shift_start = isset($input['shift_start']) ? trim($input['shift_start']) : null;
            $shift_end = isset($input['shift_end']) ? trim($input['shift_end']) : null;
            $max_active_orders = isset($input['max_active_orders']) ? intval($input['max_active_orders']) : null;
            $password = isset($input['password']) ? trim($input['password']) : null;
            
            // Build dynamic SQL
            $updates = [];
            
            if ($name !== null && !empty($name)) {
                $updates[] = "name = '" . $conn->real_escape_string($name) . "'";
            }
            if ($phone !== null) {
                $updates[] = "phone = " . ($phone ? "'" . $conn->real_escape_string($phone) . "'" : "NULL");
            }
            if ($status !== null) {
                $updates[] = "status = '" . $conn->real_escape_string($status) . "'";
            }
            if ($shift_start !== null) {
                $updates[] = "shift_start = " . ($shift_start ? "'" . $conn->real_escape_string($shift_start) . "'" : "NULL");
            }
            if ($shift_end !== null) {
                $updates[] = "shift_end = " . ($shift_end ? "'" . $conn->real_escape_string($shift_end) . "'" : "NULL");
            }
            if ($max_active_orders !== null) {
                if ($max_active_orders <= 0) {
                    $max_active_orders = 1;
                }
                $updates[] = "max_active_orders = " . $max_active_orders;
            }
            if ($password !== null && !empty($password)) {
                // Hash the password
                $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                $updates[] = "password = '" . $conn->real_escape_string($hashed_password) . "'";
            }
            
            if (empty($updates)) {
                echo json_encode([
                    'success' => false,
                    'message' => 'No fields to update'
                ]);
                exit;
            }
            
            $sql = "UPDATE servers SET " . implode(", ", $updates) . " WHERE id = " . $server_id;
            
            if ($conn->query($sql)) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Server updated successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error updating server: ' . $conn->error
                ]);
            }
            
        } elseif ($action === 'delete') {
            // Validate required fields
            if (!isset($input['server_id'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Server ID is required'
                ]);
                exit;
            }
            
            $server_id = intval($input['server_id']);
            
            // Check if server has active assignments
            $check_sql = "SELECT COUNT(*) as count FROM table_assignments WHERE server_id = " . $server_id . " AND status = 'assigned'";
            $check_result = $conn->query($check_sql);
            
            if ($check_result) {
                $check_data = $check_result->fetch_assoc();
                if ($check_data['count'] > 0) {
                    echo json_encode([
                        'success' => false,
                        'message' => 'Cannot delete server with active table assignments. Please reassign tables first.'
                    ]);
                    exit;
                }
            }

            if (supportsOnlineAssignmentTracking()) {
                $check_online_sql = "SELECT COUNT(*) as count
                                     FROM online_table_bookings otb
                                     LEFT JOIN bookings b ON b.id = otb.booking_id
                                     WHERE otb.assigned_server_id = " . $server_id . "
                                     AND otb.allocation_status = 'allocated'
                                     AND (b.id IS NULL OR b.status IN ('pending', 'confirmed', 'checked_in'))";
                $check_online_result = $conn->query($check_online_sql);
                if ($check_online_result) {
                    $check_online_data = $check_online_result->fetch_assoc();
                    if (intval($check_online_data['count']) > 0) {
                        echo json_encode([
                            'success' => false,
                            'message' => 'Cannot delete server with active online table assignments. Please release or reassign first.'
                        ]);
                        exit;
                    }
                }
            }
            
            // Delete server
            $sql = "DELETE FROM servers WHERE id = " . $server_id;
            
            if ($conn->query($sql)) {
                echo json_encode([
                    'success' => true,
                    'message' => 'Server deleted successfully'
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Error deleting server: ' . $conn->error
                ]);
            }
        }
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
}
?>
