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

session_start();
require 'config.php';

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

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    // Fetch all servers
    $action = isset($_GET['action']) ? $_GET['action'] : 'list';
    
    if ($action === 'list') {
        try {
            $sql = "SELECT id, name, employee_id, phone, status, shift_start, shift_end, rating, created_at 
                    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 * 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;
            $password = isset($input['password']) ? trim($input['password']) : null;
            
            // Validate input
            if (empty($name)) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Server name is required'
                ]);
                exit;
            }
            
            // 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, 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") . ",
                                '" . $conn->real_escape_string($hashed_password) . "')";
            } else {
                $sql = "INSERT INTO servers (name, employee_id, phone, status, shift_start, shift_end) 
                        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") . ")";
            }
            
            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;
            $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 ($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;
                }
            }
            
            // 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()
        ]);
    }
}
?>
