<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
use App\Core\App;
use App\Core\Response;
use App\Modules\Accounting\Models\FiscalYear;
use App\Modules\Accounting\Services\PeriodClosingService;

class PeriodClosingController extends Controller
{
    public function index(): Response
    {
        $this->authorize('accounting.period.view');

        $currentFY = FiscalYear::current();
        $fiscalYearId = (int) ($_GET['fiscal_year_id'] ?? ($currentFY ? $currentFY->id : 0));

        $periods = [];
        $fiscalYear = null;
        if ($fiscalYearId > 0) {
            $fiscalYear = FiscalYear::find($fiscalYearId);
            $periods = PeriodClosingService::getPeriodSummary($fiscalYearId);
        }

        $fiscalYears = FiscalYear::query()
            ->where('is_archived', '=', 0)
            ->orderBy('start_date', 'DESC')
            ->get();

        return $this->view('Accounting/Views/period_closing/index', [
            'periods'       => $periods,
            'fiscal_year'   => $fiscalYear ? $fiscalYear->toArray() : null,
            'fiscal_years'  => $fiscalYears,
            'fiscal_year_id' => $fiscalYearId,
        ]);
    }

    public function closeMonth(): Response
    {
        $this->authorize('accounting.period.close');

        $fiscalYearId = (int) ($_POST['fiscal_year_id'] ?? 0);
        $period = $_POST['period'] ?? '';

        if ($fiscalYearId <= 0 || empty($period)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', [['type' => 'error', 'message' => 'بيانات غير مكتملة']]);
            return $this->redirect('/accounting/period-closing');
        }

        $result = PeriodClosingService::closeMonth($fiscalYearId, $period);

        $session = App::getInstance()->session();
        if ($result['success']) {
            $session->flash('_alerts', [['type' => 'success', 'message' => 'تم إغلاق الفترة ' . $period . ' بنجاح']]);
        } else {
            $session->flash('_alerts', [['type' => 'error', 'message' => $result['error']]]);
        }

        return $this->redirect('/accounting/period-closing?fiscal_year_id=' . $fiscalYearId);
    }

    public function reopenMonth(): Response
    {
        $this->authorize('accounting.period.reopen');

        $fiscalYearId = (int) ($_POST['fiscal_year_id'] ?? 0);
        $period = $_POST['period'] ?? '';
        $reason = $_POST['reason'] ?? '';

        if ($fiscalYearId <= 0 || empty($period) || empty($reason)) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', [['type' => 'error', 'message' => 'يجب تقديم سبب إعادة الفتح']]);
            return $this->redirect('/accounting/period-closing');
        }

        $result = PeriodClosingService::reopenMonth($fiscalYearId, $period, $reason);

        $session = App::getInstance()->session();
        if ($result['success']) {
            $session->flash('_alerts', [['type' => 'success', 'message' => 'تم إعادة فتح الفترة ' . $period]]);
        } else {
            $session->flash('_alerts', [['type' => 'error', 'message' => $result['error']]]);
        }

        return $this->redirect('/accounting/period-closing?fiscal_year_id=' . $fiscalYearId);
    }
}
