<?php
session_start();
include "config.php";

if (!isset($_SESSION['user'])) {
    header("Location: index.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ✅ KYC ID
    $kycId = (int) ($_POST['kycid'] ?? 0);
    if ($kycId <= 0) {
        die("Invalid KYC ID");
    }

    // ✅ Bank JSON (optional)
    $bankAccountsJson = trim($_POST['bank_accounts_json'] ?? '');

    if ($bankAccountsJson === '') {
        $bankAccounts = []; // No new banks added
    } else {
        $bankAccounts = json_decode($bankAccountsJson, true);
        if (!is_array($bankAccounts)) {
            die("Invalid bank accounts data");
        }
    }

    /* ==============================
       INSERT ONLY NEW BANK ACCOUNTS
       ============================== */
    foreach ($bankAccounts as $bank) {

        $bankId = mysqli_real_escape_string($con, $bank['bank_id']);
        $bankName = mysqli_real_escape_string($con, $bank['bank_name']);
        $accountNumber = mysqli_real_escape_string($con, $bank['account_number']);
        $ifscCode = mysqli_real_escape_string($con, $bank['ifsc_code'] ?? '');
        $accountHolder = mysqli_real_escape_string($con, $bank['account_holder'] ?? '');
        $transactionId = mysqli_real_escape_string($con, $bank['transaction_id']);

        // 🔍 Prevent duplicate insert
        $checkQuery = "SELECT id FROM bank_accounts 
                       WHERE kyc_id = '$kycId' AND account_number = '$accountNumber'";
        $checkResult = mysqli_query($con, $checkQuery);

        if (mysqli_num_rows($checkResult) == 0) {
            $insertQuery = "
                INSERT INTO bank_accounts
                (kyc_id, bank_id, bank_name, account_number, ifsc_code, account_holder, transaction_id, hold_amount, remarks)
                VALUES
                ('$kycId', '$bankId', '$bankName', '$accountNumber', '$ifscCode', '$accountHolder', '$transactionId', '0', '')
            ";
            mysqli_query($con, $insertQuery);
        }
    }

    // ✅ Done
    header("Location: lien_amount.php");
    exit();
}
?>