<?php

namespace Modules\Accounting\Controllers;

use core\Controller;
use core\Auth;
use core\Database;
use core\Security;

class BankBookController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index(): void
    {
        $this->requirePermission('accounting_bankbook_view');

        $db = Database::getInstance();
        $accountId = $this->request->get('account_id', '');

        $accounts = $db->table('bank_accounts')
            ->where('deleted_at', 'IS', null)
            ->orderBy('account_name', 'ASC')
            ->get();

        $transactions = [];

        if (!empty($accountId)) {
            $transactions = $db->table('bank_transactions bt')
                ->select('bt.*, ba.account_name, ba.account_number')
                ->leftJoin('bank_accounts ba', 'bt.bank_account_id', '=', 'ba.id')
                ->where('bt.bank_account_id', $accountId)
                ->orderBy('bt.transaction_date', 'DESC')
                ->orderBy('bt.created_at', 'DESC')
                ->get();
        }

        $this->view('Accounting/bank_book', [
            'title' => 'Bank Book',
            'breadcrumb' => ['Bank Book' => url('accounting/bank-book')],
            'accounts' => $accounts,
            'transactions' => $transactions,
            'accountId' => $accountId,
        ]);
    }

    public function store(): void
    {
        $this->requirePermission('accounting_bankbook_create');

        $validated = $this->validate([
            'bank_account_id' => 'required|integer',
            'type' => 'required|in:deposit,withdrawal,transfer',
            'amount' => 'required|numeric|min:0',
            'description' => 'required|max_length:500',
            'transaction_date' => 'required|date',
            'reference' => 'max_length:100',
        ]);

        $validated['amount'] = (float)$validated['amount'];
        $validated['created_by'] = Auth::id();

        Database::getInstance()->table('bank_transactions')->insert($validated);
        $this->logActivity('create', 'Added bank transaction: ' . $validated['description']);

        $this->redirectWith(url('accounting/bank-book'), 'success', 'Bank transaction added successfully.');
    }
}
