<?php
require 'vendor/autoload.php'; // Load all SDKs

use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
use Stripe\Stripe;
use Stripe\PaymentIntent;

// ============================
// ✅ Database Connections
// ============================

// Second database
$host2 = 'localhost';
$dbname2 = 'demoptma_publications';
$username2 = 'demoptma_publications';
$password2 = 'dj$JN)hJerjG';
$pdo_new = new PDO("mysql:host=$host2;dbname=$dbname2;charset=utf8mb4", $username2, $password2);
$pdo_new->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo_new->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

// ============================
// ✅ Encryption Setup
// ============================
$encryptionKey = '*UKGVL)lWxjKjgNr57CfKfBmsvqr*3J2';
function encryptCardNumber($cardNumber, $key)
{
    $iv = openssl_random_pseudo_bytes(16);
    $encrypted = openssl_encrypt($cardNumber, 'AES-256-CBC', $key, 0, $iv);
    return base64_encode($iv . $encrypted);
}

// ============================
// ✅ Merchant Credentials
// ============================
$authorizeLogin = '7yeA2Dt56WM';
$authorizeTransactionKey = '8L9x93urt97AJZnD';

$payarcLogin = '3Bc9hN48';
$payarcTransactionKey = '4786e6nGkFye9sHL';

$stripeSecretKey = 'sk_live_your_stripe_secret_here';
$paypalClientId = 'your_paypal_client_id';
$paypalSecret = 'your_paypal_secret';

