<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="Granny Restaurant">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Servers Management - Granny Restaurant">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">

    <!-- Font Awesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Bootstrap CSS -->
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">

    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <title>Servers Management - Granny Restaurant</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 0;
            z-index: 1000;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 30px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            text-align: center;
            border-bottom: 3px solid #d4a574;
        }

        .sidebar-logo {
            font-size: 40px;
            margin-bottom: 10px;
            display: block;
        }

        .sidebar-header h2 {
            font-size: 20px;
            margin: 10px 0 5px 0;
            font-weight: 700;
        }

        .sidebar-header p {
            font-size: 12px;
            opacity: 0.9;
            margin: 0;
        }

        .sidebar-menu {
            list-style: none;
            padding: 20px 0;
        }

        .sidebar-menu li {
            margin: 0;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 25px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 500;
            border-left: 3px solid transparent;
        }

        .sidebar-menu a:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-left-color: #d4a574;
        }

        .sidebar-menu a.active {
            background: rgba(255, 255, 255, 0.15);
            color: white;
            border-left-color: #d4a574;
        }

        .sidebar-menu i {
            width: 20px;
            text-align: center;
            font-size: 16px;
        }

        .logout-btn {
            width: calc(100% - 40px);
            margin: 20px;
            padding: 12px;
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
        }

        /* Top Header */
        .topbar {
            position: fixed;
            top: 0;
            left: 280px;
            right: 0;
            height: 70px;
            background: white;
            border-bottom: 1px solid #e8e8e8;
            padding: 0 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 999;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .topbar-title {
            font-size: 24px;
            font-weight: 700;
            color: #333;
        }

        .mobile-title {
            display: none;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .topbar-user {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 16px;
        }

        /* Main Content */
        .main-content {
            margin-left: 280px;
            margin-top: 70px;
            padding: 30px;
            min-height: calc(100vh - 70px);
        }

        .content-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 30px;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .content-header h1 {
            font-size: 28px;
            font-weight: 700;
            color: #333;
        }

        .btn-primary {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        /* Table Styles */
        .servers-table {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .servers-table table {
            width: 100%;
            border-collapse: collapse;
        }

        .servers-table thead {
            background: linear-gradient(135deg, #f8f9fa 0%, #f0f1f3 100%);
            border-bottom: 3px solid #d4a574;
        }

        .servers-table th {
            padding: 18px;
            text-align: left;
            font-weight: 700;
            color: #333;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .servers-table tbody tr {
            border-bottom: 1px solid #e8e8e8;
            transition: all 0.3s ease;
        }

        .servers-table tbody tr:hover {
            background: #f8f9fa;
        }

        .servers-table td {
            padding: 15px 18px;
            font-size: 14px;
            color: #333;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: capitalize;
        }

        .status-available {
            background: #d4edda;
            color: #155724;
        }

        .status-busy {
            background: #fff3cd;
            color: #856404;
        }

        .status-break {
            background: #cce5ff;
            color: #004085;
        }

        .status-offline {
            background: #f8d7da;
            color: #721c24;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-icon {
            width: 36px;
            height: 36px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .btn-edit {
            background: #d4a574;
            color: white;
        }

        .btn-edit:hover {
            background: #8b6f47;
            transform: translateY(-2px);
        }

        .btn-delete {
            background: #e74c3c;
            color: white;
        }

        .btn-delete:hover {
            background: #c0392b;
            transform: translateY(-2px);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state i {
            font-size: 64px;
            color: #ddd;
            margin-bottom: 20px;
            display: block;
        }

        .empty-state p {
            font-size: 16px;
            margin-bottom: 10px;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            padding: 20px;
        }

        .modal.show {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }

        /* Ensure SweetAlert is always on top */
        .swal2-container {
            z-index: 2000 !important;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 10px;
            width: 100%;
            max-width: 400px;
            max-height: 85vh;
            overflow-y: auto;
            box-shadow: 0 5px 30px rgba(0, 0, 0, 0.2);
        }

        .modal-header {
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 20px;
            color: #333;
        }

        .form-group {
            margin-bottom: 12px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
            font-size: 14px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .modal-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 15px;
        }

        .btn-cancel {
            background: #f0f0f0;
            color: #333;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-cancel:hover {
            background: #e0e0e0;
        }

        .btn-submit {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .loading i {
            font-size: 32px;
            margin-right: 10px;
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #333;
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .sidebar {
                width: 250px;
            }

            .topbar {
                left: 250px;
            }

            .main-content {
                margin-left: 250px;
            }

            .content-header {
                flex-wrap: wrap;
                gap: 15px;
            }

            .content-header h1 {
                flex: 1 1 auto;
                font-size: 24px;
            }

            .servers-table th {
                padding: 14px;
                font-size: 12px;
            }

            .servers-table td {
                padding: 12px 14px;
                font-size: 13px;
            }
        }

        @media (max-width: 768px) {
            /* Hide sidebar on tablet and mobile */
            .sidebar {
                transform: translateX(-100%);
                width: 280px;
                transition: transform 0.3s ease;
                box-shadow: 2px 0 10px rgba(0, 0, 0, 0.2);
            }

            .sidebar.show {
                transform: translateX(0);
            }

            /* Show hamburger menu */
            .hamburger {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .topbar {
                left: 0;
                padding: 0 15px;
            }

            .topbar-title {
                font-size: 18px;
            }

            .mobile-title {
                display: inline !important;
            }

            .responsive-hidden {
                display: none !important;
            }

            .main-content {
                margin-left: 0;
                margin-top: 70px;
                padding: 15px;
            }

            .content-header {
                flex-direction: column;
                gap: 12px;
            }

            .content-header h1 {
                font-size: 22px;
                margin-bottom: 0;
            }

            .content-header button {
                width: 100%;
            }

            /* Make table responsive with horizontal scroll */
            .servers-table {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .servers-table table {
                min-width: 600px;
            }

            .servers-table th,
            .servers-table td {
                padding: 10px 12px;
                font-size: 12px;
            }

            .modal-content {
                width: calc(100% - 40px);
                max-width: 90%;
                margin: auto;
            }

            .action-buttons {
                flex-direction: column;
                gap: 5px;
            }

            .btn-icon {
                width: 32px;
                height: 32px;
                font-size: 12px;
            }

            .topbar-right {
                gap: 10px;
            }

            .topbar-user {
                gap: 8px;
            }

            .user-avatar {
                width: 36px;
                height: 36px;
                font-size: 14px;
            }

            #userInfo {
                display: none;
            }
        }

        @media (max-width: 480px) {
            .topbar {
                padding: 0 10px;
                height: 60px;
            }

            .topbar-title {
                font-size: 16px;
            }

            .mobile-title {
                display: inline !important;
            }

            .responsive-hidden {
                display: none !important;
            }

            .main-content {
                padding: 10px;
                margin-top: 60px;
            }

            .content-header {
                padding: 15px 10px;
            }

            .content-header h1 {
                font-size: 20px;
            }

            .content-header button {
                padding: 10px 15px;
                font-size: 12px;
            }

            .btn-primary {
                padding: 10px 15px;
                font-size: 12px;
            }

            .servers-table th,
            .servers-table td {
                padding: 8px 10px;
                font-size: 11px;
            }

            .status-badge {
                padding: 4px 8px;
                font-size: 10px;
            }

            .modal-content {
                padding: 20px;
            }

            .modal-header {
                font-size: 18px;
                margin-bottom: 15px;
            }

            .form-group {
                margin-bottom: 10px;
            }

            .form-group label {
                font-size: 12px;
                margin-bottom: 6px;
            }

            .form-group input,
            .form-group select {
                padding: 8px 10px;
                font-size: 13px;
            }

            .modal-actions {
                gap: 8px;
                margin-top: 12px;
            }

            .btn-cancel,
            .btn-submit {
                padding: 8px 15px;
                font-size: 12px;
                flex: 1;
            }

            .servers-table table {
                min-width: 500px;
            }

            .action-buttons {
                gap: 3px;
            }

            .btn-icon {
                width: 28px;
                height: 28px;
                font-size: 11px;
            }

            .sidebar-header {
                padding: 20px 15px;
            }

            .sidebar-header h2 {
                font-size: 18px;
            }

            .sidebar-logo {
                font-size: 32px;
            }

            .sidebar-menu a {
                padding: 12px 15px;
                gap: 12px;
                font-size: 13px;
            }

            .logout-btn {
                font-size: 12px;
                padding: 10px;
            }
        }

        /* Mobile overlay for sidebar */
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        .sidebar-overlay.show {
            display: block;
        }

        @media (max-width: 768px) {
            .sidebar-overlay.show {
                display: block;
            }
        }

        /* Utility classes */
        .responsive-hidden {
            display: block;
        }

        @media (max-width: 768px) {
            .responsive-hidden {
                display: none;
            }

            .mobile-title {
                display: inline !important;
            }
        }

        /* Improve touch targets on mobile */
        @media (max-width: 768px) {
            button {
                min-height: 44px;
                min-width: 44px;
            }

            input,
            select {
                min-height: 44px;
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-utensils sidebar-logo"></i>
            <h2>Granny Restaurant</h2>
            <p>Admin Panel</p>
        </div>

        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>Dashboard</span></a></li>
            <li><a href="carousel.php"><i class="fas fa-images"></i> <span>Carousel</span></a></li>
            <li><a href="gallery.php"><i class="fas fa-th-large"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="blog.php"><i class="fas fa-blog"></i> <span>Blog</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Tables</span></a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-check"></i> <span>Bookings</span></a></li>
            <li><a href="orders.php"><i class="fas fa-shopping-cart"></i> <span>Orders</span></a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> <span>Contacts</span></a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> <span>Feedback</span></a></li>
            <li><a href="servers.php" class="active"><i class="fas fa-user-secret"></i> <span>Servers</span></a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> <span>Users</span></a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> <span>Settings</span></a></li>
        </ul>

        <button class="logout-btn" onclick="logout()">
            <i class="fas fa-sign-out-alt"></i> Logout
        </button>
    </aside>

    <!-- Top Bar -->
    <div class="topbar">
        <div style="display: flex; align-items: center; gap: 15px;">
            <button class="hamburger" id="hamburger" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">
                <i class="fas fa-user-secret" style="color: #d4a574; margin-right: 10px;"></i><span class="responsive-hidden" style="display: inline;">Servers Management</span><span style="display: none;" class="mobile-title">Servers</span>
            </div>
        </div>
        <div class="topbar-right">
            <div class="topbar-user">
                <div class="user-avatar" id="userInitial">A</div>
                <div id="userInfo">
                    <strong id="userName">Admin</strong>
                </div>
            </div>
        </div>
    </div>

    <!-- Sidebar Overlay -->
    <div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Content Header -->
        <div class="content-header">
            <h1>Servers</h1>
            <button class="btn-primary" onclick="openAddServerModal()">
                <i class="fas fa-plus"></i> Add New Server
            </button>
        </div>

        <!-- Servers Table -->
        <div class="servers-table" id="serversContainer">
            <div class="loading">
                <i class="fas fa-spinner fa-spin"></i> Loading servers...
            </div>
        </div>
    </div>

    <!-- Add/Edit Server Modal -->
    <div class="modal" id="serverModal">
        <div class="modal-content">
            <div class="modal-header" id="modalTitle">Add New Server</div>

            <form id="serverForm">
                <div class="form-group">
                    <label for="serverName">Server Name *</label>
                    <input type="text" id="serverName" name="serverName" placeholder="Enter server name" required>
                </div>

                <div class="form-group" id="employeeIdGroup">
                    <label for="employeeId">Employee ID</label>
                    <input type="text" id="employeeId" name="employeeId" placeholder="Auto-generated" readonly style="background: #f5f5f5; cursor: not-allowed;">
                </div>

                <div class="form-group">
                    <label for="serverPhone">Phone</label>
                    <input type="text" id="serverPhone" name="serverPhone" placeholder="Enter phone number">
                </div>

                <div class="form-group">
                    <label for="serverStatus">Status</label>
                    <select id="serverStatus" name="serverStatus">
                        <option value="available">Available</option>
                        <option value="busy">Busy</option>
                        <option value="break">Break</option>
                        <option value="offline">Offline</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="shiftStart">Shift Start</label>
                    <input type="time" id="shiftStart" name="shiftStart">
                </div>

                <div class="form-group">
                    <label for="shiftEnd">Shift End</label>
                    <input type="time" id="shiftEnd" name="shiftEnd">
                </div>

                <div class="form-group">
                    <label for="serverPassword" id="passwordLabel">Password</label>
                    <input type="password" id="serverPassword" name="serverPassword" placeholder="Enter password">
                </div>

                <div class="modal-actions">
                    <button type="button" class="btn-cancel" onclick="closeServerModal()">Cancel</button>
                    <button type="submit" class="btn-submit">Save Server</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

    <script>
        let currentServerId = null;

        // Responsive sidebar functions
        function toggleSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            sidebar.classList.toggle('show');
            overlay.classList.toggle('show');
        }

        function closeSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            sidebar.classList.remove('show');
            overlay.classList.remove('show');
        }

        // Close sidebar when clicking on a link
        document.querySelectorAll('.sidebar-menu a').forEach(link => {
            link.addEventListener('click', closeSidebar);
        });

        // Handle window resize to hide sidebar on desktop
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                closeSidebar();
            }
        });

        $(document).ready(function() {
            loadServers();
        });

        function loadServers() {
            $.ajax({
                url: '../backend/admin_servers_api.php?action=list',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.data.length > 0) {
                        renderServersTable(response.data);
                    } else {
                        $('#serversContainer').html(`
                            <div class="empty-state">
                                <i class="fas fa-user-secret"></i>
                                <p>No servers found</p>
                                <p style="font-size: 12px; color: #ccc;">Click "Add New Server" to create one</p>
                            </div>
                        `);
                    }
                },
                error: function() {
                    $('#serversContainer').html(`
                        <div class="empty-state">
                            <i class="fas fa-exclamation-circle"></i>
                            <p>Error loading servers</p>
                        </div>
                    `);
                }
            });
        }

        function renderServersTable(servers) {
            let html = `
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Employee ID</th>
                            <th>Phone</th>
                            <th>Status</th>
                            <th>Shift</th>
                            <th>Rating</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            servers.forEach(server => {
                const shiftDisplay = server.shift_start && server.shift_end 
                    ? `${server.shift_start.substring(0, 5)} - ${server.shift_end.substring(0, 5)}`
                    : 'N/A';

                html += `
                    <tr>
                        <td><strong>${server.name}</strong></td>
                        <td>${server.employee_id}</td>
                        <td>${server.phone || 'N/A'}</td>
                        <td><span class="status-badge status-${server.status}">${server.status}</span></td>
                        <td>${shiftDisplay}</td>
                        <td>★ ${parseFloat(server.rating).toFixed(1)}</td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn-icon btn-edit" onclick="editServer(${server.id})" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn-icon btn-delete" onclick="deleteServer(${server.id})" title="Delete">
                                    <i class="fas fa-trash-alt"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            });

            html += `
                    </tbody>
                </table>
            `;

            $('#serversContainer').html(html);
        }

        function openAddServerModal() {
            // Fetch next employee ID from backend
            $.ajax({
                url: '../backend/admin_servers_api.php?action=get_next_id',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    currentServerId = null;
                    $('#modalTitle').text('Add New Server');
                    $('#serverForm')[0].reset();
                    $('#serverStatus').val('available');
                    $('#passwordLabel').text('Password');
                    $('#serverPassword').val('');
                    $('#employeeIdGroup').show();
                    $('#employeeId').val(response.next_id || 'SRV001');
                    $('#serverModal').addClass('show');
                },
                error: function() {
                    // Fallback if API fails
                    currentServerId = null;
                    $('#modalTitle').text('Add New Server');
                    $('#serverForm')[0].reset();
                    $('#serverStatus').val('available');
                    $('#passwordLabel').text('Password');
                    $('#serverPassword').val('');
                    $('#employeeIdGroup').show();
                    $('#employeeId').val('SRV001');
                    $('#serverModal').addClass('show');
                }
            });
        }

        function editServer(serverId) {
            $.ajax({
                url: '../backend/admin_servers_api.php?action=get&id=' + serverId,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const server = response.data;
                        currentServerId = serverId;
                        $('#modalTitle').text('Edit Server');
                        $('#serverName').val(server.name);
                        $('#employeeId').val(server.employee_id);
                        $('#employeeIdGroup').show();
                        $('#employeeId').prop('disabled', true);
                        $('#serverPhone').val(server.phone || '');
                        $('#serverStatus').val(server.status);
                        $('#shiftStart').val(server.shift_start || '');
                        $('#shiftEnd').val(server.shift_end || '');
                        $('#serverPassword').val('');
                        $('#passwordLabel').text('Password (Leave empty to keep current)');
                        $('#serverModal').addClass('show');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to load server details', 'error');
                }
            });
        }

        function closeServerModal() {
            $('#serverModal').removeClass('show');
            $('#employeeId').prop('disabled', false);
            $('#employeeIdGroup').show();
            currentServerId = null;
        }

        $('#serverForm').on('submit', function(e) {
            e.preventDefault();

            const data = {
                name: $('#serverName').val(),
                phone: $('#serverPhone').val(),
                status: $('#serverStatus').val(),
                shift_start: $('#shiftStart').val(),
                shift_end: $('#shiftEnd').val()
            };

            // Include password if provided
            const password = $('#serverPassword').val();
            if (password) {
                data.password = password;
            }

            if (currentServerId) {
                data.action = 'edit';
                data.server_id = currentServerId;
            } else {
                data.action = 'create';
                // Don't send employee_id - backend will auto-generate it
            }

            $.ajax({
                url: '../backend/admin_servers_api.php',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Success', response.message, 'success').then(() => {
                            closeServerModal();
                            loadServers();
                        });
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to save server', 'error');
                }
            });
        });

        function deleteServer(serverId) {
            Swal.fire({
                title: 'Delete Server?',
                text: 'Are you sure you want to delete this server?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74c3c',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Delete'
            }).then(result => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '../backend/admin_servers_api.php',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            action: 'delete',
                            server_id: serverId
                        }),
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Deleted!', 'Server deleted successfully', 'success').then(() => {
                                    loadServers();
                                });
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Failed to delete server', 'error');
                        }
                    });
                }
            });
        }

        function logout() {
            Swal.fire({
                title: 'Logout?',
                text: 'Are you sure you want to logout?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Logout'
            }).then(result => {
                if (result.isConfirmed) {
                    window.location.href = '../backend/admin_logout.php';
                }
            });
        }
    </script>
</body>

</html>
