<?php

class BankDepositController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('deposits/index', [
            'title' => lang('adv_finance.deposits'),
            'breadcrumbs' => [['label' => lang('adv_finance.title'), 'url' => '/advanced-finance/installments'], ['label' => lang('adv_finance.deposits')]],
        ], '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 (bd.deposit_number LIKE ? OR ba.bank_name_en LIKE ?)'; $like = "%{$search}%"; $params = [$like,$like]; }

        $total = (int)$db->fetchColumn("SELECT COUNT(*) FROM bank_deposits bd JOIN bank_accounts ba ON bd.bank_account_id=ba.id");
        $filtered = (int)$db->fetchColumn("SELECT COUNT(*) FROM bank_deposits bd JOIN bank_accounts ba ON bd.bank_account_id=ba.id WHERE {$where}", $params);
        $rows = $db->fetchAll(
            "SELECT bd.*, ba.bank_name_en FROM bank_deposits bd JOIN bank_accounts ba ON bd.bank_account_id=ba.id WHERE {$where} ORDER BY bd.id DESC LIMIT {$length} OFFSET {$start}",
            $params
        );
        $data = [];
        foreach ($rows as $r) {
            $data[] = [
                'id' => $r['id'], 'deposit_number' => $r['deposit_number'],
                'bank_name' => $r['bank_name_en'], 'deposit_date' => format_date($r['deposit_date']),
                'total_amount' => format_money($r['total_amount']),
                'cash_amount' => format_money($r['cash_amount']), 'check_amount' => format_money($r['check_amount']),
                'status' => $r['status'], 'status_badge' => status_badge($r['status']),
            ];
        }
        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $data]);
    }

    public function create(Request $request): void
    {
        $db = $this->db();
        $bankAccounts = $db->fetchAll("SELECT * FROM bank_accounts WHERE is_active = 1 ORDER BY bank_name_en");
        $receivedChecks = $db->fetchAll("SELECT * FROM checks WHERE status = 'received' ORDER BY check_date");
        $this->view('deposits/create', [
            'title' => lang('common.create') . ' ' . lang('adv_finance.deposits'),
            'breadcrumbs' => [['label' => lang('adv_finance.deposits'), 'url' => '/advanced-finance/deposits'], ['label' => lang('common.create')]],
            'bankAccounts' => $bankAccounts, 'receivedChecks' => $receivedChecks,
        ], '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(), [
            'bank_account_id' => 'required|integer|exists:bank_accounts,id',
            'deposit_date'    => 'required|date',
            'cash_amount'     => 'required|decimal|min:0',
            'notes'           => 'nullable|string|max:500',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $d = $validator->validated();
        $db = $this->db();

        $checkIds = $request->post('check_ids', []);
        if (!is_array($checkIds)) $checkIds = [];
        $checkTotal = 0;
        $checkCount = 0;

        if (!empty($checkIds)) {
            $placeholders = implode(',', array_fill(0, count($checkIds), '?'));
            $checks = $db->fetchAll("SELECT id, amount FROM checks WHERE id IN ({$placeholders}) AND status = 'received'", $checkIds);
            $checkCount = count($checks);
            foreach ($checks as $ch) { $checkTotal += (float)$ch['amount']; }
        }

        $totalAmount = (float)$d['cash_amount'] + $checkTotal;
        $depNumber = SequenceGenerator::next('deposit_number');

        try {
            $db->beginTransaction();
            $depId = $db->insert('bank_deposits', [
                'deposit_number'  => $depNumber,
                'bank_account_id' => $d['bank_account_id'],
                'deposit_date'    => $d['deposit_date'],
                'total_amount'    => $totalAmount,
                'cash_amount'     => $d['cash_amount'],
                'check_amount'    => $checkTotal,
                'check_count'     => $checkCount,
                'status'          => 'prepared',
                'notes'           => $d['notes'] ?? null,
                'created_by'      => Auth::id(),
            ]);

            if ((float)$d['cash_amount'] > 0) {
                $db->insert('bank_deposit_items', [
                    'deposit_id' => $depId, 'item_type' => 'cash', 'amount' => $d['cash_amount'],
                ]);
            }

            foreach ($checkIds as $cid) {
                $ch = $db->fetchOne("SELECT id, amount FROM checks WHERE id = ? AND status = 'received'", [$cid]);
                if ($ch) {
                    $db->insert('bank_deposit_items', [
                        'deposit_id' => $depId, 'item_type' => 'check', 'amount' => $ch['amount'], 'check_id' => $ch['id'],
                    ]);
                    $db->update('checks', ['status' => 'deposited', 'deposit_date' => $d['deposit_date'], 'bank_account_id' => $d['bank_account_id']], 'id = ?', [$ch['id']]);
                }
            }

            $db->commit();
            $this->audit('create', 'bank_deposits', $depId, 'Created deposit ' . $depNumber);
            $this->json(['success' => true, 'message' => lang('adv_finance.saved'), 'redirect' => '/advanced-finance/deposits/' . $depId]);
        } catch (\Exception $e) {
            $db->rollBack();
            Logger::error('Deposit creation failed: ' . $e->getMessage());
            $this->json(['success' => false, 'message' => 'Failed to create deposit'], 500);
        }
    }

    public function show(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $db = $this->db();
        $dep = $db->fetchOne("SELECT bd.*, ba.bank_name_en FROM bank_deposits bd JOIN bank_accounts ba ON bd.bank_account_id=ba.id WHERE bd.id = ?", [$id]);
        if (!$dep) { $this->abort(404, 'Not found'); return; }
        $items = $db->fetchAll(
            "SELECT bdi.*, c.check_number, c.drawer_name, c.bank_name AS check_bank
             FROM bank_deposit_items bdi
             LEFT JOIN checks c ON bdi.check_id = c.id
             WHERE bdi.deposit_id = ?",
            [$id]
        );
        $this->view('deposits/show', [
            'title' => $dep['deposit_number'],
            'breadcrumbs' => [['label' => lang('adv_finance.deposits'), 'url' => '/advanced-finance/deposits'], ['label' => $dep['deposit_number']]],
            'dep' => $dep, 'items' => $items,
        ], 'app');
    }

    public function confirm(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid CSRF'], 403); return; }
        $id = (int)$request->routeParam('id');
        $db = $this->db();
        $dep = $db->fetchOne("SELECT * FROM bank_deposits WHERE id = ? AND status IN ('prepared','deposited')", [$id]);
        if (!$dep) { $this->json(['success' => false, 'message' => 'Cannot confirm'], 422); return; }

        $bankRef = $request->post('bank_reference', '');
        $db->update('bank_deposits', [
            'status' => 'confirmed', 'confirmed_by' => Auth::id(),
            'confirmed_at' => date('Y-m-d H:i:s'), 'bank_reference' => $bankRef ?: null,
        ], 'id = ?', [$id]);

        // Update bank account balance
        $db->execute(
            "UPDATE bank_accounts SET current_balance = current_balance + ? WHERE id = ?",
            [$dep['total_amount'], $dep['bank_account_id']]
        );

        $this->audit('update', 'bank_deposits', $id, 'Confirmed deposit');
        $this->json(['success' => true, 'message' => lang('adv_finance.confirmed'), 'redirect' => '/advanced-finance/deposits/' . $id]);
    }
}