<?php
declare(strict_types=1);
require_once __DIR__ . '/../../app/Config/database.php';

class Bank {
    private PDO $db;
    public function __construct() {
        $this->db = Database::getConnection();
    }

    // --- Bank Accounts ---
    public function getAccounts(): array {
        $stmt = $this->db->query("SELECT * FROM bank_accounts ORDER BY name");
        return $stmt->fetchAll();
    }

    public function addAccount(array $data): bool {
        $sql = "INSERT INTO bank_accounts (name, account_no, bank_name, type, balance, remarks)
                VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([
            $data['name'], $data['account_no'], $data['bank_name'],
            $data['type'], $data['balance'], $data['remarks']
        ]);
    }

    public function updateAccount(int $id, array $data): bool {
        $sql = "UPDATE bank_accounts SET name=?, account_no=?, bank_name=?, type=?, remarks=? WHERE id=?";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute([
            $data['name'], $data['account_no'], $data['bank_name'],
            $data['type'], $data['remarks'], $id
        ]);
    }

    public function deleteAccount(int $id): bool {
        return $this->db->prepare("DELETE FROM bank_accounts WHERE id=?")->execute([$id]);
    }

    // --- Transactions ---
    public function getTransactions(int $accountId): array {
        $stmt = $this->db->prepare("SELECT * FROM bank_transactions WHERE account_id=? ORDER BY txn_date DESC");
        $stmt->execute([$accountId]);
        return $stmt->fetchAll();
    }

    public function addTransaction(array $data): bool {
        $sql = "INSERT INTO bank_transactions (account_id, txn_date, description, type, amount, reference_no)
                VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $this->db->prepare($sql);
        $success = $stmt->execute([
            $data['account_id'], $data['txn_date'], $data['description'],
            $data['type'], $data['amount'], $data['reference_no']
        ]);

        if ($success) {
            $balanceAdj = ($data['type'] === 'deposit') ? $data['amount'] : -$data['amount'];
            $this->db->prepare("UPDATE bank_accounts SET balance = balance + ? WHERE id=?")
                     ->execute([$balanceAdj, $data['account_id']]);
        }

        return $success;
    }

    public function reconcile(int $txnId, bool $state): bool {
        return $this->db->prepare("UPDATE bank_transactions SET reconciled=? WHERE id=?")
                        ->execute([$state ? 1 : 0, $txnId]);
    }
}
