<?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 = [
        'name' => trim($_POST['name'] ?? ''),
        'account_no' => trim($_POST['account_no'] ?? ''),
        'bank_name' => trim($_POST['bank_name'] ?? ''),
        'type' => $_POST['type'] ?? 'bank',
        'balance' => (float)($_POST['balance'] ?? 0),
        'remarks' => trim($_POST['remarks'] ?? '')
    ];

    if ($data['name'] === '') throw new Exception('Account name is required.');

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

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