<?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 FiscalYearController extends Controller
{
    public function index(): Response
    {
        $this->authorize('accounting.fiscal_year.view');

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

        return $this->view('Accounting/Views/fiscal_years/index', [
            'years' => $years,
        ]);
    }

    public function create(): Response
    {
        $this->authorize('accounting.fiscal_year.manage');

        $config = App::getInstance()->config('app');
        $startMonth = (int) ($config['financial_year_start_month'] ?? 7);
        $currentYear = (int) date('Y');

        return $this->view('Accounting/Views/fiscal_years/create', [
            'start_month' => $startMonth,
            'current_year' => $currentYear,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('accounting.fiscal_year.manage');

        $data = $this->validate($request->all(), [
            'name_ar'    => 'required',
            'name_en'    => 'required',
            'start_date' => 'required',
            'end_date'   => 'required',
        ]);

        // Validate dates
        if (strtotime($data['end_date']) <= strtotime($data['start_date'])) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', [['type' => 'error', 'message' => 'تاريخ النهاية يجب أن يكون بعد تاريخ البداية']]);
            return $this->redirect('/accounting/fiscal-years/create');
        }

        // Check overlap
        $db = App::getInstance()->db();
        $overlap = $db->selectOne(
            "SELECT id FROM fiscal_years
             WHERE is_archived = 0
               AND ((start_date <= ? AND end_date >= ?) OR (start_date <= ? AND end_date >= ?))",
            [$data['end_date'], $data['start_date'], $data['start_date'], $data['end_date']]
        );

        if ($overlap) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', [['type' => 'error', 'message' => 'يوجد تداخل مع سنة مالية أخرى']]);
            return $this->redirect('/accounting/fiscal-years/create');
        }

        $isCurrent = (int) ($request->post('is_current', 0));
        if ($isCurrent) {
            $db->execute("UPDATE fiscal_years SET is_current = 0 WHERE is_current = 1");
        }

        $fy = FiscalYear::create([
            'name_ar'    => $data['name_ar'],
            'name_en'    => $data['name_en'],
            'start_date' => $data['start_date'],
            'end_date'   => $data['end_date'],
            'is_current' => $isCurrent,
            'status'     => 'open',
            'notes'      => $request->post('notes'),
        ]);

        $session = App::getInstance()->session();
        $session->flash('_alerts', [['type' => 'success', 'message' => 'تم إنشاء السنة المالية بنجاح']]);
        return $this->redirect('/accounting/fiscal-years');
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('accounting.fiscal_year.view');

        $fy = FiscalYear::findOrFail((int) $id);
        $periods = PeriodClosingService::getPeriodSummary((int) $id);

        return $this->view('Accounting/Views/fiscal_years/show', [
            'fiscal_year' => $fy->toArray(),
            'periods'     => $periods,
        ]);
    }

    public function close(Request $request, string $id): Response
    {
        $this->authorize('accounting.fiscal_year.close');

        $result = PeriodClosingService::closeFiscalYear((int) $id);

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

        return $this->redirect('/accounting/fiscal-years/' . (int) $id);
    }
}
