<?php
include 'db.php';

$bank_name = trim($_POST['bank_name'] ?? '');
$account_title = trim($_POST['account_title'] ?? '');
$account_number = trim($_POST['account_number'] ?? '');
$iban = trim($_POST['iban'] ?? '');
$branch_name = trim($_POST['branch_name'] ?? '');
$branch_code = trim($_POST['branch_code'] ?? '');
$swift_code = trim($_POST['swift_code'] ?? '');
$address = trim($_POST['address'] ?? '');
$is_active = isset($_POST['is_active']) ? 1 : 0;
$chart_of_account_id = !empty($_POST['chart_of_account_id']) ? intval($_POST['chart_of_account_id']) : null;

if ($bank_name && $account_title && $account_number) {
    // Check if chart of account is already mapped to another bank account
    if ($chart_of_account_id) {
        $check_stmt = $conn->prepare("SELECT id FROM bank_accounts WHERE chart_of_account_id = ?");
        $check_stmt->bind_param("i", $chart_of_account_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows > 0) {
            header("Location: bank_account_list.php?error=1&message=" . urlencode("This chart of account is already mapped to another bank account"));
            exit;
        }
    }
    
    $stmt = $conn->prepare("INSERT INTO bank_accounts 
        (bank_name, account_title, account_number, iban, branch_name, branch_code, swift_code, address, is_active, chart_of_account_id, mapped_at, mapped_by) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?)");
    $mapped_by = $_SESSION['user_id'] ?? 1;
    $stmt->bind_param("ssssssssiii", $bank_name, $account_title, $account_number, $iban, $branch_name, $branch_code, $swift_code, $address, $is_active, $chart_of_account_id, $mapped_by);
    $stmt->execute();
    header("Location: bank_account_list.php?success=1");
    exit;
} else {
    echo "Missing required fields!";
}
