<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tatkal Management v2 - 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; font-weight: bold; }
        .status-confirmed { color: #28a745; font-weight: bold; }
        .status-cancelled { color: #dc3545; font-weight: bold; }
        .status-completed { color: #17a2b8; font-weight: bold; }
        .payment-pending { color: #ffc107; }
        .payment-paid { color: #28a745; }
        .payment-refunded { color: #dc3545; }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .stat-card.amber { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
        .stat-card.green { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
        .stat-card.blue { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
        .stat-card.purple { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
    </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_v2.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 v2</h2>
                        <button class="btn btn-primary" onclick="refreshData()">
                            <i class="fas fa-sync-alt"></i> Refresh
                        </button>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4" id="statsContainer">
                        <!-- Stats will be loaded here -->
                    </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">
                            <form id="settingsForm">
                                <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="enabled" name="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="price" name="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="max_slots" name="max_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="advance_days" name="advance_days" min="1" max="30">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Start Time</label>
                                            <input type="time" class="form-control" id="start_time" name="start_time">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">End Time</label>
                                            <input type="time" class="form-control" id="end_time" name="end_time">
                                        </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="monday" name="monday" value="1">
                                            <label class="form-check-label" for="monday">Monday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="tuesday" name="tuesday" value="1">
                                            <label class="form-check-label" for="tuesday">Tuesday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="wednesday" name="wednesday" value="1">
                                            <label class="form-check-label" for="wednesday">Wednesday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="thursday" name="thursday" value="1">
                                            <label class="form-check-label" for="thursday">Thursday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="friday" name="friday" value="1">
                                            <label class="form-check-label" for="friday">Friday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="saturday" name="saturday" value="1">
                                            <label class="form-check-label" for="saturday">Saturday</label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="sunday" name="sunday" value="1">
                                            <label class="form-check-label" for="sunday">Sunday</label>
                                        </div>
                                        
                                        <div class="mt-3">
                                            <label class="form-label">Min Advance Hours</label>
                                            <input type="number" class="form-control" id="min_advance_hours" name="min_advance_hours" min="1" max="24">
                                        </div>
                                        <div class="mt-3">
                                            <label class="form-label">Max Advance Hours</label>
                                            <input type="number" class="form-control" id="max_advance_hours" name="max_advance_hours" min="24" max="720">
                                        </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 class="table-responsive">
                                <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>Payment</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() {
            loadData();
        });

        // Load all data
        async function loadData() {
            await Promise.all([
                loadSettings(),
                loadAppointments(),
                loadStats()
            ]);
        }

        // Load statistics
        async function loadStats() {
            try {
                const response = await fetch('../api/tatkal_management_v2.php');
                const data = await response.json();
                
                if (data.success && data.stats) {
                    const stats = data.stats;
                    const statsContainer = document.getElementById('statsContainer');
                    
                    statsContainer.innerHTML = `
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3>${stats.total_appointments || 0}</h3>
                                        <p class="mb-0">Total Appointments</p>
                                    </div>
                                    <i class="fas fa-calendar-check fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card amber">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3>${stats.pending_appointments || 0}</h3>
                                        <p class="mb-0">Pending</p>
                                    </div>
                                    <i class="fas fa-clock fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card green">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3>₹${(stats.total_revenue || 0).toLocaleString()}</h3>
                                        <p class="mb-0">Total Revenue</p>
                                    </div>
                                    <i class="fas fa-rupee-sign fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card blue">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3>${stats.paid_appointments || 0}</h3>
                                        <p class="mb-0">Paid</p>
                                    </div>
                                    <i class="fas fa-check-circle fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('Error loading stats:', error);
            }
        }

        // Load settings
        async function loadSettings() {
            try {
                const response = await fetch('../api/tatkal_management_v2.php');
                const data = await response.json();
                
                if (data.success) {
                    const settings = data.settings;
                    
                    // Populate form fields
                    document.getElementById('enabled').value = settings.enabled || '1';
                    document.getElementById('price').value = settings.price || '1500';
                    document.getElementById('max_slots').value = settings.max_slots || '10';
                    document.getElementById('advance_days').value = settings.advance_days || '7';
                    document.getElementById('start_time').value = settings.start_time || '09:00';
                    document.getElementById('end_time').value = settings.end_time || '18:00';
                    document.getElementById('min_advance_hours').value = settings.min_advance_hours || '2';
                    document.getElementById('max_advance_hours').value = settings.max_advance_hours || '168';
                    
                    // Check day checkboxes
                    const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
                    days.forEach(day => {
                        const checkbox = document.getElementById(day);
                        if (settings[day] === '1') {
                            checkbox.checked = true;
                        }
                    });
                }
            } catch (error) {
                console.error('Error loading settings:', error);
                alert('Error loading settings');
            }
        }

        // Load appointments
        async function loadAppointments() {
            try {
                const response = await fetch('../api/tatkal_management_v2.php');
                const data = await response.json();
                
                if (data.success) {
                    const tbody = document.getElementById('appointmentsBody');
                    tbody.innerHTML = '';
                    
                    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}</td>
                            <td>${appointment.consultation_type}</td>
                            <td>${appointment.number_of_persons}</td>
                            <td><span class="status-${appointment.status}">${appointment.status.toUpperCase()}</span></td>
                            <td><span class="payment-${appointment.payment_status}">${appointment.payment_status.toUpperCase()}</span></td>
                            <td>
                                <div class="btn-group" role="group">
                                    <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>
                                    <select class="form-select form-select-sm mt-1" onchange="updatePaymentStatus(${appointment.id}, this.value)">
                                        <option value="pending" ${appointment.payment_status === 'pending' ? 'selected' : ''}>Pending</option>
                                        <option value="paid" ${appointment.payment_status === 'paid' ? 'selected' : ''}>Paid</option>
                                        <option value="refunded" ${appointment.payment_status === 'refunded' ? 'selected' : ''}>Refunded</option>
                                    </select>
                                </div>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                }
            } catch (error) {
                console.error('Error loading appointments:', error);
                alert('Error loading appointments');
            }
        }

        // 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 = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            checkboxes.forEach(day => {
                settings[day] = document.getElementById(day).checked ? '1' : '0';
            });
            
            try {
                const response = await fetch('../api/tatkal_management_v2.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!');
                } else {
                    alert('Error saving settings: ' + data.message);
                }
            } catch (error) {
                console.error('Error saving settings:', error);
                alert('Error saving settings');
            }
        });

        // Update appointment status
        async function updateStatus(appointmentId, status) {
            try {
                const response = await fetch('../api/tatkal_management_v2.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);
                }
            } catch (error) {
                console.error('Error updating status:', error);
                alert('Error updating status');
            }
        }

        // Update payment status
        async function updatePaymentStatus(appointmentId, paymentStatus) {
            try {
                const response = await fetch('../api/tatkal_management_v2.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'update_payment_status',
                        appointment_id: appointmentId,
                        payment_status: paymentStatus
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Payment status updated successfully!');
                    loadAppointments(); // Refresh the table
                } else {
                    alert('Error updating payment status: ' + data.message);
                }
            } catch (error) {
                console.error('Error updating payment status:', error);
                alert('Error updating payment status');
            }
        }

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