<?php
declare(strict_types=1);

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

/**
 * ================= CORE & SECURITY =================
 */
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Logger.php';
require_once __DIR__ . '/../../security/auth_guard_api.php';

/**
 * ❌ CSRF intentionally skipped (READ-ONLY API)
 */

/**
 * ================= DB INSTANCE =================
 */
try {
    $pdo = Database::getInstance();
} catch (Throwable $e) {
    Response::error('Database connection unavailable');
    exit;
}

/**
 * ================= DATE RANGE =================
 */
$range = $_GET['range'] ?? 'today';

switch ($range) {
    case 'month':
        $dateCondition = "DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)";
        break;

    case 'quarter':
        $dateCondition = "DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH)";
        break;

    default:
        $range = 'today';
        $dateCondition = "DATE(created_at) = CURDATE()";
        break;
}

/**
 * ================= SAFE HELPERS =================
 */
function countSafe(PDO $pdo, string $sql): int
{
    try {
        return (int) $pdo->query($sql)->fetchColumn();
    } catch (Throwable $e) {
        return 0;
    }
}

function fetchSafe(PDO $pdo, string $sql): array
{
    try {
        return $pdo->query($sql)->fetchAll() ?: [];
    } catch (Throwable $e) {
        return [];
    }
}

/**
 * ================= DASHBOARD DATA =================
 */
$data = [
    'range' => $range,

    'counts' => [
        'dealers' => [
            'active'   => countSafe($pdo, "SELECT COUNT(*) FROM dealers WHERE status = 'active'"),
            'inactive' => countSafe($pdo, "SELECT COUNT(*) FROM dealers WHERE status = 'inactive'")
        ],
        'employees' => [
            'active'   => countSafe($pdo, "SELECT COUNT(*) FROM employees WHERE status = 'active'"),
            'inactive' => countSafe($pdo, "SELECT COUNT(*) FROM employees WHERE status = 'inactive'")
        ],
        'leads' => [
            'total'      => countSafe($pdo, "SELECT COUNT(*) FROM leads"),
            'this_range' => countSafe($pdo, "SELECT COUNT(*) FROM leads WHERE $dateCondition")
        ],
        'products' => [
            'retail'      => countSafe($pdo, "SELECT COUNT(*) FROM products WHERE type = 'retail'"),
            'hospitality' => countSafe($pdo, "SELECT COUNT(*) FROM products WHERE type = 'hospitality'")
        ],
        'blogs'       => countSafe($pdo, "SELECT COUNT(*) FROM blogs"),
        'faqs'        => countSafe($pdo, "SELECT COUNT(*) FROM faqs"),
        'pages'       => countSafe($pdo, "SELECT COUNT(*) FROM pages"),
        'subscribers' => countSafe($pdo, "SELECT COUNT(*) FROM subscribers")
    ],

    'lists' => [
        'latest_blogs' => fetchSafe($pdo, "
            SELECT id, title, created_at AS date, status
            FROM blogs
            ORDER BY created_at DESC
            LIMIT 5
        "),

        'latest_faqs' => fetchSafe($pdo, "
            SELECT id, question AS title, created_at AS date, status
            FROM faqs
            ORDER BY created_at DESC
            LIMIT 5
        "),

        'latest_pages' => fetchSafe($pdo, "
            SELECT id, title, created_at AS date, status
            FROM pages
            ORDER BY created_at DESC
            LIMIT 5
        "),

        'top_cities' => fetchSafe($pdo, "
            SELECT city, COUNT(*) AS total_leads
            FROM leads
            GROUP BY city
            ORDER BY total_leads DESC
            LIMIT 5
        "),

        'top_dealers' => fetchSafe($pdo, "
            SELECT d.name AS dealer_name,
                   d.city,
                   COUNT(l.id) AS total_leads,
                   d.rating,
                   d.status
            FROM dealers d
            LEFT JOIN leads l ON l.dealer_id = d.id
            GROUP BY d.id
            ORDER BY total_leads DESC
            LIMIT 5
        ")
    ]
];

/**
 * ================= RESPONSE =================
 */
Response::success('Dashboard data loaded', $data);
