<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Appointments Admin</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
        }

        /* Login Screen */
        .login-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
        }

        .login-card {
            background: white;
            padding: 40px;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            width: 100%;
            max-width: 400px;
        }

        .login-card h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }

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

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

        .form-group input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .error-msg {
            background: #f8d7da;
            color: #721c24;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .error-msg.show {
            display: block;
        }

        /* Dashboard */
        .dashboard {
            display: none;
        }

        .dashboard.show {
            display: block;
        }

        .login-container.hide {
            display: none;
        }

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

        .header h1 {
            color: #333;
            font-size: 1.5rem;
        }

        .header-actions {
            display: flex;
            gap: 10px;
        }

        .btn-small {
            padding: 10px 20px;
            font-size: 0.9rem;
            border-radius: 6px;
            cursor: pointer;
            border: none;
            font-weight: 500;
        }

        .btn-refresh {
            background: #667eea;
            color: white;
        }

        .btn-logout {
            background: #e0e0e0;
            color: #333;
        }

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

        /* Stats */
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

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

        .stat-card h3 {
            color: #888;
            font-size: 0.9rem;
            font-weight: 500;
            margin-bottom: 8px;
        }

        .stat-card .number {
            font-size: 2rem;
            font-weight: 700;
            color: #333;
        }

        .stat-card.pending .number { color: #f39c12; }
        .stat-card.confirmed .number { color: #27ae60; }
        .stat-card.total .number { color: #667eea; }

        /* Filter tabs */
        .filter-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-tab {
            padding: 10px 20px;
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            color: #666;
            transition: all 0.2s;
        }

        .filter-tab:hover {
            border-color: #667eea;
        }

        .filter-tab.active {
            background: #667eea;
            border-color: #667eea;
            color: white;
        }

        /* Appointments list */
        .appointments-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .appointment-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: grid;
            grid-template-columns: 1fr auto;
            gap: 20px;
            align-items: start;
        }

        @media (max-width: 600px) {
            .appointment-card {
                grid-template-columns: 1fr;
            }
        }

        .appointment-info h3 {
            color: #333;
            margin-bottom: 10px;
            font-size: 1.2rem;
        }

        .appointment-info p {
            color: #666;
            margin: 5px 0;
            font-size: 0.95rem;
        }

        .appointment-info .label {
            color: #888;
            font-weight: 500;
        }

        .appointment-info .datetime {
            color: #667eea;
            font-weight: 600;
            font-size: 1rem;
        }

        .appointment-info .reason {
            display: inline-block;
            background: #f0f0f0;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            margin-top: 8px;
        }

        .appointment-info .details {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #eee;
            color: #555;
            font-style: italic;
        }

        .appointment-actions {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .btn-action {
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            font-size: 0.85rem;
            font-weight: 500;
            cursor: pointer;
            transition: opacity 0.2s;
        }

        .btn-action:hover {
            opacity: 0.8;
        }

        .btn-confirm {
            background: #27ae60;
            color: white;
        }

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

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

        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            margin-left: 10px;
        }

        .status-pending {
            background: #fef3cd;
            color: #856404;
        }

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

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

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

        .empty-state h3 {
            margin-bottom: 10px;
            color: #666;
        }
    </style>
</head>
<body>
    <!-- Login Screen -->
    <div class="login-container" id="loginScreen">
        <div class="login-card">
            <h1>Admin Login</h1>
            <div class="error-msg" id="loginError"></div>
            <form id="loginForm">
                <div class="form-group">
                    <label>Password</label>
                    <input type="password" id="password" required placeholder="Enter admin password">
                </div>
                <button type="submit" class="btn">Login</button>
            </form>
        </div>
    </div>

    <!-- Dashboard -->
    <div class="dashboard" id="dashboard">
        <div class="header">
            <h1>Appointments Dashboard</h1>
            <div class="header-actions">
                <button class="btn-small btn-refresh" onclick="loadAppointments()">Refresh</button>
                <button class="btn-small btn-logout" onclick="logout()">Logout</button>
            </div>
        </div>

        <div class="content">
            <div class="stats">
                <div class="stat-card pending">
                    <h3>Pending</h3>
                    <div class="number" id="pendingCount">0</div>
                </div>
                <div class="stat-card confirmed">
                    <h3>Confirmed</h3>
                    <div class="number" id="confirmedCount">0</div>
                </div>
                <div class="stat-card total">
                    <h3>Total</h3>
                    <div class="number" id="totalCount">0</div>
                </div>
            </div>

            <div class="filter-tabs">
                <button class="filter-tab active" data-filter="all">All</button>
                <button class="filter-tab" data-filter="pending">Pending</button>
                <button class="filter-tab" data-filter="confirmed">Confirmed</button>
                <button class="filter-tab" data-filter="cancelled">Cancelled</button>
            </div>

            <div class="appointments-list" id="appointmentsList">
                <!-- Populated by JavaScript -->
            </div>
        </div>
    </div>

    <script>
        const ADMIN_PASSWORD = 'rosy2024'; // Change this!
        let appointments = [];
        let currentFilter = 'all';

        // Check if already logged in
        if (sessionStorage.getItem('adminLoggedIn')) {
            showDashboard();
        }

        // Login form
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const password = document.getElementById('password').value;

            if (password === ADMIN_PASSWORD) {
                sessionStorage.setItem('adminLoggedIn', 'true');
                showDashboard();
            } else {
                const error = document.getElementById('loginError');
                error.textContent = 'Incorrect password';
                error.classList.add('show');
            }
        });

        // Filter tabs
        document.querySelectorAll('.filter-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');
                currentFilter = this.dataset.filter;
                renderAppointments();
            });
        });

        function showDashboard() {
            document.getElementById('loginScreen').classList.add('hide');
            document.getElementById('dashboard').classList.add('show');
            loadAppointments();
        }

        function logout() {
            sessionStorage.removeItem('adminLoggedIn');
            location.reload();
        }

        async function loadAppointments() {
            try {
                const response = await fetch('/appointments/api/list.php');
                const data = await response.json();

                if (data.success) {
                    appointments = data.appointments || [];
                    updateStats();
                    renderAppointments();
                }
            } catch (error) {
                console.error('Error loading appointments:', error);
            }
        }

        function updateStats() {
            const pending = appointments.filter(a => a.status === 'pending').length;
            const confirmed = appointments.filter(a => a.status === 'confirmed').length;

            document.getElementById('pendingCount').textContent = pending;
            document.getElementById('confirmedCount').textContent = confirmed;
            document.getElementById('totalCount').textContent = appointments.length;
        }

        function renderAppointments() {
            const list = document.getElementById('appointmentsList');
            let filtered = appointments;

            if (currentFilter !== 'all') {
                filtered = appointments.filter(a => a.status === currentFilter);
            }

            // Sort by date (newest first)
            filtered.sort((a, b) => new Date(b.date + ' ' + b.time) - new Date(a.date + ' ' + a.time));

            if (filtered.length === 0) {
                list.innerHTML = `
                    <div class="empty-state">
                        <h3>No appointments found</h3>
                        <p>No ${currentFilter === 'all' ? '' : currentFilter} appointments yet.</p>
                    </div>
                `;
                return;
            }

            list.innerHTML = filtered.map(apt => {
                const dateObj = new Date(apt.date + 'T' + apt.time);
                const formattedDate = dateObj.toLocaleDateString('en-US', {
                    weekday: 'short',
                    month: 'short',
                    day: 'numeric',
                    year: 'numeric'
                });
                const formattedTime = dateObj.toLocaleTimeString('en-US', {
                    hour: 'numeric',
                    minute: '2-digit'
                });

                const statusClass = `status-${apt.status}`;
                const statusLabel = apt.status.charAt(0).toUpperCase() + apt.status.slice(1);

                return `
                    <div class="appointment-card">
                        <div class="appointment-info">
                            <h3>${apt.name} <span class="status-badge ${statusClass}">${statusLabel}</span></h3>
                            <p class="datetime">${formattedDate} at ${formattedTime}</p>
                            <p><span class="label">Email:</span> ${apt.email}</p>
                            <p><span class="label">Phone:</span> ${apt.phone}</p>
                            <span class="reason">${apt.reason}</span>
                            ${apt.details && apt.details !== 'None' ? `<p class="details">"${apt.details}"</p>` : ''}
                        </div>
                        <div class="appointment-actions">
                            ${apt.status === 'pending' ? `
                                <button class="btn-action btn-confirm" onclick="updateStatus(${apt.id}, 'confirmed')">Confirm</button>
                                <button class="btn-action btn-cancel" onclick="updateStatus(${apt.id}, 'cancelled')">Cancel</button>
                            ` : ''}
                            ${apt.status === 'cancelled' ? `
                                <button class="btn-action btn-confirm" onclick="updateStatus(${apt.id}, 'pending')">Restore</button>
                            ` : ''}
                            <button class="btn-action btn-delete" onclick="deleteAppointment(${apt.id})">Delete</button>
                        </div>
                    </div>
                `;
            }).join('');
        }

        async function updateStatus(id, status) {
            try {
                const response = await fetch('/appointments/api/update.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id, status })
                });

                const result = await response.json();
                if (result.success) {
                    loadAppointments();
                }
            } catch (error) {
                console.error('Error updating status:', error);
            }
        }

        async function deleteAppointment(id) {
            if (!confirm('Are you sure you want to delete this appointment?')) return;

            try {
                const response = await fetch('/appointments/api/delete.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id })
                });

                const result = await response.json();
                if (result.success) {
                    loadAppointments();
                }
            } catch (error) {
                console.error('Error deleting appointment:', error);
            }
        }
    </script>
</body>
</html>
