<?php
session_start();
include "../../connect/db.php";

if (!isset($_SESSION['man'])) { die("Access Denied"); }

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['id'])) {
    die("Invalid request.");
}

$id = intval($_POST['id']);
$admin = $_SESSION['man'];

// Get application
$app = $mysqli->query("SELECT * FROM virtualcard WHERE id = $id");
if (!$app || $app->num_rows === 0) { die("Application not found."); }
$row = $app->fetch_assoc();

if ($row['status'] !== 'pending') {
    die("This application is no longer pending.");
}

// Check user doesn't already have an active card
$existing = $mysqli->query("SELECT id FROM virtualcard WHERE email = '{$row['email']}' AND status IN ('approved','Completed') AND id != $id");
if ($existing && $existing->num_rows > 0) {
    die("User already has an active virtual card.");
}

// Start transaction
$mysqli->begin_transaction();

try {
    // Generate card number based on network prefix
    $prefixes = ['visa' => '4', 'mastercard' => '5', 'discover' => '6'];
    $prefix = $prefixes[strtolower($row['card_type'])] ?? '4';
    $card_number = $prefix . str_pad(mt_rand(0, 999999999), 9, '0', STR_PAD_LEFT) . str_pad($id % 10000, 4, '0', STR_PAD_LEFT);
    $card_number = wordwrap($card_number, 4, ' ', true);
    $lastFour = substr(str_replace(' ', '', $card_number), -4);
    $expiry = date('m/y', strtotime('+3 years'));
    $cvv = str_pad(mt_rand(0, 999), 3, '0', STR_PAD_LEFT);

    $update = $mysqli->query("UPDATE virtualcard SET
        status = 'approved',
        card_number = '$card_number',
        card_last_four = '$lastFour',
        expiration_date = '$expiry',
        cvv = '$cvv',
        is_test_card = 1,
        available_balance = 0.00,
        approved_by = '$admin',
        approved_at = NOW()
        WHERE id = $id AND status = 'pending'");

    if (!$update || $mysqli->affected_rows === 0) {
        throw new Exception("Failed to update application.");
    }

    $mysqli->commit();
    echo "success";
} catch (Exception $e) {
    $mysqli->rollback();
    echo "Error: " . $e->getMessage();
}
