<?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;
use App\Modules\AcademyContracts\Models\AcademySettlement;
use App\Modules\AcademyContracts\Services\SettlementService;
use App\Modules\Academies\Models\Academy;

class SettlementController extends Controller
{
    /**
     * List all settlements with filters and pagination.
     */
    public function index(Request $request): Response
    {
        $filters = [
            'q'            => trim((string) $request->get('q', '')),
            'status'       => trim((string) $request->get('status', '')),
            'academy_id'   => trim((string) $request->get('academy_id', '')),
            'period_month' => trim((string) $request->get('period_month', '')),
            'direction'    => trim((string) $request->get('direction', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = AcademySettlement::search($filters, 25, $page);

        return $this->view('AcademyContracts.Views.settlement_index', [
            'settlements' => $result['data'],
            'pagination'  => $result['pagination'],
            'filters'     => $filters,
            'statuses'    => AcademySettlement::getStatuses(),
            'directions'  => AcademySettlement::getDirections(),
            'academies'   => Academy::allActive(),
        ]);
    }

    /**
     * Show settlement detail page.
     */
    public function show(Request $request, string $id): Response
    {
        $settlement = AcademySettlement::find((int) $id);
        if (!$settlement) {
            return $this->redirect('/academy-settlements')->withError('التسوية غير موجودة');
        }

        $academy = Academy::find((int) $settlement->academy_id);

        $db = App::getInstance()->db();
        $contract = $db->selectOne(
            "SELECT * FROM academy_contracts WHERE id = ?",
            [(int) $settlement->contract_id]
        );

        return $this->view('AcademyContracts.Views.settlement_show', [
            'settlement' => $settlement,
            'academy'    => $academy,
            'contract'   => $contract,
        ]);
    }

    /**
     * Generate settlements for a given month (POST with month param).
     */
    public function generate(Request $request): Response
    {
        $month = trim((string) $request->post('period_month', ''));

        if ($month === '' || !preg_match('/^\d{4}-\d{2}$/', $month)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', [['type' => 'error', 'message' => 'الشهر مطلوب بالصيغة YYYY-MM']]);
            return $this->redirect('/academy-settlements');
        }

        $count = SettlementService::generateMonthlySettlements($month);

        if ($count > 0) {
            return $this->redirect('/academy-settlements?period_month=' . $month)
                ->withSuccess("تم إنشاء {$count} تسوية لشهر {$month}");
        }

        return $this->redirect('/academy-settlements')
            ->withWarning('لا توجد عقود نشطة تحتاج لتسوية أو تم إنشاء التسويات مسبقاً');
    }

    /**
     * Approve a settlement.
     */
    public function approve(Request $request, string $id): Response
    {
        $settlement = AcademySettlement::find((int) $id);
        if (!$settlement) {
            return $this->redirect('/academy-settlements')->withError('التسوية غير موجودة');
        }

        $session = App::getInstance()->session();
        $currentUser = $session->get('employee_id', 0);

        SettlementService::approveSettlement((int) $id, (int) $currentUser);

        return $this->redirect('/academy-settlements/' . $id)->withSuccess('تم اعتماد التسوية بنجاح');
    }
}
