<?php
require_once 'auth.php';

// Require admin login
requireAdminLogin();

$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="day_management.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-alt fa-2x mb-2"></i>
                        <span>Manage Days</span>
                    </a>
                </div>
                <div class="col-md-3 mb-3">
                    <a href="quotes_management.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-quote-left fa-2x mb-2"></i>
                        <span>Manage Quotes</span>
                    </a>
                </div>
                <div class="col-md-3 mb-3">
                    <a href="booking_management.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-calendar-check fa-2x mb-2"></i>
                        <span>View Bookings</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="booking_management.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);
            console.log('Response headers:', response.headers);
            return response.text(); // Get as text first to see raw response
        })
        .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);
                console.error('Response text:', text);
                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');
    
    if (bookings.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 recent bookings found</p>
            </div>
        `;
        return;
    }
    
    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>
    `;
    
    bookings.forEach(booking => {
        const statusClass = booking.status === 'confirmed' ? 'success' : 
                          (booking.status === 'pending' ? 'warning' : 'danger');
        
        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>${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).toLocaleString()}</td>
                <td>
                    <span class="badge bg-${statusClass}">
                        ${booking.status.charAt(0).toUpperCase() + booking.status.slice(1)}
                    </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';
?>
