<?php
declare(strict_types=1);

namespace App\Modules\AcademyContracts\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

class ReportController extends Controller
{
    public function guaranteeReport(Request $request): Response
    {
        $db = App::getInstance()->db();

        $filterAcademy = trim((string) $request->get('academy_id', ''));
        $filterFrom = trim((string) $request->get('from_month', ''));
        $filterTo = trim((string) $request->get('to_month', ''));

        if ($filterFrom === '') {
            $filterFrom = date('Y-01');
        }
        if ($filterTo === '') {
            $filterTo = date('Y-m');
        }

        $where = ["ac.status = 'active'", 'ac.is_archived = 0'];
        $params = [];

        if ($filterAcademy !== '') {
            $where[] = 'ac.academy_id = ?';
            $params[] = (int) $filterAcademy;
        }

        $whereSql = implode(' AND ', $where);

        $contracts = $db->select(
            "SELECT ac.id, ac.contract_number, ac.academy_id, ac.minimum_revenue_guarantee,
                    ac.club_commission_pct, ac.academy_share_pct,
                    a.name_ar as academy_name
             FROM academy_contracts ac
             INNER JOIN academies a ON a.id = ac.academy_id
             WHERE {$whereSql}
             ORDER BY a.name_ar ASC",
            $params
        );

        $reportData = [];
        foreach ($contracts as $contract) {
            $settlements = $db->select(
                "SELECT period_month, total_revenue, minimum_guarantee, revenue_surplus,
                        revenue_shortfall, direction, net_amount, status
                 FROM academy_settlements
                 WHERE contract_id = ? AND period_month >= ? AND period_month <= ?
                 ORDER BY period_month ASC",
                [(int) $contract['id'], $filterFrom, $filterTo]
            );

            $totalRevenue = 0.0;
            $totalGuarantee = 0.0;
            $totalDeficit = 0.0;
            $totalSurplus = 0.0;

            foreach ($settlements as $s) {
                $totalRevenue += (float) $s['total_revenue'];
                $totalGuarantee += (float) $s['minimum_guarantee'];
                $totalDeficit += (float) $s['revenue_shortfall'];
                $totalSurplus += (float) $s['revenue_surplus'];
            }

            $reportData[] = [
                'contract'        => $contract,
                'settlements'     => $settlements,
                'total_revenue'   => $totalRevenue,
                'total_guarantee' => $totalGuarantee,
                'total_deficit'   => $totalDeficit,
                'total_surplus'   => $totalSurplus,
                'net_position'    => $totalRevenue - $totalGuarantee,
            ];
        }

        $academies = $db->select(
            "SELECT id, name_ar FROM academies WHERE is_active = 1 AND is_archived = 0 ORDER BY name_ar ASC"
        );

        return $this->view('AcademyContracts.Views.guarantee_report', [
            'reportData'    => $reportData,
            'academies'     => $academies,
            'filterAcademy' => $filterAcademy,
            'filterFrom'    => $filterFrom,
            'filterTo'      => $filterTo,
        ]);
    }
}
