<?php
session_start();
require_once '../config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$page_title = 'Dashboard';
$current_page = 'index.php';

// Initialize default values
$userCount = $todayBookings = $totalBookings = $todayRevenue = $tatkalToday = 0;
$recentBookings = [];

ob_start();
?>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-users fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-primary" id="total-users">0</h3>
                    <p class="text-muted mb-0">Total Users</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-success text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-calendar-day fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-success" id="today-bookings">0</h3>
                    <p class="text-muted mb-0">Today's Bookings</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-warning text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-rupee-sign fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-warning" id="today-revenue">₹0</h3>
                    <p class="text-muted mb-0">Today's Revenue</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="content-card text-center">
            <div class="d-flex align-items-center">
                <div class="flex-shrink-0">
                    <div class="bg-info text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                        <i class="fas fa-bolt fa-2x"></i>
                    </div>
                </div>
                <div class="flex-grow-1 ms-3 text-start">
                    <h3 class="mb-0 text-info" id="tatkal-today">0</h3>
                    <p class="text-muted mb-0">Tatkal Bookings</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Quick Actions -->
<div class="row mb-4">
    <div class="col-12">
        <div class="content-card">
            <h4 class="mb-3">
                <i class="fas fa-bolt me-2 text-primary"></i>
                Quick Actions
            </h4>
            <div class="row">
                <div class="col-md-3 mb-3">
                    <a href="appointments.php" class="btn btn-outline-primary w-100 h-100 d-flex flex-column align-items-center justify-content-center py-4">
                        <i class="fas fa-calendar-check fa-2x mb-2"></i>
                        <span>Manage Appointments</span>
                    </a>
                </div>
                <div class="col-md-3 mb-3">
                    <a href="users.php" class="btn btn-outline-success w-100 h-100 d-flex flex-column align-items-center justify-content-center py-4">
                        <i class="fas fa-users fa-2x mb-2"></i>
                        <span>Manage Users</span>
                    </a>
                </div>
                <div class="col-md-3 mb-3">
                    <a href="tatkal_management_panel.php" class="btn btn-outline-warning w-100 h-100 d-flex flex-column align-items-center justify-content-center py-4">
                        <i class="fas fa-bolt fa-2x mb-2"></i>
                        <span>Tatkal Management</span>
                    </a>
                </div>
                <div class="col-md-3 mb-3">
                    <a href="settings.php" class="btn btn-outline-info w-100 h-100 d-flex flex-column align-items-center justify-content-center py-4">
                        <i class="fas fa-cog fa-2x mb-2"></i>
                        <span>Settings</span>
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Bookings -->
<!--<div class="row">-->
<!--    <div class="col-12">-->
<!--        <div class="content-card">-->
<!--            <div class="d-flex justify-content-between align-items-center mb-3">-->
<!--                <h4 class="mb-0">-->
<!--                    <i class="fas fa-clock me-2 text-primary"></i>-->
<!--                    Recent Bookings-->
<!--                </h4>-->
<!--                <a href="appointments.php" class="btn btn-sm btn-outline-primary">View All</a>-->
<!--            </div>-->
            
<!--            <div id="recent-bookings-container">-->
<!--                <div class="text-center py-5">-->
<!--                    <i class="fas fa-spinner fa-spin fa-2x text-muted mb-3"></i>-->
<!--                    <p class="text-muted">Loading recent bookings...</p>-->
<!--                </div>-->
<!--            </div>-->
<!--        </div>-->
<!--    </div>-->
<!--</div>-->

<script>
document.addEventListener('DOMContentLoaded', function() {
    loadDashboardData();
});

function loadDashboardData() {
    console.log('Loading dashboard data...');
    fetch('../api/get_dashboard_data.php')
        .then(response => {
            console.log('Response status:', response.status);
            return response.text();
        })
        .then(text => {
            console.log('Raw response:', text);
            try {
                const data = JSON.parse(text);
                console.log('Parsed data:', data);
                if (data.success) {
                    updateStats(data.stats);
                    updateRecentBookings(data.recent_bookings);
                } else {
                    console.error('Error loading dashboard data:', data.message);
                    showError('Failed to load dashboard data: ' + data.message);
                }
            } catch (e) {
                console.error('JSON parse error:', e);
                showError('Invalid response from server');
            }
        })
        .catch(error => {
            console.error('Fetch error:', error);
            showError('Network error while loading data: ' + error.message);
        });
}

function updateStats(stats) {
    document.getElementById('total-users').textContent = stats.total_users.toLocaleString();
    document.getElementById('today-bookings').textContent = stats.today_bookings.toLocaleString();
    document.getElementById('today-revenue').textContent = '₹' + stats.today_revenue.toLocaleString();
    document.getElementById('tatkal-today').textContent = stats.tatkal_today.toLocaleString();
}
function updateRecentBookings(bookings) {
    const container = document.getElementById('recent-bookings-container');
    const confirmed = (bookings || []).filter(
        b => String(b.status).trim().toLowerCase() === 'confirmed'
    );

    if (confirmed.length === 0) {
        container.innerHTML = `
            <div class="text-center py-5">
                <i class="fas fa-calendar-times fa-3x text-muted mb-3"></i>
                <p class="text-muted">No confirmed bookings found</p>
            </div>
        `;
        return;
    }

    // Sort newest-first by date/time and pick top 5
    const sorted = confirmed.sort((a, b) => {
        const da = new Date(`${a.appointment_date} ${a.time_slot || ''}`);
        const db = new Date(`${b.appointment_date} ${b.time_slot || ''}`);
        return db - da;
    });
    const latestFive = sorted.slice(0, 5);

    let tableHTML = `
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Date</th>
                        <th>Time</th>
                        <th>Type</th>
                        <th>Amount</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
    `;

    latestFive.forEach(booking => {
        tableHTML += `
            <tr>
                <td>
                    <div class="d-flex align-items-center">
                        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center me-2" style="width: 35px; height: 35px;">
                            ${(booking.user_name || '').charAt(0).toUpperCase()}
                        </div>
                        ${escapeHtml(booking.user_name || '')}
                    </div>
                </td>
                <td>${escapeHtml(booking.appointment_date || '')}</td>
                <td>${escapeHtml(booking.time_slot || '')}</td>
                <td><span class="badge bg-info">${escapeHtml(booking.consultation_type || '')}</span></td>
                <td>₹${parseInt(booking.amount || 0, 10).toLocaleString()}</td>
                <td><span class="badge bg-success">Confirmed</span></td>
            </tr>
        `;
    });

    tableHTML += `
                </tbody>
            </table>
        </div>
    `;

    container.innerHTML = tableHTML;
}


function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function showError(message) {
    const container = document.getElementById('recent-bookings-container');
    container.innerHTML = `
        <div class="text-center py-5">
            <i class="fas fa-exclamation-triangle fa-3x text-danger mb-3"></i>
            <p class="text-danger">${message}</p>
        </div>
    `;
}
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>