<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tatkal Management - Astro Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
        }
        .btn-success {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
            border: none;
        }
        .btn-warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            border: none;
        }
        .btn-danger {
            background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
            border: none;
        }
        .status-pending { color: #ffc107; }
        .status-confirmed { color: #28a745; }
        .status-cancelled { color: #dc3545; }
        .status-completed { color: #17a2b8; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar text-white p-3">
                    <h4 class="text-center mb-4">
                        <i class="fas fa-star"></i> Astro Admin
                    </h4>
                    <ul class="nav flex-column">
                        <li class="nav-item mb-2">
                            <a class="nav-link text-white" href="index.php">
                                <i class="fas fa-home"></i> Dashboard
                            </a>
                        </li>
                        <li class="nav-item mb-2">
                            <a class="nav-link text-white" href="appointments.php">
                                <i class="fas fa-calendar"></i> Appointments
                            </a>
                        </li>
                        <li class="nav-item mb-2">
                            <a class="nav-link text-white active" href="tatkal_management.php">
                                <i class="fas fa-bolt"></i> Tatkal Management
                            </a>
                        </li>
                        <li class="nav-item mb-2">
                            <a class="nav-link text-white" href="users.php">
                                <i class="fas fa-users"></i> Users
                            </a>
                        </li>
                        <li class="nav-item mb-2">
                            <a class="nav-link text-white" href="settings.php">
                                <i class="fas fa-cog"></i> Settings
                            </a>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 px-0">
                <div class="main-content p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-bolt text-warning"></i> Tatkal Management</h2>
                        <button class="btn btn-primary" onclick="refreshData()">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                    </div>

                    <!-- Settings Section -->
                    <div class="card mb-4">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="fas fa-cog"></i> Tatkal Settings</h5>
                        </div>
                        <div class="card-body">
                            <div id="settingsLoading" class="text-center" style="display: none;">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2">Loading settings...</p>
                            </div>
                            <form id="settingsForm" style="display: none;">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Enable Tatkal Booking</label>
                                            <select class="form-select" id="tatkal_enabled" name="tatkal_enabled">
                                                <option value="1">Enabled</option>
                                                <option value="0">Disabled</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Tatkal Price (₹)</label>
                                            <input type="number" class="form-control" id="tatkal_price" name="tatkal_price" min="0" step="0.01">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Max Slots per Day</label>
                                            <input type="number" class="form-control" id="tatkal_slots" name="tatkal_slots" min="1" max="100">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Advance Booking Days</label>
                                            <input type="number" class="form-control" id="tatkal_advance_days" name="tatkal_advance_days" min="1" max="30">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Available Days</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tatkal_monday" name="tatkal_monday" value="1">
                                            <label class="form-check-label" for="tatkal_monday">Monday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tatkal_tuesday" name="tatkal_tuesday" value="1">
                                            <label class="form-check-label" for="tatkal_tuesday">Tuesday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tatkal_wednesday" name="tatkal_wednesday" value="1">
                                            <label class="form-check-label" for="tatkal_wednesday">Wednesday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tatkal_thursday" name="tatkal_thursday" value="1">
                                            <label class="form-check-label" for="tatkal_thursday">Thursday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tatkal_friday" name="tatkal_friday" value="1">
                                            <label class="form-check-label" for="tatkal_friday">Friday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tatkal_saturday" name="tatkal_saturday" value="1">
                                            <label class="form-check-label" for="tatkal_saturday">Saturday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tatkal_sunday" name="tatkal_sunday" value="1">
                                            <label class="form-check-label" for="tatkal_sunday">Sunday</label>
                                        </div>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-save"></i> Save Settings
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- Appointments Section -->
                    <div class="card">
                        <div class="card-header bg-info text-white">
                            <h5 class="mb-0"><i class="fas fa-calendar-check"></i> Tatkal Appointments</h5>
                        </div>
                        <div class="card-body">
                            <div id="appointmentsLoading" class="text-center" style="display: none;">
                                <div class="spinner-border text-info" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2">Loading appointments...</p>
                            </div>
                            <div class="table-responsive" id="appointmentsTableContainer" style="display: none;">
                                <table class="table table-striped" id="appointmentsTable">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>User</th>
                                            <th>Mobile</th>
                                            <th>Date</th>
                                            <th>Amount</th>
                                            <th>Type</th>
                                            <th>Persons</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody id="appointmentsBody">
                                        <!-- Data will be loaded here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Load data on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadSettings();
            loadAppointments();
        });

        // Load settings
        async function loadSettings() {
            const loadingDiv = document.getElementById('settingsLoading');
            const formDiv = document.getElementById('settingsForm');
            
            loadingDiv.style.display = 'block';
            formDiv.style.display = 'none';
            
            try {
                const response = await fetch('../api/tatkal_management.php');
                const data = await response.json();
                
                if (data.success) {
                    const settings = data.settings;
                    
                    // Populate form fields
                    document.getElementById('tatkal_enabled').value = settings.tatkal_enabled || '1';
                    document.getElementById('tatkal_price').value = settings.tatkal_price || '1500';
                    document.getElementById('tatkal_slots').value = settings.tatkal_slots || '10';
                    document.getElementById('tatkal_advance_days').value = settings.tatkal_advance_days || '7';
                    
                    // Check day checkboxes
                    const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
                    days.forEach(day => {
                        const checkbox = document.getElementById(`tatkal_${day}`);
                        if (settings[`tatkal_${day}`] === '1') {
                            checkbox.checked = true;
                        }
                    });
                    
                    loadingDiv.style.display = 'none';
                    formDiv.style.display = 'block';
                } else {
                    console.error('Error loading settings:', data.message);
                    loadingDiv.innerHTML = '<div class="alert alert-danger">Error loading settings: ' + data.message + '</div>';
                }
            } catch (error) {
                console.error('Error loading settings:', error);
                loadingDiv.innerHTML = '<div class="alert alert-danger">Error loading settings: ' + error.message + '<br>Response: ' + (await response.text()) + '</div>';
            }
        }

        // Load appointments
        async function loadAppointments() {
            const loadingDiv = document.getElementById('appointmentsLoading');
            const tableContainer = document.getElementById('appointmentsTableContainer');
            
            loadingDiv.style.display = 'block';
            tableContainer.style.display = 'none';
            
            try {
                const response = await fetch('../api/tatkal_management.php');
                const data = await response.json();
                
                if (data.success) {
                    const tbody = document.getElementById('appointmentsBody');
                    tbody.innerHTML = '';
                    
                    if (data.appointments && data.appointments.length > 0) {
                        data.appointments.forEach(appointment => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${appointment.id}</td>
                                <td>${appointment.user_name || 'N/A'}</td>
                                <td>${appointment.user_mobile || 'N/A'}</td>
                                <td>${appointment.appointment_date}</td>
                                <td>₹${appointment.amount || '0'}</td>
                                <td>${appointment.consultation_type || 'Tatkal'}</td>
                                <td>${appointment.number_of_persons || '1'}</td>
                                <td><span class="status-${appointment.status}">${appointment.status.toUpperCase()}</span></td>
                                <td>
                                    <select class="form-select form-select-sm" onchange="updateStatus(${appointment.id}, this.value)">
                                        <option value="pending" ${appointment.status === 'pending' ? 'selected' : ''}>Pending</option>
                                        <option value="confirmed" ${appointment.status === 'confirmed' ? 'selected' : ''}>Confirmed</option>
                                        <option value="cancelled" ${appointment.status === 'cancelled' ? 'selected' : ''}>Cancelled</option>
                                        <option value="completed" ${appointment.status === 'completed' ? 'selected' : ''}>Completed</option>
                                    </select>
                                </td>
                            `;
                            tbody.appendChild(row);
                        });
                    } else {
                        tbody.innerHTML = '<tr><td colspan="9" class="text-center">No tatkal appointments found</td></tr>';
                    }
                    
                    loadingDiv.style.display = 'none';
                    tableContainer.style.display = 'block';
                } else {
                    console.error('Error loading appointments:', data.message);
                    loadingDiv.innerHTML = '<div class="alert alert-danger">Error loading appointments: ' + data.message + '</div>';
                }
            } catch (error) {
                console.error('Error loading appointments:', error);
                loadingDiv.innerHTML = '<div class="alert alert-danger">Error loading appointments: ' + error.message + '<br>Response: ' + (await response.text()) + '</div>';
            }
        }

        // Save settings
        document.getElementById('settingsForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const settings = {};
            
            // Collect all form data
            for (let [key, value] of formData.entries()) {
                settings[key] = value;
            }
            
            // Handle checkboxes
            const checkboxes = ['tatkal_monday', 'tatkal_tuesday', 'tatkal_wednesday', 'tatkal_thursday', 'tatkal_friday', 'tatkal_saturday', 'tatkal_sunday'];
            checkboxes.forEach(day => {
                settings[day] = document.getElementById(day).checked ? '1' : '0';
            });
            
            // Show loading state
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            submitBtn.disabled = true;
            
            try {
                const response = await fetch('../api/tatkal_management.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'update_settings',
                        settings: settings
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Settings saved successfully!');
                    loadSettings(); // Reload settings to confirm
                } else {
                    alert('Error saving settings: ' + data.message);
                }
            } catch (error) {
                console.error('Error saving settings:', error);
                alert('Error saving settings: ' + error.message);
            } finally {
                // Reset button state
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        });

        // Update appointment status
        async function updateStatus(appointmentId, status) {
            if (!confirm(`Are you sure you want to change the status to ${status.toUpperCase()}?`)) {
                // Reset the select to previous value
                loadAppointments();
                return;
            }
            
            try {
                const response = await fetch('../api/tatkal_management.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'update_appointment_status',
                        appointment_id: appointmentId,
                        status: status
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Status updated successfully!');
                    loadAppointments(); // Refresh the table
                } else {
                    alert('Error updating status: ' + data.message);
                    loadAppointments(); // Refresh to reset the select
                }
            } catch (error) {
                console.error('Error updating status:', error);
                alert('Error updating status: ' + error.message);
                loadAppointments(); // Refresh to reset the select
            }
        }

        // Refresh data
        function refreshData() {
            loadSettings();
            loadAppointments();
        }
    </script>
</body>
</html>
