<?php
/**
 * AJAX endpoint for real-time stats refresh
 * Returns JSON data for dashboard and reports
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'includes/config.php';

try {
    $pdo = getDBConnection();
    
    // Get real-time booking stats
    $stmt = $pdo->query("SELECT 
                            COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY) THEN 1 END) as bookings_today,
                            COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as bookings_week,
                            COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as bookings_month
                         FROM bookings");
    $stats = $stmt->fetch();
    
    // Get fleet stats
    $total_vehicles = 0;
    $available = 0;
    $rented = 0;
    $maintenance = 0;
    $fleet_distribution = [];

    try {
        $stmt = $pdo->query("SELECT
                                COUNT(*) as total_vehicles,
                                COUNT(CASE WHEN status = 'available' THEN 1 END) as available,
                                COUNT(CASE WHEN status = 'rented' THEN 1 END) as rented,
                                COUNT(CASE WHEN status = 'maintenance' THEN 1 END) as maintenance
                             FROM vehicles");
        $fleet_stats = $stmt->fetch();
        $total_vehicles = (int)($fleet_stats['total_vehicles'] ?? 0);
        $available = (int)($fleet_stats['available'] ?? 0);
        $rented = (int)($fleet_stats['rented'] ?? 0);
        $maintenance = (int)($fleet_stats['maintenance'] ?? 0);

        $stmt = $pdo->query("SELECT status, COUNT(*) as count FROM vehicles GROUP BY status");
        $fleet_distribution = $stmt->fetchAll();
    } catch (Exception $e) {
        error_log("AJAX Stats error (fleet): " . $e->getMessage());
    }
    
    // Get payments stats
    $stmt = $pdo->query("SELECT COUNT(*) as pending_payments FROM payments WHERE status = 'pending'");
    $payment_stats = $stmt->fetch();
    
    // Get review stats
    $stmt = $pdo->query("SELECT status, COUNT(*) as count FROM reviews GROUP BY status");
    $review_stats = [];
    while ($row = $stmt->fetch()) {
        $review_stats[$row['status']] = $row['count'];
    }
    
    // Get monthly revenue
    $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) as monthly_revenue 
                         FROM bookings 
                         WHERE MONTH(created_at) = MONTH(CURDATE()) 
                         AND YEAR(created_at) = YEAR(CURDATE())
                         AND booking_status = 'completed'");
    $revenue = $stmt->fetch()['monthly_revenue'] ?? 0;

    // Get last month revenue
    $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) as total FROM bookings WHERE MONTH(created_at) = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND YEAR(created_at) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND booking_status = 'completed'");
    $last_month_revenue = $stmt->fetch()['total'] ?? 0;

    $revenue_growth = 0;
    if ($last_month_revenue > 0) {
        $revenue_growth = (($revenue - $last_month_revenue) / $last_month_revenue) * 100;
    } elseif ($revenue > 0) {
        $revenue_growth = 100;
    }

    // Bookings trend
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM bookings WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
    $this_week_bookings = $stmt->fetch()['count'] ?? 0;

    $stmt = $pdo->query("SELECT COUNT(*) as count FROM bookings WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND created_at < DATE_SUB(CURDATE(), INTERVAL 7 DAY)");
    $last_week_bookings = $stmt->fetch()['count'] ?? 0;

    $booking_trend = 0;
    if ($last_week_bookings > 0) {
        $booking_trend = (($this_week_bookings - $last_week_bookings) / $last_week_bookings) * 100;
    } elseif ($this_week_bookings > 0) {
        $booking_trend = 100;
    }

    // Active rentals
    $stmt = $pdo->query("SELECT COUNT(*) as count FROM bookings WHERE booking_status = 'active'");
    $active_rentals = $stmt->fetch()['count'] ?? 0;

    // Revenue chart data (last 7 days)
    $stmt = $pdo->query("SELECT DATE(created_at) as date, SUM(total_amount) as revenue
                         FROM bookings
                         WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
                         AND booking_status = 'completed'
                         GROUP BY DATE(created_at)");
    $raw_revenue_data = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $revenue_chart_labels = [];
    $revenue_chart_data = [];
    for ($i = 6; $i >= 0; $i--) {
        $date = date('Y-m-d', strtotime("-$i days"));
        $revenue_chart_labels[] = date('D', strtotime("-$i days"));
        $revenue_chart_data[] = (float)($raw_revenue_data[$date] ?? 0);
    }
    
    // Return JSON response
    echo json_encode([
        'success' => true,
        'data' => [
            'bookings_today' => (int)($stats['bookings_today'] ?? 0),
            'bookings_week' => (int)($stats['bookings_week'] ?? 0),
            'bookings_month' => (int)($stats['bookings_month'] ?? 0),
            'active_rentals' => (int)$active_rentals,
            'booking_trend' => (float)$booking_trend,
            'total_vehicles' => $total_vehicles,
            'available_vehicles' => $available,
            'rented_vehicles' => $rented,
            'maintenance_vehicles' => $maintenance,
            'fleet_distribution' => $fleet_distribution,
            'pending_payments' => (int)($payment_stats['pending_payments'] ?? 0),
            'monthly_revenue' => (float)($revenue ?? 0),
            'revenue_growth' => (float)$revenue_growth,
            'revenue_chart' => [
                'labels' => $revenue_chart_labels,
                'data' => $revenue_chart_data
            ],
            'review_stats' => [
                'pending' => (int)($review_stats['pending'] ?? 0),
                'published' => (int)($review_stats['published'] ?? 0),
                'flagged' => (int)($review_stats['flagged'] ?? 0),
                'hidden' => (int)($review_stats['hidden'] ?? 0)
            ],
            'timestamp' => date('Y-m-d H:i:s')
        ]
    ]);
    
} catch (PDOException $e) {
    // Return zero values if database error
    echo json_encode([
        'success' => false,
        'error' => 'Database error',
        'data' => [
            'bookings_today' => 0,
            'bookings_week' => 0,
            'bookings_month' => 0,
            'total_vehicles' => 0,
            'available_vehicles' => 0,
            'rented_vehicles' => 0,
            'maintenance_vehicles' => 0,
            'pending_payments' => 0,
            'monthly_revenue' => 0,
            'review_stats' => [
                'pending' => 0,
                'published' => 0,
                'flagged' => 0,
                'hidden' => 0
            ]
        ]
    ]);
}
?>