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

if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $atf = $_POST['atf'] ?? '';
    $policeId = $_POST['police_id'] ?? '';
    $subjectId = $_POST['subject_id'] ?? '';
    $noticeId = $_POST['notice_id'] ?? '';
    $type = "KYC";
    $createdBy = $_SESSION['user']['id'];

    $bankAccountsJson = $_POST['bank_accounts_json'] ?? '[]';
    $bankAccounts = json_decode($bankAccountsJson, true);

    if ($bankAccounts === null && json_last_error() !== JSON_ERROR_NONE) {
        die("Invalid bank accounts data.");
    }

    // Insert main KYC data
    $query = "INSERT INTO kyc (c_id, police_id, subject_id, notice_id, type, created_by) 
              VALUES ('$atf', '$policeId', '$subjectId', '$noticeId', '$type', '$createdBy')";
    mysqli_query($con, $query);
    $kycId = mysqli_insert_id($con);

    // Insert bank accounts
    if (!empty($bankAccounts)) {
        foreach ($bankAccounts as $bank) {
            $bankId = $bank['bank_id'];
            $bankName = $bank['bank_name'];
            $accountNumber = $bank['account_number'];
            $ifscCode = $bank['ifsc_code'];
            //$accountHolder = $bank['account_holder'];
            $transactionId = $bank['transaction_id'];
            $accountHolder = '';


            $queryBank = "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, $queryBank);

        }
    }

    echo '<script>window.location.href = "kyc_form.php";</script>';
    exit();
}
?>