<?php
// app/Models/Admin.php
// إحصائيات وعمليات على مستوى المنصة بالكامل (للمدير)

class Admin {

    /** كل الأعداد المجمّعة للوحة التحكم */
    public static function counts(): array {
        $pdo = db();

        $roles = ['owner'=>0,'driver'=>0,'officer'=>0,'admin'=>0];
        $r = $pdo->query("SELECT role, COUNT(*) c FROM users GROUP BY role")->fetchAll();
        foreach ($r as $row) $roles[$row['role']] = (int)$row['c'];

        $docs = ['valid'=>0,'expiring'=>0,'expired'=>0];
        $d = $pdo->query("SELECT status, COUNT(*) c FROM documents GROUP BY status")->fetchAll();
        foreach ($d as $row) $docs[$row['status']] = (int)$row['c'];

        return [
            'users_total'   => array_sum($roles),
            'roles'         => $roles,
            'vehicles'      => (int)$pdo->query("SELECT COUNT(*) FROM vehicles")->fetchColumn(),
            'documents'     => array_sum($docs),
            'docs'          => $docs,
            'templates'     => (int)$pdo->query("SELECT COUNT(*) FROM document_templates")->fetchColumn(),
            'violations'    => (int)$pdo->query("SELECT COUNT(*) FROM violations")->fetchColumn(),
            'unpaid'        => (int)$pdo->query("SELECT COUNT(*) FROM violations WHERE status='unpaid'")->fetchColumn(),
            'revenue'       => (float)$pdo->query("SELECT COALESCE(SUM(amount),0) FROM payment_logs")->fetchColumn(),
            'tows_active'   => (int)$pdo->query("SELECT COUNT(*) FROM tow_logs WHERE status='active'")->fetchColumn(),
        ];
    }

    public static function recentUsers(int $n = 6): array {
        $n = max(1, min($n, 50));
        $s = db()->query("SELECT id,name,email,role,created_at FROM users ORDER BY created_at DESC LIMIT $n");
        return $s->fetchAll();
    }

    public static function recentViolations(int $n = 6): array {
        $n = max(1, min($n, 50));
        $s = db()->query(
            "SELECT v.*, u.name AS officer_name
             FROM violations v LEFT JOIN users u ON u.id=v.officer_id
             ORDER BY v.issued_at DESC LIMIT $n"
        );
        return $s->fetchAll();
    }

    // ── Analytics ────────────────────────────────────────────

    /** Documents grouped by status */
    public static function docsByStatus(): array {
        $out = ['valid'=>0,'expiring'=>0,'expired'=>0,'unknown'=>0];
        foreach (db()->query("SELECT status, COUNT(*) c FROM documents GROUP BY status") as $r)
            $out[$r['status']] = (int)$r['c'];
        return $out;
    }

    /** Violations grouped by status */
    public static function violationsByStatus(): array {
        $out = ['unpaid'=>0,'paid'=>0,'cancelled'=>0];
        foreach (db()->query("SELECT status, COUNT(*) c FROM violations GROUP BY status") as $r)
            $out[$r['status']] = (int)$r['c'];
        return $out;
    }

    /** New user registrations per month for the last N months */
    public static function monthlyRegistrations(int $months = 6): array {
        $months = max(1, min($months, 24));
        $s = db()->prepare(
            "SELECT DATE_FORMAT(created_at,'%Y-%m') ym, COUNT(*) c
             FROM users
             WHERE created_at >= DATE_SUB(DATE_FORMAT(CURDATE(),'%Y-%m-01'), INTERVAL ? MONTH)
             GROUP BY ym ORDER BY ym"
        );
        $s->execute([$months-1]);
        return self::fillMonths($s->fetchAll(), $months);
    }

    /** Paid revenue per month for the last N months */
    public static function monthlyRevenue(int $months = 6): array {
        $months = max(1, min($months, 24));
        $s = db()->prepare(
            "SELECT DATE_FORMAT(paid_at,'%Y-%m') ym, COALESCE(SUM(amount),0) c
             FROM violations
             WHERE status='paid' AND paid_at IS NOT NULL
               AND paid_at >= DATE_SUB(DATE_FORMAT(CURDATE(),'%Y-%m-01'), INTERVAL ? MONTH)
             GROUP BY ym ORDER BY ym"
        );
        $s->execute([$months-1]);
        return self::fillMonths($s->fetchAll(), $months);
    }

    /** Documents grouped by template type (top usage) */
    public static function docsByType(int $limit = 8): array {
        $limit = max(1, min($limit, 30));
        $s = db()->query("SELECT type, COUNT(*) c FROM documents GROUP BY type ORDER BY c DESC LIMIT $limit");
        $out = [];
        foreach ($s as $r) $out[$r['type']] = (int)$r['c'];
        return $out;
    }

    /** Owners with the most vehicles */
    public static function topOwners(int $limit = 5): array {
        $limit = max(1, min($limit, 20));
        $s = db()->query(
            "SELECT u.name, COUNT(v.id) c
             FROM vehicles v JOIN users u ON u.id=v.owner_id
             GROUP BY v.owner_id ORDER BY c DESC LIMIT $limit"
        );
        return $s->fetchAll();
    }

    /** Ensure a continuous series of the last N months (zero-filled) */
    private static function fillMonths(array $rows, int $months): array {
        $map = [];
        foreach ($rows as $r) $map[$r['ym']] = (float)$r['c'];
        $out = [];
        for ($i = $months-1; $i >= 0; $i--) {
            $m = date('Y-m', strtotime("first day of -$i month"));
            $out[$m] = $map[$m] ?? 0;
        }
        return $out;
    }
}
