<?php
declare(strict_types=1);
require_once __DIR__ . '/../../../app/Config/config.php';
require_once __DIR__ . '/../../../app/Models/Bank.php';
require_once __DIR__ . '/../../../app/Config/functions.php';

require_login();
header('Content-Type: application/json');

try {
    $data = [
        'account_id' => (int)($_POST['account_id'] ?? 0),
        'txn_date' => $_POST['txn_date'] ?? '',
        'description' => trim($_POST['description'] ?? ''),
        'type' => $_POST['type'] ?? '',
        'amount' => (float)($_POST['amount'] ?? 0),
        'reference_no' => trim($_POST['reference_no'] ?? '')
    ];

    if ($data['account_id'] <= 0 || !$data['txn_date'] || $data['amount'] <= 0)
        throw new Exception('Incomplete transaction data.');

    $model = new Bank();
    $success = $model->addTransaction($data);

    echo json_encode(['status' => $success ? 'success' : 'error', 'message' => $success ? 'Transaction added successfully.' : 'Failed to add transaction.']);
} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
