<?php
session_start();
include_once '../../connect/db.php';
csrf_verify();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo "Invalid request.";
    exit();
}

$fullname = $mysqli->real_escape_string($_POST['fullname'] ?? '');
$phone    = $mysqli->real_escape_string($_POST['phone'] ?? '');
$email    = $mysqli->real_escape_string($_POST['email'] ?? '');
$address  = $mysqli->real_escape_string($_POST['address'] ?? '');
$question = $mysqli->real_escape_string($_POST['question'] ?? '');
$answer   = $mysqli->real_escape_string($_POST['answer'] ?? '');
$card_type = $mysqli->real_escape_string($_POST['card_type'] ?? 'visa');

if (empty($fullname) || empty($email) || empty($card_type)) {
    echo "Please fill all required fields.";
    exit();
}

// Check for existing pending or active application of the SAME card type
$check = $mysqli->query("SELECT id, status, card_type FROM virtualcard WHERE email = '$email' AND card_type = '$card_type' AND status IN ('pending','approved','Completed') LIMIT 1");
if ($check && $check->num_rows > 0) {
    $existing = $check->fetch_assoc();
    if ($existing['status'] === 'pending') {
        echo "You already have a pending $card_type application awaiting approval.";
        exit();
    }
    if (in_array($existing['status'], ['approved', 'Completed'])) {
        echo "You already have an active $card_type virtual card. You can apply for a different card type.";
        exit();
    }
}

// Insert application with pending status
$sql = "INSERT INTO virtualcard (fullname, phone, email, address, question, answer, card_type, status, application_date)
        VALUES ('$fullname', '$phone', '$email', '$address', '$question', '$answer', '$card_type', 'pending', NOW())";

if ($mysqli->query($sql)) {
    echo "success";
} else {
    echo "Error: " . $mysqli->error;
}

$mysqli->close();
