<?php

// Include database configuration
include "../config.php";

// Only handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Set header to return JSON
    header('Content-Type: application/json');

    // Read the raw input
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    // Check if JSON decoding was successful
    if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON"]);
        exit();
    }

    // Extract variables
    $atf = $data['atf'] ?? '';
    $ackNo = $data['ack_no'] ?? '';
    $complainantName = $data['complainant_name'] ?? '';
    $policestationId = $data['policestation_id'] ?? '';
    $policeId = $data['police_id'] ?? '';
    $subjectId = $data['subject_id'] ?? '';
    $noticeId = $data['notice_id'] ?? '';
    $type = $data['type'];
    $mobile = "true";
    $createdBy = $data['uid'];
    $bankAccounts = $data['bank_accounts'] ?? [];

    // Insert into kyc table
    $query = "INSERT INTO kyc (acknowledgement_no, complainant_name, policestation_id, police_id, subject_id, notice_id, type, created_by, atf,mobile) 
              VALUES ('$ackNo', '$complainantName', '$policestationId', '$policeId', '$subjectId', '$noticeId', '$type', '$createdBy', '$atf','$mobile')";
    if (!mysqli_query($con, $query)) {
        http_response_code(500);
        echo json_encode(["error" => "KYC insert failed", "details" => mysqli_error($con)]);
        exit();
    }

    $kycId = mysqli_insert_id($con);

    // Insert bank accounts
    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'] ?? '';

        $queryBank = "INSERT INTO bank_accounts (kyc_id, bank_id, bank_name, account_number, ifsc_code, account_holder, transaction_id)
                      VALUES ('$kycId', '$bankId', '$bankName', '$accountNumber', '$ifscCode', '$accountHolder', '$transactionId')";
        if (!mysqli_query($con, $queryBank)) {
            http_response_code(500);
            echo json_encode(["error" => "Bank account insert failed", "details" => mysqli_error($con)]);
            exit();
        }
    }
    echo json_encode(["success" => true, "kyc_id" => $kycId]);
    exit();
} else {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed"]);
    exit();
}
?>