<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
use App\Core\Request;
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(Request $request): Response
    {
        $this->authorize('accounting.period.view');

        $currentFY = FiscalYear::current();
        $fiscalYearId = (int) ($request->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(Request $request): Response
    {
        $this->authorize('accounting.period.close');

        $fiscalYearId = (int) ($request->post('fiscal_year_id', 0));
        $period = $request->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(Request $request): Response
    {
        $this->authorize('accounting.period.reopen');

        $fiscalYearId = (int) ($request->post('fiscal_year_id', 0));
        $period = $request->post('period', '');
        $reason = $request->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);
    }
}
