<?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\BankAccountRepository;
use App\Services\BankAccountService;
use Throwable;

final class BankAccountController
{
    private \PDO $pdo; private BankAccountRepository $repo; private BankAccountService $service; private FinanceRouteContext $routeContext;
    public function __construct(){ $this->pdo=DB::pdo(); $this->repo=new BankAccountRepository($this->pdo); $this->service=new BankAccountService($this->pdo,$this->repo); $this->routeContext = new FinanceRouteContext(); }
    public function index(): void { Auth::requireLogin(); $this->service->ensureSchema(); require_permission('banks.accounts.view'); $q=trim((string)Request::get('q','')); $accounts=$this->repo->search($q); Response::view('pages/banks/accounts_index', ['accounts'=>$accounts,'balances'=>$this->service->balancesFor($accounts),'q'=>$q,'page_title'=>'الحسابات البنكية','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'البنوك'],['label'=>'الحسابات البنكية']], 'bank_accounts_url'=>$this->routeContext->bankAccountsPath(), 'bank_account_form_url'=>$this->routeContext->bankAccountFormPath(), 'bank_balances_url'=>$this->routeContext->bankBalancesPath()]); }
    public function form(): void { Auth::requireLogin(); $this->service->ensureSchema(); $id=(int)Request::get('id',0); require_permission($id>0?'banks.accounts.edit':'banks.accounts.create'); try{ if(Request::isPost()){ Csrf::verify(); $this->service->save($id, Request::all()); Response::flash('success','تم حفظ الحساب البنكي.'); Response::redirect($this->routeContext->bankAccountsPath()); return; } Response::view('pages/banks/account_form', $this->service->loadForm($id)+['page_title'=>$id>0?'تعديل حساب بنكي':'إضافة حساب بنكي','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'البنوك'],['label'=>'الحسابات البنكية','url'=>$this->routeContext->bankAccountsPath()],['label'=>$id>0?'تعديل حساب بنكي':'إضافة حساب بنكي']], 'bank_accounts_url'=>$this->routeContext->bankAccountsPath()]); } catch(Throwable $e){ Response::flash('danger','حدث خطأ أثناء الحفظ: '.$e->getMessage()); Response::redirect($this->routeContext->bankAccountFormPath($id)); } }
    public function balancesReport(): void { Auth::requireLogin(); $this->service->ensureSchema(); require_permission('banks.accounts.view'); $q=trim((string)Request::get('q','')); $data=$this->service->balancesReport($q); Response::view('pages/banks/balances_report', ['rows'=>$data['rows'],'q'=>$q,'totals'=>$data['totals'],'page_title'=>'تقرير أرصدة البنوك','breadcrumbs'=>[$this->routeContext->dashboardCrumb(),['label'=>'البنوك'],['label'=>'أرصدة البنوك']], 'bank_accounts_url'=>$this->routeContext->bankAccountsPath()]); }
}
