<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Finance\Application\Services\FinanceRouteContext;
use App\Repositories\CashboxRepository;
use App\Services\CashboxService;
use Throwable;

final class CashboxController
{
    private \PDO $pdo; private CashboxRepository $repo; private CashboxService $service; private FinanceRouteContext $routeContext;
    public function __construct() { $this->pdo = DB::pdo(); $this->repo = new CashboxRepository($this->pdo); $this->service = new CashboxService($this->pdo, $this->repo); $this->routeContext = new FinanceRouteContext(); }

    public function index(): void
    {
        Auth::requireLogin(); $this->service->ensureSchema(); require_permission('cashboxes.view');
        $q = trim((string) Request::get('q', '')); $cashboxes = $this->repo->search($q);
        Response::view('pages/cashboxes/index', ['cashboxes'=>$cashboxes,'balances'=>$this->service->balancesFor($cashboxes),'q'=>$q,'page_title'=>'الخزن','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'الخزنة'],['label'=>'الخزن']], 'cashboxes_url'=>$this->routeContext->cashboxesPath(), 'cashbox_form_url'=>$this->routeContext->cashboxFormPath(), 'cashbox_ledger_url'=>$this->routeContext->cashboxLedgerPath(), 'cashbox_txn_url'=>$this->routeContext->cashboxTxnPath()]);
    }

    public function form(): void
    {
        Auth::requireLogin(); $this->service->ensureSchema(); $id=(int)Request::get('id',0); require_permission('cashboxes.create');
        try {
            if (Request::isPost()) { Csrf::verify(); $this->service->save($id, Request::all()); Response::flash('success', 'تم حفظ الخزنة.'); Response::redirect($this->routeContext->cashboxesPath()); return; }
            Response::view('pages/cashboxes/form', $this->service->loadForm($id) + ['page_title'=>$id>0?'تعديل خزنة':'إضافة خزنة','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'الخزن','url'=>$this->routeContext->cashboxesPath()],['label'=>$id>0?'تعديل خزنة':'إضافة خزنة']], 'cashboxes_url'=>$this->routeContext->cashboxesPath()]);
        } catch (Throwable $e) {
            Response::flash('danger', 'حدث خطأ أثناء الحفظ: '.$e->getMessage()); Response::redirect($this->routeContext->cashboxFormPath($id));
        }
    }

    public function ledger(): void
    {
        Auth::requireLogin(); $this->service->ensureSchema(); require_permission('cashboxes.report.view');
        $data = $this->service->loadLedger((int)Request::get('cashbox_id', 0), trim((string)Request::get('from','')), trim((string)Request::get('to','')));
        $page=max(1,(int)Request::get('page',1)); $pagination=paginate_rows($data['tx'], $page, 25);
        Response::view('pages/cashboxes/ledger', ['cashboxes'=>$data['cashboxes'],'cashbox_id'=>$data['cashboxId'],'from'=>$data['from'],'to'=>$data['to'],'openBal'=>$data['openBal'],'endBal'=>$data['endBal'],'inTotal'=>$data['inTotal'],'outTotal'=>$data['outTotal'],'tx'=>$pagination['items'],'page'=>$pagination['page'],'per_page'=>$pagination['per_page'],'total_pages'=>$pagination['total_pages'],'total_rows'=>$pagination['total_rows'],'from_row'=>$pagination['from'],'to_row'=>$pagination['to'],'page_title'=>'كشف حركة خزنة','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'الخزنة'],['label'=>'كشف حركة خزنة']], 'cashboxes_url'=>$this->routeContext->cashboxesPath()]);
    }

    public function txnForm(): void
    {
        Auth::requireLogin(); $this->service->ensureSchema(); require_permission('cashboxes.txn.create');
        $data = $this->service->loadTxnForm();
        if (Request::isPost()) {
            try { Csrf::verify(); $this->service->submitTxn(Request::all(), (int)(current_user_id() ?: 0)); $data['success'] = 'تم تسجيل الحركة بنجاح.'; $data['form']['amount']=''; $data['form']['notes']=''; }
            catch (Throwable $e) { $data['errors'] = [$e->getMessage()]; $data['form'] = array_merge($data['form'], Request::all()); }
        }
        Response::view('pages/cashboxes/txn_form', $data + ['page_title'=>'حركة خزنة','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'الخزنة'],['label'=>'حركة خزنة']], 'cashboxes_url'=>$this->routeContext->cashboxesPath()]);
    }
}
