<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

require_once "../../dbcon.php";
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS')
    exit(0);

$agent_id = isset($_GET['agent_id']) ? intval($_GET['agent_id']) : null;
$agent_where_users = $agent_id ? " WHERE agent_id = $agent_id" : "";
$agent_where_orders = $agent_id ? " JOIN users u ON u.id = orders.user_id WHERE u.agent_id = $agent_id" : "";
$agent_where_inquiries = $agent_id ? " JOIN users u ON u.id = inquiries.user_id WHERE u.agent_id = $agent_id" : "";

// --- Stats ---
$stats = [];
$q = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM users" . $agent_where_users);
$stats['total_users'] = (int) (mysqli_fetch_assoc($q)['cnt'] ?? 0);

if ($agent_id) {
    // For agents, show total cars available in general or cars they created? 
    // Usually total cars is fine, but maybe they want to see orders relevance.
    $stats['total_cars'] = (int) (mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM cars"))['cnt'] ?? 0);
} else {
    $stats['total_cars'] = (int) (mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM cars"))['cnt'] ?? 0);
}

$q = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM inquiries" . ($agent_id ? " i JOIN users u ON u.id = i.user_id WHERE u.agent_id = $agent_id" : ""));
$stats['total_inquiries'] = (int) (mysqli_fetch_assoc($q)['cnt'] ?? 0);

$q = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM orders " . ($agent_id ? " o JOIN users u ON u.id = o.user_id WHERE u.agent_id = $agent_id AND o.status='pending'" : " WHERE status='pending'"));
$stats['pending_orders'] = (int) (mysqli_fetch_assoc($q)['cnt'] ?? 0);

$q = mysqli_query($conn, "SELECT COUNT(*) as cnt FROM orders " . ($agent_id ? " o JOIN users u ON u.id = o.user_id WHERE u.agent_id = $agent_id AND DATE(o.created_at) = CURDATE()" : " WHERE DATE(created_at) = CURDATE()"));
$stats['new_orders'] = (int) (mysqli_fetch_assoc($q)['cnt'] ?? 0);

// --- Monthly Orders Comparison (thisYear vs lastYear) ---
$ordersData = [];
for ($m = 1; $m <= 12; $m++) {
    $thisMonthQ = mysqli_query($conn, "
        SELECT COUNT(*) as cnt 
        FROM orders " . ($agent_id ? " o JOIN users u ON u.id = o.user_id " : "") . "
        WHERE MONTH(" . ($agent_id ? "o." : "") . "created_at) = $m AND YEAR(" . ($agent_id ? "o." : "") . "created_at) = YEAR(CURDATE())" . ($agent_id ? " AND u.agent_id = $agent_id" : "") . "
    ");
    $lastMonthQ = mysqli_query($conn, "
        SELECT COUNT(*) as cnt 
        FROM orders " . ($agent_id ? " o JOIN users u ON u.id = o.user_id " : "") . "
        WHERE MONTH(" . ($agent_id ? "o." : "") . "created_at) = $m AND YEAR(" . ($agent_id ? "o." : "") . "created_at) = YEAR(CURDATE())-1" . ($agent_id ? " AND u.agent_id = $agent_id" : "") . "
    ");

    $ordersData[] = [
        'month' => date('M', mktime(0, 0, 0, $m, 1)),
        'thisMonth' => (int) (mysqli_fetch_assoc($thisMonthQ)['cnt'] ?? 0),
        'lastMonth' => (int) (mysqli_fetch_assoc($lastMonthQ)['cnt'] ?? 0)
    ];
}

// --- Revenue ---
$today = date('Y-m-d');

// Helper for revenue queries
function getRevenueQuery($conn, $where_clause, $agent_id) {
    $join = $agent_id ? " JOIN users u ON u.id = o.user_id " : "";
    $agent_filter = $agent_id ? " AND u.agent_id = $agent_id" : "";
    $q = mysqli_query($conn, "SELECT SUM(total_amount) as revenue FROM orders o $join WHERE o.status='completed' AND $where_clause $agent_filter");
    return (float) (mysqli_fetch_assoc($q)['revenue'] ?? 0);
}

$revenueDay = getRevenueQuery($conn, "DATE(o.updated_at) = '$today'", $agent_id);

$startWeek = date('Y-m-d', strtotime('monday this week'));
$endWeek = date('Y-m-d', strtotime('sunday this week'));
$revenueWeek = getRevenueQuery($conn, "DATE(o.updated_at) BETWEEN '$startWeek' AND '$endWeek'", $agent_id);

$startMonth = date('Y-m-01');
$endMonth = date('Y-m-t');
$revenueMonth = getRevenueQuery($conn, "DATE(o.updated_at) BETWEEN '$startMonth' AND '$endMonth'", $agent_id);

$startYear = date('Y-01-01');
$endYear = date('Y-12-31');
$revenueYear = getRevenueQuery($conn, "DATE(o.updated_at) BETWEEN '$startYear' AND '$endYear'", $agent_id);

// --- Weekly Breakdown for Chart ---
$revenueWeekly = [];
$firstDayOfMonth = date('Y-m-01');
$currentDay = date('Y-m-d');

for ($w = 1; $w <= 5; $w++) {
    $start = date('Y-m-d', strtotime($firstDayOfMonth . " +" . ($w - 1) . " week"));
    $end = date('Y-m-d', strtotime($start . " +6 days"));
    if ($start > $currentDay) break;

    $rev = getRevenueQuery($conn, "DATE(o.updated_at) BETWEEN '$start' AND '$end'", $agent_id);
    $revenueWeekly[] = [
        'name' => "Week $w",
        'revenue' => $rev
    ];
}

// --- Latest Inquiries ---
$latestInquiries = [];
$qSelection = "SELECT i.*, u.full_name as user_name 
               FROM inquiries i 
               JOIN users u ON u.id = i.user_id ";
if ($agent_id) {
    $qSelection .= " WHERE u.agent_id = $agent_id ";
}
$qSelection .= " ORDER BY i.created_at DESC LIMIT 5";

$q = mysqli_query($conn, $qSelection);
while ($row = mysqli_fetch_assoc($q)) {
    $latestInquiries[] = $row;
}

echo json_encode([
    'status' => 'success',
    'data' => [
        'stats' => $stats,
        'ordersData' => $ordersData,
        'revenueDay' => $revenueDay,
        'revenueWeek' => $revenueWeek,
        'revenueMonth' => $revenueMonth,
        'revenueYear' => $revenueYear,
        'revenueWeekly' => $revenueWeekly,
        'latestInquiries' => $latestInquiries
    ]
]);
exit;
?>
