<?php
require_once __DIR__ . '/config.php';

$currentUser = requireAuth();
$db = getDB();
$action = $_GET['action'] ?? 'overview';

header('Content-Type: application/json');

switch ($action) {

    case 'overview':
        // Dashboard stats
        $totalLeads = $db->query("SELECT COUNT(*) FROM leads")->fetchColumn();
        $totalCustomers = $db->query("SELECT COUNT(*) FROM customers")->fetchColumn();
        $activeBookings = $db->query("SELECT COUNT(*) FROM bookings WHERE status IN ('pending','confirmed')")->fetchColumn();
        $revenue = $db->query("SELECT COALESCE(SUM(amount),0) FROM payments WHERE status='completed'")->fetchColumn();
        $monthRevenue = $db->query("SELECT COALESCE(SUM(amount),0) FROM payments WHERE status='completed' AND MONTH(paid_date)=MONTH(NOW()) AND YEAR(paid_date)=YEAR(NOW())")->fetchColumn();
        $conversionRate = $totalLeads > 0 ? round(($db->query("SELECT COUNT(*) FROM leads WHERE status='booked'")->fetchColumn() / $totalLeads) * 100, 1) : 0;
        $leadsThisMonth = $db->query("SELECT COUNT(*) FROM leads WHERE MONTH(created_at)=MONTH(NOW()) AND YEAR(created_at)=YEAR(NOW())")->fetchColumn();
        $outstanding = $db->query("SELECT COALESCE(SUM(b.total_amount - b.paid_amount),0) FROM bookings b WHERE b.status != 'cancelled'")->fetchColumn();

        jsonResponse(['success' => true, 'data' => [
            'total_leads' => $totalLeads,
            'total_customers' => $totalCustomers,
            'active_bookings' => $activeBookings,
            'total_revenue' => $revenue,
            'month_revenue' => $monthRevenue,
            'conversion_rate' => $conversionRate,
            'leads_this_month' => $leadsThisMonth,
            'outstanding' => max(0, $outstanding),
        ]]);
        break;

    case 'lead_pipeline':
        $rows = $db->query("SELECT status, COUNT(*) as count FROM leads GROUP BY status")->fetchAll();
        jsonResponse(['success' => true, 'data' => $rows]);
        break;

    case 'monthly_revenue':
        $months = $db->query("
            SELECT DATE_FORMAT(paid_date, '%Y-%m') as month, 
                   DATE_FORMAT(paid_date, '%b %Y') as label,
                   COALESCE(SUM(amount),0) as total
            FROM payments 
            WHERE status='completed' AND paid_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
            GROUP BY DATE_FORMAT(paid_date, '%Y-%m')
            ORDER BY month ASC
        ")->fetchAll();
        jsonResponse(['success' => true, 'data' => $months]);
        break;

    case 'lead_sources':
        $rows = $db->query("
            SELECT ls.name, ls.color, COUNT(l.id) as count
            FROM lead_sources ls
            LEFT JOIN leads l ON l.source_id = ls.id
            GROUP BY ls.id
            HAVING count > 0
            ORDER BY count DESC
        ")->fetchAll();
        jsonResponse(['success' => true, 'data' => $rows]);
        break;

    case 'agent_performance':
        $rows = $db->query("
            SELECT u.name, u.email,
                   COUNT(l.id) as total_leads,
                   SUM(CASE WHEN l.status='booked' THEN 1 ELSE 0 END) as booked,
                   SUM(CASE WHEN l.status='lost' THEN 1 ELSE 0 END) as lost
            FROM users u
            LEFT JOIN leads l ON l.assigned_to = u.id
            WHERE u.role != 'viewer'
            GROUP BY u.id
            ORDER BY total_leads DESC
        ")->fetchAll();
        jsonResponse(['success' => true, 'data' => $rows]);
        break;

    case 'top_destinations':
        $rows = $db->query("
            SELECT destination, COUNT(*) as count
            FROM leads
            WHERE destination IS NOT NULL AND destination != ''
            GROUP BY destination
            ORDER BY count DESC
            LIMIT 10
        ")->fetchAll();
        jsonResponse(['success' => true, 'data' => $rows]);
        break;

    case 'recent_activity':
        $rows = $db->query("
            SELECT al.*, u.name as user_name
            FROM activity_log al
            LEFT JOIN users u ON al.user_id = u.id
            ORDER BY al.created_at DESC
            LIMIT 20
        ")->fetchAll();
        jsonResponse(['success' => true, 'data' => $rows]);
        break;

    case 'recent_leads':
        $rows = $db->query("
            SELECT l.*, ls.name as source_name, u.name as agent_name
            FROM leads l
            LEFT JOIN lead_sources ls ON l.source_id = ls.id
            LEFT JOIN users u ON l.assigned_to = u.id
            ORDER BY l.created_at DESC
            LIMIT 8
        ")->fetchAll();
        jsonResponse(['success' => true, 'data' => $rows]);
        break;

    default:
        jsonResponse(['success' => false, 'error' => 'Unknown action'], 400);
}
