<?php

declare(strict_types=1);

namespace backend\controllers;

use common\models\Customer;
use common\models\CustomerPlan;
use common\models\Invoice;
use common\services\CustomerPlanService;
use common\services\InvoiceService;
use common\services\LeadService;
use yii\filters\AccessControl;
use yii\web\Controller;

/**
 * DashboardController — main overview page with cached metrics + live alerts.
 */
class DashboardController extends Controller
{
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [['allow' => true, 'roles' => ['@']]],
            ],
        ];
    }

    public function actionIndex(): string
    {
        $cache = \Yii::$app->cache;

        // Cached stats (5 min TTL)
        $stats = $cache->getOrSet('dashboard_stats', function () {
            $leadService    = new LeadService();
            $invoiceService = new InvoiceService();

            $leadCounts      = $leadService->getDashboardCounts();
            $revenueSummary  = $invoiceService->getRevenueSummary();
            $totalCustomers  = Customer::find()->where(['is_active' => 1])->count();
            $activePlans     = CustomerPlan::find()->where(['status' => CustomerPlan::STATUS_ACTIVE])->count();
            $pendingInvoices = Invoice::find()
                ->where(['IN', 'status', [Invoice::STATUS_UNPAID, Invoice::STATUS_PARTIAL]])
                ->count();

            return [
                'leads'            => $leadCounts,
                'total_customers'  => $totalCustomers,
                'active_plans'     => $activePlans,
                'pending_invoices' => $pendingInvoices,
                'revenue'          => $revenueSummary,
            ];
        }, 300);

        // Live alerts (not cached — always fresh)
        $cpService      = new CustomerPlanService();
        $expiringPlans  = $cpService->getExpiringPlans(7);

        $overdueInvoices = Invoice::find()
            ->with('customer')
            ->where(['IN', 'status', [Invoice::STATUS_UNPAID, Invoice::STATUS_PARTIAL]])
            ->andWhere(['IS NOT', 'due_date', null])
            ->andWhere(['<', 'due_date', date('Y-m-d')])
            ->orderBy(['due_date' => SORT_ASC])
            ->limit(5)
            ->all();

        // Recent leads (last 5)
        $recentLeads = \common\models\Lead::find()
            ->orderBy(['created_at' => SORT_DESC])
            ->limit(5)
            ->all();

        return $this->render('index', [
            'stats'          => $stats,
            'expiringPlans'  => $expiringPlans,
            'overdueInvoices'=> $overdueInvoices,
            'recentLeads'    => $recentLeads,
        ]);
    }
}
