<!DOCTYPE html>
<html dir="ltr" lang="en-US">

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

    <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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="manager-styles.css">

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

    <style>
        .main-content {
            padding: 30px 30px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0;
        }

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

        .page-header h1 {
            color: #1e3c72;
            font-size: 28px;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .stat-card-icon {
            font-size: 32px;
            color: #d4a574;
            margin-bottom: 10px;
        }

        .stat-card-title {
            font-size: 12px;
            color: #666;
            text-transform: uppercase;
            margin-bottom: 10px;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        .stat-card-value {
            font-size: 32px;
            font-weight: 700;
            color: #1e3c72;
        }

        .stat-card-change {
            font-size: 12px;
            color: #28a745;
            margin-top: 5px;
        }

        .controls {
            background: white;
            padding: 20px 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }

        .control-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .control-group label {
            font-size: 12px;
            color: #666;
            font-weight: 600;
            text-transform: uppercase;
        }

        .control-group input,
        .control-group select {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            font-size: 14px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(42, 82, 152, 0.3);
        }

        .servers-table {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 800px;
        }

        thead {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
        }

        th {
            padding: 15px 20px;
            text-align: left;
            font-weight: 600;
            font-size: 13px;
            text-transform: uppercase;
            white-space: nowrap;
        }

        td {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            white-space: nowrap;
        }

        tbody tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-align: center;
            min-width: 80px;
        }

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

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

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

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

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .rating-stars {
            color: #ffc107;
        }

        /* Responsive */
        @media (max-width: 1440px) and (min-width: 1025px) {
            .stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 1024px) and (min-width: 769px) {
            .stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            .control-group input,
            .control-group select {
                width: 100%;
            }

            .stats {
                grid-template-columns: repeat(2, 1fr);
            }

            .servers-table {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            table {
                font-size: 12px;
                min-width: 100%;
            }

            th, td {
                padding: 10px 8px;
                white-space: nowrap;
            }

            th {
                font-size: 11px;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                padding: 15px;
            }

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

            .main-content {
                padding: 15px 15px;
            }

            .container {
                padding: 0;
            }

            .stat-card {
                padding: 15px;
            }

            .stat-card-value {
                font-size: 24px;
            }

            .stat-card-icon {
                font-size: 24px;
            }
        }

        @media (max-width: 480px) {
            .stats {
                grid-template-columns: 1fr;
            }

            table {
                font-size: 11px;
            }

            th, td {
                padding: 8px 6px;
            }

            th {
                font-size: 10px;
            }

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

            .stat-card-value {
                font-size: 20px;
            }

            .page-header h1 {
                font-size: 18px;
            }
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }
    </style>
</head>

<body>
    <div class="dashboard-container">
        <?php include 'sidebar.php'; ?>
        <div class="main-content">
            <div class="container">
                <div class="page-header">
                    <h1><i class="fas fa-users"></i> Servers Management</h1>
                </div>

                <!-- Statistics -->
                <div class="stats" id="statsContainer">
                    <div class="stat-card">
                        <div class="stat-card-icon"><i class="fas fa-user-tie"></i></div>
                        <div class="stat-card-title">Total Servers</div>
                        <div class="stat-card-value" id="totalServers">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-card-icon"><i class="fas fa-check-circle"></i></div>
                        <div class="stat-card-title">Currently Online</div>
                        <div class="stat-card-value" id="onlineServers">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-card-icon"><i class="fas fa-clock"></i></div>
                        <div class="stat-card-title">On Duty</div>
                        <div class="stat-card-value" id="onDutyServers">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-card-icon"><i class="fas fa-star"></i></div>
                        <div class="stat-card-title">Average Rating</div>
                        <div class="stat-card-value" id="averageRating">0.0</div>
                    </div>
                </div>

                <!-- Controls -->
                <div class="controls">
                    <div class="control-group">
                        <label>Status Filter</label>
                        <select id="statusFilter" onchange="filterServers()">
                            <option value="">All Servers</option>
                            <option value="online">Online</option>
                            <option value="offline">Offline</option>
                        </select>
                    </div>

                    <div class="control-group">
                        <label>&nbsp;</label>
                        <button class="btn btn-primary" onclick="loadServers()">
                            <i class="fas fa-sync"></i> Refresh
                        </button>
                    </div>
                </div>

                <!-- Servers Table -->
                <div class="servers-table">
                    <table id="serversTable">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Employee ID</th>
                                <th>Phone</th>
                                <th>Status</th>
                                <th>Shift Start</th>
                                <th>Shift End</th>
                                <th>Rating</th>
                                <th>Joined Date</th>
                            </tr>
                        </thead>
                        <tbody id="serversBody">
                            <tr>
                                <td colspan="8" style="text-align: center; padding: 40px;">
                                    <i class="fas fa-spinner fa-spin"></i> Loading servers...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

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

    <script>
        $(document).ready(function() {
            checkAuthentication();
            loadServers();
            // Refresh every 30 seconds
            setInterval(loadServers, 30000);
        });

        function checkAuthentication() {
            if (!localStorage.getItem('manager_id')) {
                window.location.href = 'login.php';
            }
        }

        function loadServers() {
            const managerId = localStorage.getItem('manager_id');
            $.ajax({
                url: `../backend/manager_servers_api.php?action=list&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayServers(response.data);
                        updateStats(response.data);
                    } else {
                        Swal.fire('Error', response.message || 'Failed to load servers', 'error');
                    }
                },
                error: function(error) {
                    console.error('Error:', error);
                    Swal.fire('Error', 'Failed to load servers', 'error');
                }
            });
        }

        function updateStats(servers) {
            let totalServers = servers.length;
            let onlineCount = 0;
            let onDutyCount = 0;
            let totalRating = 0;
            let ratedServers = 0;

            servers.forEach(server => {
                // Use is_online column directly - it's set to 1/true when server is logged in
                if (server.is_online == 1 || server.is_online === true) {
                    onlineCount++;
                }
                
                // Calculate on-duty servers (those with active shift times)
                if (server.shift_start && server.shift_end) {
                    onDutyCount++;
                }

                if (server.rating && server.rating > 0) {
                    totalRating += parseFloat(server.rating);
                    ratedServers++;
                }
            });

            const averageRating = ratedServers > 0 ? (totalRating / ratedServers).toFixed(1) : 0;

            $('#totalServers').text(totalServers);
            $('#onlineServers').text(onlineCount);
            $('#onDutyServers').text(onDutyCount);
            $('#averageRating').text(averageRating);
        }

        function displayServers(servers) {
            let statusFilter = $('#statusFilter').val();
            let filteredServers = servers;

            if (statusFilter) {
                filteredServers = servers.filter(server => {
                    // Use is_online column directly - it's set to 1/true when logged in
                    const status = server.is_online == 1 || server.is_online === true ? 'online' : 'offline';
                    return status === statusFilter;
                });
            }

            let tableHtml = '';

            if (filteredServers.length === 0) {
                tableHtml = '<tr><td colspan="8" class="empty-state"><i class="fas fa-inbox"></i><p>No servers found</p></td></tr>';
            } else {
                filteredServers.forEach(server => {
                    // Use is_online column directly - it's boolean/int from database
                    const status = server.is_online == 1 || server.is_online === true ? 'online' : 'offline';
                    const statusBadgeClass = status === 'online' ? 'status-online' : 'status-offline';
                    const statusText = status === 'online' ? 'Online' : 'Offline';
                    
                    const rating = server.rating ? parseFloat(server.rating).toFixed(1) : 'N/A';
                    const ratingStars = rating !== 'N/A' ? '<span class="rating-stars">' + 
                        '<i class="fas fa-star"></i>'.repeat(Math.floor(rating)) +
                        (rating % 1 >= 0.5 ? '<i class="fas fa-star-half-alt"></i>' : '') +
                        '</span> ' + rating : 'N/A';

                    const joinDate = new Date(server.created_at).toLocaleDateString();
                    const shiftStart = server.shift_start || 'N/A';
                    const shiftEnd = server.shift_end || 'N/A';

                    tableHtml += `
                        <tr>
                            <td><strong>${server.name}</strong></td>
                            <td>${server.employee_id}</td>
                            <td>${server.phone || 'N/A'}</td>
                            <td><span class="status-badge ${statusBadgeClass}">${statusText}</span></td>
                            <td>${shiftStart}</td>
                            <td>${shiftEnd}</td>
                            <td>${ratingStars}</td>
                            <td>${joinDate}</td>
                        </tr>
                    `;
                });
            }

            $('#serversBody').html(tableHtml);
        }

        function filterServers() {
            $.ajax({
                url: '../backend/admin_servers_api.php?action=list',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayServers(response.data);
                    }
                }
            });
        }
    </script>

    <!-- Manager Sidebar Script -->
    <script src="manager-sidebar.js"></script>
</body>

</html>
