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

$user = $_SESSION['user'];
$uid = $user['id'];

$reference_type = $_POST['reference_type'] ?? '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize form inputs
    //$uid = mysqli_real_escape_string($con, $_POST['uid']);
    $atf = mysqli_real_escape_string($con, $_POST['atf']);
    $pid = '';
    $police_id = mysqli_real_escape_string($con, $_POST['police_id']);
    $court_order = mysqli_real_escape_string($con, $_POST['court_order']);
    $ack_no = '';
    //$name = mysqli_real_escape_string($con, $_POST['complainant_name']);
    $subject_id = mysqli_real_escape_string($con, $_POST['subject_id']);

    // Victim details
    $v_name = mysqli_real_escape_string($con, $_POST['v_name']);
    $v_bank = mysqli_real_escape_string($con, $_POST['victim_bank_id']);
    $v_ac_no = mysqli_real_escape_string($con, $_POST['victim_account_no']);
    $v_ifsc = mysqli_real_escape_string($con, $_POST['victim_ifsc']);

    // Dynamic bank data JSON
    $bankAccountsJson = $_POST['bank_accounts_json'] ?? '';
    $bankAccounts = json_decode($bankAccountsJson, true);

    // Optional: Save raw JSON in comply_order for record
    //$bank_data_raw = mysqli_real_escape_string($con, $bankAccountsJson);


    // Insert into comply_order
    $query = "INSERT INTO `comply_order`
(`c_id`, `police_id`, `court_order`, `s_id`, `n_id`,
 `v_name`, `v_bank`, `v_ac_no`, `v_ifsc`, `time_stamp`,
 `mobile`, `status`, `remarks`)
VALUES
('$atf', '$police_id', '$court_order', '$subject_id', 2,
 '$v_name', '$v_bank', '$v_ac_no', '$v_ifsc', NOW(),
 '', '', '');
";

    if (mysqli_query($con, $query)) {
        $comply_order_id = mysqli_insert_id($con); // Get inserted comply_order ID

        // Insert each bank data row
        if (is_array($bankAccounts)) {
            foreach ($bankAccounts as $bank) {
                $bank_id = mysqli_real_escape_string($con, $bank['bank_id']);
                $account_number = mysqli_real_escape_string($con, $bank['account_number']);
                $ifsc_code = mysqli_real_escape_string($con, $bank['ifsc_code']);
                $account_holder = mysqli_real_escape_string($con, $bank['account_holder']);
                $release_amount = mysqli_real_escape_string($con, $bank['release_amount']);

                $bankInsert = "INSERT INTO c_bank_data (
                    comply_order_id, bank_id, account_number, ifsc_code, account_holder, release_amount,remarks
                ) VALUES (
                    '$comply_order_id', '$bank_id', '$account_number', '$ifsc_code', '$account_holder', '$release_amount',''
                )";

                mysqli_query($con, $bankInsert);
            }
        }

        echo "<script>alert('Comply Order Submitted Successfully!'); window.location.href='comply_order.php';</script>";
    } else {
        echo "Error inserting comply_order: " . mysqli_error($con);
    }
}
?>