// ============================
// ✅ Payment Handling
// ============================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $invoiceId = intval($_POST['invoice_id'] ?? 0);
    $stmt = $pdo_new->prepare("SELECT * FROM invoices WHERE id = ?");
    $stmt->execute([$invoiceId]);
    $invoice = $stmt->fetch();
    $merchant = $_POST['merchant'] ?? '';
    $paymentMethodId = $_POST['payment_method_id'] ?? '';
    if (strtolower($merchant) === 'stripe') {
        
        \Stripe\Stripe::setApiKey('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');
        

        if (!$paymentMethodId) {
            die("Missing payment method");
        }

        try {
            // 1️⃣ Ensure Customer exists
            if (!empty($invoice['customer_stripe_id'])) {
                $customer_id = $invoice['customer_stripe_id'];
            } else {
                $customer = \Stripe\Customer::create([
                    'name' => $invoice['client_name'],
                    'email' => $invoice['client_email'],
                    'metadata' => ['invoice_id' => $invoiceId]
                ]);
                $customer_id = $customer->id;

                // Save customer_id in DB
                $stmt = $pdo_new->prepare("UPDATE invoices SET customer_stripe_id=? WHERE id=?");
                $stmt->execute([$customer_id, $invoiceId]);
            }

            // 2️⃣ Attach the PaymentMethod to the Customer
            $paymentMethod = \Stripe\PaymentMethod::retrieve($paymentMethodId);
            $paymentMethod->attach([
                'customer' => $customer_id
            ]);

            // 3️⃣ Create or reuse PaymentIntent
            if (!empty($invoice['stripe_payment_intent_id'])) {
                $paymentIntent = \Stripe\PaymentIntent::retrieve($invoice['stripe_payment_intent_id']);
            } else {
                $paymentIntent = \Stripe\PaymentIntent::create([
                    'amount' => intval($invoice['amount'] * 100),
                    'currency' => 'usd',
                    'customer' => $customer_id,
                    'payment_method' => $paymentMethodId,
                    'payment_method_types' => ['card'],
                    'confirm' => true,
                    'confirmation_method' => 'automatic',
                    'statement_descriptor_suffix' => 'TMCOMPLIANCE',
                    'metadata' => ['invoice_id' => $invoiceId]
                ]);

                // Save PaymentIntent ID
                $stmt = $pdo_new->prepare("UPDATE invoices SET stripe_payment_intent_id=? WHERE id=?");
                $stmt->execute([$paymentIntent->id, $invoiceId]);
            }

            // 4️⃣ Handle Payment Result
            if ($paymentIntent->status === 'succeeded') {
                echo "<script>
                    alert('Payment successful!');
                    window.location.href = 'checkout.php?reg={$invoiceId}';
                  </script>";
                exit;
            } elseif ($paymentIntent->status === 'requires_action') {
                // 3D Secure required
                // header("Location: action_required.php?invoice=$invoiceId");
                // header("Location: action_required.php?pi=".$paymentIntent->id."&client_secret=".$paymentIntent->client_secret);
                header(
                    "Location: action_required.php?reg=" . urlencode($invoiceId) .
                    "&pi=" . urlencode($paymentIntent->id) .
                    "&client_secret=" . urlencode($paymentIntent->client_secret)
                );
                exit;

            } else {
                // Anything else = failure
                echo "<script>
                    alert('Payment Failed!');
                    window.location.href = 'checkout.php?reg={$invoiceId}';
                  </script>";
                exit;
            }

        } catch (\Stripe\Exception\CardException $e) {
            // Card declined
            error_log($e->getMessage());
            echo "<script>
                alert('Payment Failed: {$e->getMessage()}');
                window.location.href = 'checkout.php?reg={$invoiceId}';
              </script>";
            exit;
        } catch (\Exception $e) {
            // Other errors
            error_log($e->getMessage());
            echo "<script>
                alert('Payment Failed: {$e->getMessage()}');
                window.location.href = 'checkout.php?reg={$invoiceId}';
              </script>";
            exit;
        }
    }

    
    $amount = floatval($_POST['amount'] ?? 0);
    $card_num = preg_replace('/\D/', '', $_POST['card_num']) ?? $_POST['cardnumber'];
    $exp = $_POST['exp'] ?? $_POST['exp-date'];
    $cvv = $_POST['cvv'] ?? $_POST['cvc'];
    $cusName = $_POST['client_name'] ?? 'Customer';
    $zip = $_POST['zip'] ?? '';

    $address = trim($_POST['card_address'] ?? '');

    if (!$invoiceId || !$merchant || !$amount || !$card_num || !$exp || !$cvv) {
        die("Missing required fields.");
    }

    // Encrypt card
    $encryptedCardNumber = encryptCardNumber($card_num, $encryptionKey);
    $sql = "INSERT INTO card_details (
        name_on_card,
        card_number,
        cvv,
        card_holder_address,
        zip_code,
        expiry_date,
        invoice_status,
        invoice_number,
        customer_email,
        customer_name,
        customer_phone,
        city,
        state,
        date
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $pdo_new->prepare($sql);
    $stmt->execute([
        $_POST["card_name"],
        $encryptedCardNumber,
        $_POST["cvv"],
        $_POST["card_address"],
        $_POST["zip"],
        $_POST["exp"],
        1,
        $_POST["invoice_id"],
        $_POST["client_email"],
        $_POST["client_name"],
        $_POST["client_phone"],
        $_POST["city"],
        $_POST["state"],
        date('Y-m-d H:i:s')
    ]);

    // Fetch Invoice
    $stmt = $pdo_new->prepare("SELECT * FROM invoices WHERE id = ?");
    $stmt->execute([$invoiceId]);
    $invoice = $stmt->fetch();
    if (!$invoice) {
        die("Invoice not found");
    }

    $payment_status = 'unpaid';
    $transactionId = null;
    $errorMsg = '';

    // ============================
    // ✅ MERCHANT LOGIC
    // ============================

    // ---------- AUTHORIZE.NET ----------
    if ($merchant === 'authorize') {
        
        $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
        $merchantAuthentication->setName($authorizeLogin);
        $merchantAuthentication->setTransactionKey($authorizeTransactionKey);
    
        $refId = 'ref' . time();
        $creditCard = new AnetAPI\CreditCardType();
        $creditCard->setCardNumber($card_num);
        $creditCard->setExpirationDate(str_replace('/', '', $exp)); // MMYY
        $creditCard->setCardCode($cvv);
        
        

        $paymentType = new AnetAPI\PaymentType();
        $paymentType->setCreditCard($creditCard);

        $order = new AnetAPI\OrderType();
        $order->setInvoiceNumber($invoiceId);
        
        

        // Set the customer's Bill To address
        $customerAddress = new AnetAPI\CustomerAddressType();
        $customerAddress->setFirstName($cusName);
        $customerAddress->setAddress($address);
        $customerAddress->setZip($zip);
        
        

        // Add values for transaction settings
        $duplicateWindowSetting = new AnetAPI\SettingType();
        $duplicateWindowSetting->setSettingName("duplicateWindow");
        $duplicateWindowSetting->setSettingValue("60");

        

        $transactionRequest = new AnetAPI\TransactionRequestType();
        $transactionRequest->setTransactionType("authCaptureTransaction");
        $transactionRequest->setAmount($amount);
        $transactionRequest->setOrder($order);
        $transactionRequest->setPayment($paymentType);
        $transactionRequest->setBillTo($customerAddress);
        $transactionRequest->addToTransactionSettings($duplicateWindowSetting);

        $request = new AnetAPI\CreateTransactionRequest();
        $request->setMerchantAuthentication($merchantAuthentication);
        $request->setRefId($refId);
        $request->setTransactionRequest($transactionRequest);

        $controller = new AnetController\CreateTransactionController($request);
        $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);

        if ($response != null && $response->getMessages()->getResultCode() == "Ok") {
            $tresponse = $response->getTransactionResponse();

            if ($tresponse != null && $tresponse->getMessages() != null) {

                // $transactionId = $tresponse->getTransId();
                // print_r($transactionId);
                // exit;
                $payment_status = 'paid';
            } else {
                $errorMsg = $tresponse->getErrors()[0]->getErrorText() ?? 'Transaction failed.';
            }
        } else {
            $errorMsg = 'Authorize.Net payment failed.';
        }
    }

    // ---------- STRIPE ----------
    elseif ($merchant === 'stripe') {
        try {
            \Stripe\Stripe::setApiKey('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'); // use live key in production




            // Extract dynamic values
            $totalAmount = $amount;          // e.g. 50.00
            $amountCurrency = strtolower('usd');  // e.g. "usd"


            // Stripe requires amount in cents
            $amountInCents = (int) intval($totalAmount * 100);

            $stmt = $pdo_new->prepare("SELECT * FROM invoices WHERE Id=?");
            $stmt->execute([$invoiceId]);
            $invoice = $stmt->fetch(PDO::FETCH_ASSOC);
            $customerId = $invoice['customer_stripe_id'];
            $customerName = $invoice['client_name'];
            $customerEmail = $invoice['client_email'];

            if (!empty($customerId)) {
                $customer_id = $customerId;
            } else {
                $customer = \Stripe\Customer::create([
                    'name' => $customerName,
                    'email' => $customerEmail,
                    'metadata' => [
                        'invoice_id' => $invoiceId,
                    ]
                ]);

                $customer_id = $customer->id;
                $stmt = $pdo->prepare("UPDATE invoice SET customer_stripe_id=? WHERE Id=?");
                $stmt->execute([$customer_id, $invoiceId]);
            }


            $orderId = $order['Id'];


            $checkoutId = $invoice['stripe_session_id'];
            if (!empty($checkoutId)) {
                $session = \Stripe\Checkout\Session::retrieve($checkoutId);

                if ($session->status === 'complete' && $session->payment_status === 'paid') {
                    // ✅ Paid successfully
                    header("Location: https://trademarkreliance.com/paid.php?invoice_id=" . $invoiceId);
                    exit;
                } elseif ($session->payment_status === 'unpaid') {
                    if ($session->status === 'open') {
                        // 🟡 Still open → redirect user back to Stripe Checkout page
                        header("Location: " . $session->url);
                        exit;
                    }
                    if ($session->status === 'complete') {
                        // ❌ Complete but unpaid → means they canceled or failed
                        header("Location: https://trademarkreliance.com/failed.php?invoice_id=" . $invoiceId);
                        exit;
                    }
                } else {
                    // If session is still open/pending, redirect user to it
                    header("Location: " . $session->url);
                    exit;
                }
            } else {
                $checkout_session = \Stripe\Checkout\Session::create([
                    'customer' => $customer_id,
                    'payment_method_types' => ['card'],
                    'mode' => 'payment',
                    'line_items' => [
                        [
                            'price_data' => [
                                'currency' => $amountCurrency,
                                'unit_amount' => $amountInCents,
                                'product_data' => [
                                    'name' => "Invoice #{$invoice['invoicestripeId']} - {$customerName}",
                                    'description' => "{$invoice['package']}",
                                ],
                            ],
                            'quantity' => 1,
                        ]
                    ],
                    'success_url' => 'https://trademarkreliance.com/success.php?invoice_id=' . $invoiceId,
                    'cancel_url' => 'https://trademarkreliance.com/failed.php?invoice_id=' . $invoiceId,
                    'metadata' => [
                        'invoice_id' => $invoice['invoicestripeId'],
                        'customer_name' => $customerName,
                    ]
                ]);

                $checkout_session_id = $checkout_session->id;
                $stmt = $pdo->prepare("UPDATE invoice SET stripe_session_id=? WHERE Id=?");
                $stmt->execute([$checkout_session_id, $invoiceId]);

                header("Location: " . $checkout_session->url);
                exit;
            }

        } catch (Exception $e) {
            $errorMsg = $e->getMessage();
        }
    }

    // ---------- PAYPAL ----------
    if ($merchant === 'payarc') {
        
        $merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
        $merchantAuthentication->setName($payarcLogin);
        $merchantAuthentication->setTransactionKey($payarcTransactionKey);
    
        $refId = 'ref' . time();
        $creditCard = new AnetAPI\CreditCardType();
        $creditCard->setCardNumber($card_num);
        $creditCard->setExpirationDate(str_replace('/', '', $exp)); // MMYY
        $creditCard->setCardCode($cvv);
        
        

        $paymentType = new AnetAPI\PaymentType();
        $paymentType->setCreditCard($creditCard);

        $order = new AnetAPI\OrderType();
        $order->setInvoiceNumber($invoiceId);
        
        

        // Set the customer's Bill To address
        $customerAddress = new AnetAPI\CustomerAddressType();
        $customerAddress->setFirstName($cusName);
        $customerAddress->setAddress($address);
        $customerAddress->setZip($zip);
        
        

        // Add values for transaction settings
        $duplicateWindowSetting = new AnetAPI\SettingType();
        $duplicateWindowSetting->setSettingName("duplicateWindow");
        $duplicateWindowSetting->setSettingValue("60");

        

        $transactionRequest = new AnetAPI\TransactionRequestType();
        $transactionRequest->setTransactionType("authCaptureTransaction");
        $transactionRequest->setAmount($amount);
        $transactionRequest->setOrder($order);
        $transactionRequest->setPayment($paymentType);
        $transactionRequest->setBillTo($customerAddress);
        $transactionRequest->addToTransactionSettings($duplicateWindowSetting);

        $request = new AnetAPI\CreateTransactionRequest();
        $request->setMerchantAuthentication($merchantAuthentication);
        $request->setRefId($refId);
        $request->setTransactionRequest($transactionRequest);

        $controller = new AnetController\CreateTransactionController($request);
        $response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::PRODUCTION);

        if ($response != null && $response->getMessages()->getResultCode() == "Ok") {
            $tresponse = $response->getTransactionResponse();

            if ($tresponse != null && $tresponse->getMessages() != null) {

                // $transactionId = $tresponse->getTransId();
                // print_r($transactionId);
                // exit;
                $payment_status = 'paid';
            } else {
                $errorMsg = $tresponse->getErrors()[0]->getErrorText() ?? 'Transaction failed.';
            }
        } else {
            $errorMsg = 'Authorize.Net payment failed.';
        }
    }

    // ============================
    // ✅ Store Transaction
    // ============================
    if ($payment_status === 'paid') {
        $transactionId = 1;
        $update = $pdo_new->prepare("UPDATE invoices SET payment_status = ?, transaction_id = ?, updated_at = NOW() WHERE id = ?");
        $update->execute([$payment_status, $transactionId, $invoiceId]);

        // $insertCard = $pdo->prepare("INSERT INTO card_details 
        //     (invoice_id, name_on_card, card_number, cvv, expiry_date, transaction_id)
        //     VALUES (?, ?, ?, ?, ?, ?)");
        // $insertCard->execute([
        //     $invoiceId,
        //     $invoice['client_name'],
        //     $encryptedCard,
        //     $cvv,
        //     $exp,
        //     $transactionId
        // ]);

        echo "<script>
                alert('Payment successful!');
                window.location.href = 'checkout.php?reg={$invoiceId}';
            </script>";
        exit;
    } else {
        echo "<script>alert('Payment failed: {$errorMsg}'); window.history.back();</script>";
        exit;
    }
}
?>