<?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\CashPaymentRepository;
use App\Services\CashPaymentService;
use Throwable;

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

    public function index(): void
    {
        Auth::requireLogin(); $this->service->ensureSchema(); require_permission('cash.payments.view');
        $q=trim((string)Request::get('q','')); $from=trim((string)Request::get('from', date('Y-m-01'))); $to=trim((string)Request::get('to', date('Y-m-d'))); $page=max(1,(int)Request::get('page',1)); $pagination=paginate_rows($this->repo->search($q,$from,$to), $page, 25);
        Response::view('pages/cash/payments_index', ['rows'=>$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'],'q'=>$q,'from'=>$from,'to'=>$to,'page_title'=>'سندات الصرف','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'الخزنة'],['label'=>'سندات الصرف']], 'cash_payments_url'=>$this->routeContext->cashPaymentsPath(), 'cash_payment_form_url'=>$this->routeContext->cashPaymentFormPath(), 'cash_payment_view_base_url'=>$this->routeContext->cashPaymentViewPath()]);
    }
    public function form(): void
    {
        Auth::requireLogin(); $this->service->ensureSchema(); require_permission('cash.payments.create');
        try {
            if (Request::isPost()) { Csrf::verify(); $id=$this->service->save(Request::all(), (int)(current_user_id() ?: 0)); Response::flash('success','تم إنشاء سند الصرف'); Response::redirect($this->routeContext->cashPaymentViewPath($id)); return; }
            $data = $this->service->loadForm();
            if ((int)($data['form']['party_id'] ?? 0) > 0 && empty($data['form']['party_name'])) { $row = $this->repo->findPartyById((int)$data['form']['party_id']); $data['form']['party_name'] = (string)($row['name'] ?? ''); }
            Response::view('pages/cash/payment_form', $data + ['page_title'=>'إنشاء سند صرف','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'الخزنة'],['label'=>'سندات الصرف','url'=>$this->routeContext->cashPaymentsPath()],['label'=>'إنشاء']], 'cash_payments_url'=>$this->routeContext->cashPaymentsPath()]);
        } catch (Throwable $e) { Response::flash('danger','حدث خطأ أثناء الحفظ: '.$e->getMessage()); Response::redirect($this->routeContext->cashPaymentFormPath()); }
    }
    public function view(): void
    {
        Auth::requireLogin(); $this->service->ensureSchema(); require_permission('cash.payments.view');
        $id=(int)Request::get('id',0); if($id<=0){ Response::flash('danger','سند غير موجود'); Response::redirect($this->routeContext->cashPaymentsPath()); return; }
        try { Response::view('pages/cash/payment_view', $this->service->loadView($id) + ['page_title'=>'عرض سند صرف','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'الخزنة'],['label'=>'سندات الصرف','url'=>$this->routeContext->cashPaymentsPath()],['label'=>'عرض']], 'cash_payments_url'=>$this->routeContext->cashPaymentsPath()]); }
        catch (Throwable $e) { Response::flash('danger',$e->getMessage()); Response::redirect($this->routeContext->cashPaymentsPath()); }
    }
}
