<?php

declare(strict_types=1);

namespace App\Modules\Reporting\Presentation\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Reporting\Application\Services\AlertsDashboardService;
use Throwable;

final class AlertsDashboardController
{
    public function __construct(private ?AlertsDashboardService $service = null)
    {
        $this->service ??= new AlertsDashboardService(db());
    }

    public function index(): void
    {
        Auth::requireLogin();
        require_permission('alerts.view');

        $daysAhead = max(1, Request::int('days_ahead', 7));
        $agingDays = max(1, Request::int('aging_days', 30));
        $cashMin = max(0.0, (float) Request::get('cash_min', '1000'));
        $bankMin = max(0.0, (float) Request::get('bank_min', '1000'));
        $draftDays = max(1, Request::int('draft_days', 7));
        $stagnantDays = max(1, Request::int('stagnant_days', 60));

        try {
            $data = $this->service->dashboard($daysAhead, $agingDays, $cashMin, $bankMin, $draftDays, $stagnantDays);
        } catch (Throwable $e) {
            error_log('Alerts dashboard failed: ' . $e->getMessage() . "\n" . (string) $e);
            $data = $this->emptyDashboard($daysAhead, $agingDays, $cashMin, $bankMin, $draftDays, $stagnantDays) + [
                'alertsError' => 'تعذر تحميل بعض بيانات التنبيهات بسبب اختلاف في مخطط قاعدة البيانات أو بيانات ناقصة. تم فتح الصفحة بوضع آمن.',
            ];
        }

        Response::view('pages/alerts_dashboard', $data + [
            'page_title' => 'لوحة التنبيهات',
            'breadcrumbs' => [
                ['label' => 'لوحة التحكم', 'url' => '/admin/dashboard'],
                ['label' => 'لوحة التنبيهات'],
            ],
        ]);
    }
    /**
     * @return array<string,mixed>
     */
    private function emptyDashboard(
        int $daysAhead,
        int $agingDays,
        float $cashMin,
        float $bankMin,
        int $draftDays,
        int $stagnantDays
    ): array {
        $today = date('Y-m-d');
        $future = date('Y-m-d', strtotime('+' . $daysAhead . ' days'));
        $cutoff = date('Y-m-d', strtotime('-' . $agingDays . ' days'));
        $draftCutoff = date('Y-m-d H:i:s', strtotime('-' . $draftDays . ' days'));
        $stagnantCutoff = date('Y-m-d H:i:s', strtotime('-' . $stagnantDays . ' days'));

        $counts = [
            'checks' => ['returned' => 0, 'due' => 0, 'total' => 0],
            'inventory' => ['total' => 0],
            'parties' => ['customers' => 0, 'suppliers' => 0, 'total' => 0],
            'treasury' => ['cashboxes' => 0, 'banks' => 0, 'total' => 0],
            'drafts' => ['total' => 0],
            'total' => 0,
        ];

        return compact('daysAhead', 'agingDays', 'cashMin', 'bankMin', 'draftDays', 'stagnantDays', 'counts', 'today', 'future', 'cutoff', 'draftCutoff', 'stagnantCutoff') + [
            'checkReturned' => [],
            'checkDueToday' => [],
            'checkDueSoon' => [],
            'checkOverdue' => [],
            'inventoryRows' => [],
            'stagnantRows' => [],
            'customerOverdue' => [],
            'supplierDue' => [],
            'cashboxRows' => [],
            'bankRows' => [],
            'draftSales' => [],
            'draftPurchases' => [],
            'draftSalesReturns' => [],
            'draftPurchaseReturns' => [],
        ];
    }

}
