<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
use App\Core\Request;
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(Request $request): Response
    {
        $this->authorize('accounting.bank_recon.view');

        $db = App::getInstance()->db();
        $statusFilter = $request->get('status', '');
        $bankAccountFilter = $request->get('bank_account_id') ? (int) $request->get('bank_account_id') : 0;

        $where = 'br.is_archived = 0';
        $params = [];

        if ($statusFilter !== '') {
            $where .= ' AND br.status = ?';
            $params[] = $statusFilter;
        }
        if ($bankAccountFilter > 0) {
            $where .= ' AND br.bank_account_id = ?';
            $params[] = $bankAccountFilter;
        }

        $reconciliations = $db->select(
            "SELECT br.*, ba.account_name_ar as bank_account_name
             FROM bank_reconciliations br
             LEFT JOIN bank_accounts ba ON ba.id = br.bank_account_id
             WHERE {$where}
             ORDER BY br.reconciliation_date DESC
             LIMIT 100",
            $params
        );

        $bankAccounts = $db->select("SELECT id, account_name_ar FROM bank_accounts WHERE is_archived = 0 ORDER BY account_name_ar");

        return $this->view('Accounting/Views/bank_reconciliation/index', [
            'reconciliations' => $reconciliations,
            'bank_accounts'   => $bankAccounts,
            'filters'         => ['status' => $statusFilter, 'bank_account_id' => $bankAccountFilter],
        ]);
    }

    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(Request $request): Response
    {
        $this->authorize('accounting.bank_recon.manage');

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

        $result = BankReconciliationService::create($request->all());

        $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(Request $request, string $id): Response
    {
        $this->authorize('accounting.bank_recon.view');

        $recon = BankReconciliation::findOrFail((int) $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(Request $request, string $id): Response
    {
        $this->authorize('accounting.bank_recon.manage');

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

        $result = BankReconciliationService::addItem((int) $id, $request->all());

        $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(Request $request, string $id): Response
    {
        $this->authorize('accounting.bank_recon.manage');

        $result = BankReconciliationService::complete((int) $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);
    }
}
