<?php

declare(strict_types=1);

namespace App\Modules\Finance\Presentation\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Finance\Application\Services\CashPaymentCancelService;
use App\Modules\Finance\Application\Services\FinanceRouteContext;
use Throwable;

final class CashPaymentCancelController
{
    private FinanceRouteContext $routeContext;

    public function __construct(private ?CashPaymentCancelService $service = null)
    {
        $this->service ??= new CashPaymentCancelService(db());
        $this->routeContext = new FinanceRouteContext();
    }

    public function handle(): void
    {
        Auth::requireLogin();
        $this->service->ensureSchema();
        require_permission('cash.payments.cancel_expense');

        $id = (int) Request::input('id', 0);

        try {
            $row = $this->service->load($id);
        } catch (Throwable $e) {
            Response::flash('danger', $e->getMessage());
            Response::redirect($this->routeContext->cashPaymentsPath());
            return;
        }

        if (Request::isPost()) {
            try {
                Csrf::verify();
                $reason = trim((string) Request::post('cancel_reason', ''));
                $this->service->cancel($id, $reason, (int) (current_user_id() ?: 0));
                Response::flash('success', 'تم إلغاء سند المصروف وعكس أثره المالي بنجاح.');
            } catch (Throwable $e) {
                Response::flash('danger', 'تعذر إلغاء السند: ' . $e->getMessage());
            }

            Response::redirect($this->routeContext->cashPaymentViewPath($id));
            return;
        }

        Response::view('pages/cash/payment_cancel', [
            'row' => $row,
            'page_title' => 'إلغاء سند صرف مصروف',
            'breadcrumbs' => [
                $this->routeContext->dashboardCrumb(),
                ['label' => 'الخزنة'],
                ['label' => 'سندات الصرف', 'url' => $this->routeContext->cashPaymentsPath()],
                ['label' => 'عرض السند', 'url' => $this->routeContext->cashPaymentViewPath($id)],
                ['label' => 'إلغاء'],
            ],
        ]);
    }
}
