<?php

class BankAccountController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('bank-accounts/index', [
            'title' => lang('adv_finance.bank_accounts'),
            'breadcrumbs' => [['label' => lang('adv_finance.title'), 'url' => '/advanced-finance/installments'], ['label' => lang('adv_finance.bank_accounts')]],
        ], 'app');
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int)$request->get('draw', 1);
        $start = (int)$request->get('start', 0);
        $length = (int)$request->get('length', 25);
        $search = $request->get('search')['value'] ?? '';

        $where = '1=1'; $params = [];
        if ($search) {
            $where .= ' AND (ba.account_code LIKE ? OR ba.bank_name_en LIKE ? OR ba.account_number LIKE ?)';
            $like = "%{$search}%"; $params = [$like,$like,$like];
        }
        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM bank_accounts ba");
        $filtered = (int)$db->fetchColumn("SELECT COUNT(*) FROM bank_accounts ba WHERE {$where}", $params);
        $rows = $db->fetchAll(
            "SELECT ba.*, c.currency_code FROM bank_accounts ba LEFT JOIN sys_currencies c ON ba.currency_id=c.id WHERE {$where} ORDER BY ba.id DESC LIMIT {$length} OFFSET {$start}",
            $params
        );
        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'id' => $r['id'], 'account_code' => $r['account_code'],
                'bank_name' => $r['bank_name_en'], 'account_number' => $r['account_number'],
                'iban' => $r['iban'] ?? '—', 'account_type' => $r['account_type'],
                'current_balance' => format_money($r['current_balance']),
                'is_active' => $r['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $data]);
    }

    public function create(Request $request): void
    {
        $currencies = $this->db()->fetchAll("SELECT * FROM sys_currencies WHERE is_active = 1");
        $this->view('bank-accounts/form', [
            'title' => lang('common.create') . ' ' . lang('adv_finance.bank_accounts'),
            'breadcrumbs' => [['label' => lang('adv_finance.bank_accounts'), 'url' => '/advanced-finance/bank-accounts'], ['label' => lang('common.create')]],
            'account' => null, 'currencies' => $currencies,
        ], 'app');
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $validator = new Validator($request->all(), [
            'account_code' => 'required|string|max:30|unique:bank_accounts,account_code',
            'bank_name_en' => 'required|string|max:200', 'bank_name_ar' => 'required|string|max:200',
            'account_name' => 'required|string|max:200', 'account_number' => 'required|string|max:50',
            'iban' => 'nullable|string|max:50', 'swift_code' => 'nullable|string|max:20',
            'branch' => 'nullable|string|max:200', 'currency_id' => 'required|integer|exists:sys_currencies,id',
            'account_type' => 'required|in:current,savings,deposit',
            'opening_balance' => 'required|decimal|min:0',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $d = $validator->validated();
        $d['current_balance'] = $d['opening_balance'];
        $d['is_active'] = 1;
        $id = $this->db()->insert('bank_accounts', $d);
        $this->audit('create', 'bank_accounts', $id, 'Created bank account ' . $d['account_code']);
        $this->json(['success' => true, 'message' => lang('adv_finance.saved'), 'redirect' => '/advanced-finance/bank-accounts']);
    }

    public function edit(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $account = $this->db()->fetchOne("SELECT * FROM bank_accounts WHERE id = ?", [$id]);
        if (!$account) { $this->abort(404, 'Not found'); return; }
        $currencies = $this->db()->fetchAll("SELECT * FROM sys_currencies WHERE is_active = 1");
        $this->view('bank-accounts/form', [
            'title' => lang('common.edit') . ' ' . $account['account_code'],
            'breadcrumbs' => [['label' => lang('adv_finance.bank_accounts'), 'url' => '/advanced-finance/bank-accounts'], ['label' => lang('common.edit')]],
            'account' => $account, 'currencies' => $currencies,
        ], 'app');
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $id = (int)$request->routeParam('id');
        $validator = new Validator($request->all(), [
            'account_code' => "required|string|max:30|unique:bank_accounts,account_code,{$id}",
            'bank_name_en' => 'required|string|max:200', 'bank_name_ar' => 'required|string|max:200',
            'account_name' => 'required|string|max:200', 'account_number' => 'required|string|max:50',
            'iban' => 'nullable|string|max:50', 'swift_code' => 'nullable|string|max:20',
            'branch' => 'nullable|string|max:200', 'currency_id' => 'required|integer|exists:sys_currencies,id',
            'account_type' => 'required|in:current,savings,deposit',
            'is_active' => 'nullable|boolean',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $d = $validator->validated();
        $d['is_active'] = !empty($d['is_active']) ? 1 : 0;
        $this->db()->update('bank_accounts', $d, 'id = ?', [$id]);
        $this->audit('update', 'bank_accounts', $id, 'Updated bank account');
        $this->json(['success' => true, 'message' => lang('adv_finance.saved'), 'redirect' => '/advanced-finance/bank-accounts']);
    }
}