<?php
declare(strict_types=1);

namespace App\Modules\Dashboard\Services;

use App\Core\App;

final class DashboardDataService
{
    public static function getData(): array
    {
        $db = App::getInstance()->db();
        $data = [];

        // Summary Cards
        try {
            $data['total_active'] = (int) ($db->selectOne("SELECT COUNT(*) as c FROM members WHERE status = 'active' AND is_archived = 0")['c'] ?? 0);
        } catch (\Throwable $e) { $data['total_active'] = 0; }

        try {
            $data['new_this_month'] = (int) ($db->selectOne("SELECT COUNT(*) as c FROM members WHERE is_archived = 0 AND created_at >= ?", [date('Y-m-01')])['c'] ?? 0);
        } catch (\Throwable $e) { $data['new_this_month'] = 0; }

        try {
            $data['total_revenue_month'] = $db->selectOne("SELECT COALESCE(SUM(amount), 0) as t FROM payments WHERE is_voided = 0 AND payment_date >= ?", [date('Y-m-01')])['t'] ?? '0.00';
        } catch (\Throwable $e) { $data['total_revenue_month'] = '0.00'; }

        try {
            $data['pending_interviews'] = (int) ($db->selectOne("SELECT COUNT(*) as c FROM interviews WHERE decision = 'pending' AND status = 'scheduled'")['c'] ?? 0);
        } catch (\Throwable $e) { $data['pending_interviews'] = 0; }

        try {
            $data['overdue_installments'] = (int) ($db->selectOne("SELECT COUNT(DISTINCT p.member_id) as c FROM installment_plans p JOIN installment_schedule s ON s.installment_plan_id = p.id WHERE p.status = 'active' AND s.status = 'pending' AND s.due_date < CURDATE()")['c'] ?? 0);
        } catch (\Throwable $e) { $data['overdue_installments'] = 0; }

        try {
            $data['total_members_by_branch'] = $db->select("SELECT b.name_ar, COUNT(m.id) as cnt FROM branches b LEFT JOIN members m ON m.branch_id = b.id AND m.is_archived = 0 AND m.status = 'active' WHERE b.is_active = 1 GROUP BY b.id, b.name_ar ORDER BY cnt DESC");
        } catch (\Throwable $e) { $data['total_members_by_branch'] = []; }

        // Monthly revenue (last 6 months)
        try {
            $data['monthly_revenue'] = $db->select("SELECT DATE_FORMAT(payment_date, '%Y-%m') as month, SUM(amount) as total FROM payments WHERE is_voided = 0 AND payment_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY month ORDER BY month ASC");
        } catch (\Throwable $e) { $data['monthly_revenue'] = []; }

        // Recent activity
        try {
            $data['recent_activity'] = $db->select("SELECT employee_name, action, entity_type, entity_label, created_at FROM audit_trail ORDER BY created_at DESC LIMIT 15");
        } catch (\Throwable $e) { $data['recent_activity'] = []; }

        // Alerts
        $data['alerts'] = self::getAlerts($db);

        return $data;
    }

    private static function getAlerts($db): array
    {
        $alerts = [];

        // Children approaching 25
        try {
            $approaching25 = (int) ($db->selectOne("SELECT COUNT(*) as c FROM children WHERE is_archived = 0 AND gender = 'male' AND status = 'active' AND date_of_birth BETWEEN DATE_SUB(CURDATE(), INTERVAL 25 YEAR) AND DATE_SUB(CURDATE(), INTERVAL 24 YEAR 9 MONTH)")['c'] ?? 0);
            if ($approaching25 > 0) $alerts[] = ['type' => 'warning', 'message' => "{$approaching25} ابن ذكر يقترب من 25 سنة", 'link' => '/reports/view/RPT_CHILDREN_25'];
        } catch (\Throwable $e) {}

        // Expiring forms
        try {
            $expiringForms = (int) ($db->selectOne("SELECT COUNT(*) as c FROM form_submissions WHERE status = 'submitted' AND expires_at IS NOT NULL AND expires_at BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 3 DAY)")['c'] ?? 0);
            if ($expiringForms > 0) $alerts[] = ['type' => 'danger', 'message' => "{$expiringForms} استمارة تنتهي خلال 3 أيام", 'link' => '/forms/submissions'];
        } catch (\Throwable $e) {}

        // Overdue installments
        try {
            $overdueInst = (int) ($db->selectOne("SELECT COUNT(*) as c FROM installment_schedule s JOIN installment_plans p ON p.id = s.installment_plan_id WHERE p.status = 'active' AND s.status = 'pending' AND s.due_date < CURDATE()")['c'] ?? 0);
            if ($overdueInst > 0) $alerts[] = ['type' => 'danger', 'message' => "{$overdueInst} قسط متأخر", 'link' => '/installments?overdue_only=1'];
        } catch (\Throwable $e) {}

        // Honorary expiring
        try {
            $honoraryExpiring = (int) ($db->selectOne("SELECT COUNT(*) as c FROM honorary_members WHERE is_archived = 0 AND status = 'active' AND end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)")['c'] ?? 0);
            if ($honoraryExpiring > 0) $alerts[] = ['type' => 'info', 'message' => "{$honoraryExpiring} عضوية شرفية تنتهي خلال 30 يوم", 'link' => '/honorary'];
        } catch (\Throwable $e) {}

        return $alerts;
    }
}