<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
use App\Core\App;
use App\Core\Response;
use App\Modules\Accounting\Models\BankReconciliation;
use App\Modules\Accounting\Models\BankAccount;
use App\Modules\Accounting\Services\BankReconciliationService;

class BankReconciliationController extends Controller
{
    public function index(): Response
    {
        $this->authorize('accounting.bank_recon.view');

        $reconciliations = BankReconciliation::query()
            ->where('is_archived', '=', 0)
            ->orderBy('reconciliation_date', 'DESC')
            ->limit(50)
            ->get();

        $db = App::getInstance()->db();
        foreach ($reconciliations as &$r) {
            $ba = $db->selectOne("SELECT account_name_ar FROM bank_accounts WHERE id = ?", [(int) $r['bank_account_id']]);
            $r['bank_account_name'] = $ba['account_name_ar'] ?? '—';
        }
        unset($r);

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

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

        $bankAccounts = BankAccount::getActive();

        return $this->view('Accounting/Views/bank_reconciliation/create', [
            'bank_accounts' => $bankAccounts,
        ]);
    }

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

        $this->validate($_POST, [
            'bank_account_id'  => 'required|numeric',
            'statement_date'   => 'required',
            'statement_balance' => 'required|numeric',
        ]);

        $result = BankReconciliationService::create($_POST);

        $session = App::getInstance()->session();
        if ($result['success']) {
            $session->flash('_alerts', [['type' => 'success', 'message' => 'تم إنشاء المطابقة البنكية']]);
            return $this->redirect('/accounting/bank-reconciliation/' . $result['reconciliation_id']);
        }

        $session->flash('_alerts', [['type' => 'error', 'message' => $result['error']]]);
        return $this->redirect('/accounting/bank-reconciliation/create');
    }

    public function show(int $id): Response
    {
        $this->authorize('accounting.bank_recon.view');

        $recon = BankReconciliation::findOrFail($id);
        $items = $recon->items();
        $bankAccount = BankAccount::find((int) $recon->bank_account_id);

        $transactions = BankReconciliationService::getUnreconciledTransactions(
            (int) $recon->bank_account_id,
            $recon->statement_date
        );

        return $this->view('Accounting/Views/bank_reconciliation/show', [
            'recon'        => $recon->toArray(),
            'items'        => $items,
            'bank_account' => $bankAccount ? $bankAccount->toArray() : [],
            'transactions' => $transactions,
        ]);
    }

    public function addItem(int $id): Response
    {
        $this->authorize('accounting.bank_recon.manage');

        $this->validate($_POST, [
            'item_type'      => 'required',
            'description_ar' => 'required',
            'amount'         => 'required|numeric',
        ]);

        $result = BankReconciliationService::addItem($id, $_POST);

        $session = App::getInstance()->session();
        if ($result['success']) {
            $session->flash('_alerts', [['type' => 'success', 'message' => 'تم إضافة بند المطابقة']]);
        } else {
            $session->flash('_alerts', [['type' => 'error', 'message' => $result['error']]]);
        }

        return $this->redirect('/accounting/bank-reconciliation/' . $id);
    }

    public function complete(int $id): Response
    {
        $this->authorize('accounting.bank_recon.manage');

        $result = BankReconciliationService::complete($id);

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

        return $this->redirect('/accounting/bank-reconciliation/' . $id);
    }
}
