<?php
require 'config.php';
// Database connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Extract UUID and hash from clean URL
$requestUri = $_SERVER['REQUEST_URI'];
// $parts = explode('/', trim($requestUri, '/'));
// $uuid = $conn->real_escape_string($parts[2] ?? '');
// $clientHash = $conn->real_escape_string($parts[3] ?? '');

$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = explode('/', trim($path, '/'));

if (count($parts) >= 4) {
    // invoice / secure / UUID / HASH
    $uuid = $conn->real_escape_string($parts[2]);
    $clientHash = $conn->real_escape_string($parts[3]);
} else {
    die("Invalid invoice access (URL mismatch)");
}



if (!empty($uuid) && !empty($clientHash)) {
    $stmt = $conn->prepare("SELECT * FROM invoices WHERE uuid = ? AND deleted_at IS NULL");
    $stmt->bind_param("s", $uuid);
    $stmt->execute();
    $result = $stmt->get_result();
    $invoice = $result->fetch_assoc();
    $stmt->close();
    
    if (!$invoice) {
        http_response_code(404);
        $errorMessage = "This invoice no longer exists.";
        $showError = true;
    }


    elseif (!hash_equals(generateInvoiceHash($invoice['id'], $invoice['salt']), $clientHash)) {
        http_response_code(403);
        $errorMessage = "Invalid invoice access.";
        $showError = true;
    }


    else {
        $invoiceId = $invoice['id'];
        $currency = $invoice['currency'];
        $paymentMethod = $invoice['payment_method'] ?? 'square';
    }

} else {
    header("Location: error.php");
    exit;
}
// Fetch invoice items
$itemStmt = $conn->prepare("SELECT * FROM invoice_items WHERE invoice_id = ?");
$itemStmt->bind_param("i", $invoiceId);
$itemStmt->execute();
$itemsResult = $itemStmt->get_result();
$items = [];
$subtotal = 0;
while ($row = $itemsResult->fetch_assoc()) {
    $items[] = $row;
    $subtotal += $row['amount'];
}
$itemStmt->close();
$discountPercent = (float) $invoice['discount'];
$taxPercent = (float) $invoice['tax'];
if($invoice['currency'] == 'USD'){
   $currency = '$'; 
}elseif($invoice['currency'] == 'GBP'){
    $currency = '£'; 
}elseif($invoice['currency'] == 'AUD'){
    $currency = 'A$'; 
}elseif($invoice['currency'] == 'CAD'){
    $currency = 'C$'; 
}else{
    $currency = '$'; 
}
$discountAmount = $subtotal * ($discountPercent / 100);
$taxAmount = ($subtotal - $discountAmount) * ($taxPercent / 100);
$totalAmount = $subtotal - $discountAmount + $taxAmount;
$paypalTotalAmount = round($subtotal - $discountAmount + $taxAmount, 2);
$isPaid = $invoice['status'] === 'paid';

// -----------------------------
// Payment method fetch & keys populate
// -----------------------------
$paymentMethod = strtolower($invoice['payment_method'] ?? 'square');

// Default IDs agar missing ho
$defaultIds = [
    'square' => 1,
    'stripe' => 2,
    'paypal' => 3,
    'authorize' => 5,
    'epd' => 6
];

// payment_method_id fetch
$pmId = $invoice['payment_method_id'] ?? null;
if (empty($pmId) && !empty($paymentMethod)) {
    $pmId = $defaultIds[$paymentMethod] ?? null;
}

// fetch merchant/payment data
$gatewayData = null;
if (!empty($pmId)) {
    $pmStmt = $conn->prepare("SELECT * FROM payment_methods WHERE id = ? AND status = 1");
    $pmStmt->bind_param("i", $pmId);
    $pmStmt->execute();
    $pmResult = $pmStmt->get_result();
    $gatewayData = $pmResult->fetch_assoc();
    $pmStmt->close();
    
    // $merchantName = $gatewayData['merchant_name'] ?? '';

    $nameStmt = $conn->prepare("SELECT merchant_name FROM payment_methods WHERE id = ?");
    $nameStmt->bind_param("i", $pmId);
    $nameStmt->execute();
    $nameResult = $nameStmt->get_result();
    $nameRow = $nameResult->fetch_assoc();
    
    if ($nameRow) {
        $merchantName = $nameRow['merchant_name'];
    }
    $nameStmt->close();
    
}

// -----------------------------
// Populate PHP constants dynamically
// -----------------------------
if ($gatewayData) {
    // Square
    define('SQUARE_ACCESS_TOKEN', $gatewayData['square_access_token'] ?? '');
    define('SQUARE_LOCATION_ID', $gatewayData['square_location_id'] ?? '');
    define('SQUARE_APPLICATION_ID', $gatewayData['square_application_id'] ?? '');

    // PayPal
    // define('PAYPAL_MODE', 'sandbox'); // ya sandbox agar chahiye to
    // define('PAYPAL_CLIENT_ID', PAYPAL_MODE === 'sandbox'
    //     ? ($gatewayData['paypal_client_id'] ?? '')
    //     : ($gatewayData['paypal_client_id'] ?? '') // yahan live id same column se
    // );
    // define('PAYPAL_SECRET_KEY', $gatewayData['paypal_secret_key'] ?? '');
    // define('PAYPAL_MERCHANT_ID', $gatewayData['paypal_merchant_id'] ?? '');
    
    
        // SANDBOX KEYS
    $sandbox_client_id     = "AWC6zxQassGuh4XAdXlEQoqEBsAOfz5Lnl9RH8ChUW9kwCDBPbtrAcQtnTADgJU2dx_WcPWqHoeBeI43";
    $sandbox_secret_key    = "EEvaaFagj2_cSfQE7wXju0hANng0_PJQ9mAe9dmlJqzgNTm3OmOmtVun6JYfCn_jEorSxnh3XmKI2JC1";
    $sandbox_merchant_id   = "";
    
    // LIVE KEYS
    $live_client_id        = $gatewayData['paypal_client_id'] ?? '';
    $live_secret_key       = $gatewayData['paypal_secret_key'] ?? '';
    $live_merchant_id      = $gatewayData['paypal_merchant_id'] ?? '';
    
// Define PayPal credentials dynamically based on mode
define('PAYPAL_CLIENT_ID', PAYPAL_MODE === 'sandbox' ? $sandbox_client_id : $live_client_id);
define('PAYPAL_SECRET_KEY', PAYPAL_MODE === 'sandbox' ? $sandbox_secret_key : $live_secret_key);

    
    define('PAYPAL_MERCHANT_ID', PAYPAL_MODE === 'sandbox' ? $sandbox_merchant_id : $live_merchant_id);
    
    define('AUTHORIZE_API_LOGIN_ID', $gatewayData['authorize_api_login'] ?? '');
    define('AUTHORIZE_TRANSACTION_KEY', $gatewayData['authorize_transaction_key'] ?? '');
    define('AUTHORIZE_PUBLIC_KEY', $gatewayData['authorize_public_key'] ?? '');
    define('AUTHORIZE_SIGNATURE_KEY', $gatewayData['authorize_signature_key'] ?? '');


    

    // Stripe
    define('STRIPE_MODE', 'live'); // ya sandbox
    if (STRIPE_MODE === 'sandbox') {
        define('STRIPE_PUBLISHABLE_KEY', "pk_test_51NxGHQIrZYESSIgqn72APBOFuFvtSvUKPNgbeej7IJZVZpFMdQZkKL7lTPeX1MarPQ1nv78DNe6FJrvQGz6WOTxp00KWfGXbA9" ?? '');
        define('STRIPE_SECRET_KEY', "sk_test_51NxGHQIrZYESSIgqOH9qryUbDk14t7YGfH0R2EEGVOVkPRcSkxIS1zeZ1LxNiU82e2ZHnbXHbZ1Ur5xUZMRUZGQk00WSXtcCIU" ?? '');
    } else {
        define('STRIPE_PUBLISHABLE_KEY', $gatewayData['stripe_public_key'] ?? '');
        define('STRIPE_SECRET_KEY', $gatewayData['stripe_secret_key'] ?? '');
    }
} else {
    // Agar payment method data missing ho to empty strings set kar do
    define('SQUARE_ACCESS_TOKEN', '');
    define('SQUARE_LOCATION_ID', '');
    define('SQUARE_APPLICATION_ID', '');
    define('PAYPAL_CLIENT_ID', '');
    define('PAYPAL_SECRET_KEY', '');
    define('PAYPAL_MERCHANT_ID', '');
    define('STRIPE_PUBLISHABLE_KEY', '');
    define('STRIPE_SECRET_KEY', '');
}


?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>Invoice #<?= htmlspecialchars($invoice['po_no']) ?></title>
     <link rel="shortcut icon" href="https://bookspublisherhub.com/images/fav.webp" type="image/x-icon">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .invoice-container {
            max-width: 800px;
            margin: 30px auto;
            padding: 30px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            position: relative;
        }
        .invoice-header {
            border-bottom: 2px solid #eee;
            padding-bottom: 20px;
            margin-bottom: 30px;
        }
        .invoice-title {
            font-size: 28px;
            font-weight: bold;
            color: #333;
        }
        .invoice-number {
            font-size: 18px;
            color: #666;
            margin-bottom: 10px;
        }
        .company-info {
            margin-bottom: 20px;
        }
        .balance-due {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            font-size: 16px;
            font-weight: bold;
            margin: 20px 0;
            text-align: right;
        }
        .bill-to {
            margin-bottom: 30px;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        .items-table th,
        .items-table td {
            padding: 8px;
            border-bottom: 1px solid #eee;
        }
        .items-table th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #ddd;
        }
        .items-table tr:last-child td {
            border-bottom: 2px solid #ddd;
        }
        .total-row {
            font-weight: bold;
        }
        .paid-stamp {
            position: absolute;
            top: 50%;
            left: 50%;
            color: green;
            font-size: 5rem;
            font-weight: bold;
            transform: rotate(-20deg) translate(-50%, -50%);
            opacity: 0.4;
        }
        .payment-form {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-top: 30px;
        }
    </style>
    <?php if (!$isPaid): ?>
        <?php if ($paymentMethod === 'paypal'): ?>
        
        <?php elseif ($paymentMethod === 'square'): ?>
        <script src="https://web.squarecdn.com/v1/square.js"></script>
        <?php elseif ($paymentMethod === 'stripe'): ?>
        <script src="https://js.stripe.com/v3/"></script>
        <?php endif; ?>
    <?php endif; ?>
</head>
<body>
<?php if (!empty($showError)): ?>
    <div class="d-flex justify-content-center align-items-center" style="height:100vh;background:#f8f9fa;">
        <div class="text-center p-5 bg-white shadow rounded" style="max-width:500px;width:100%;">
            <h1 class="text-danger mb-3">
                <?= http_response_code() ?>
            </h1>
            <h4 class="mb-3"><?= htmlspecialchars($errorMessage) ?></h4>
        </div>
    </div>
    <?php exit; ?>
<?php endif; ?>
<div class="invoice-container">
    
    <?php if ($isPaid): ?>
        <div class="paid-stamp">PAID</div>
    <?php endif; ?>
    <div class="invoice-header">
        <div class="row justify-content-between">
            <div class="col-lg-7 col-md-7">
                <div class="company-info">
                    <?php if (!empty($invoice['logo_path'])): ?>
                        <img src="<?= htmlspecialchars($invoice['logo_path']) ?>" alt="Logo" style="height:40px;margin-bottom:25px">
                    <?php else: ?>
                        <img src="https://bookspublisherhub.com/images/logo.webp" alt="Default Logo" style="height:80px;margin-bottom:25px">
                    <?php endif; ?>
                   
                    <p><?= htmlspecialchars($invoice['b_email']) ?><br>
                    <?= htmlspecialchars($invoice['b_contact']) ?> </p>
                </div>
                <div class="bill-to mt-2">
                    <h6 class="mb-3">Bill To:</h6>
                    <p> <strong><?= htmlspecialchars($invoice['name']) ?></strong><br>
                     <?= htmlspecialchars($invoice['email']) ?><br>
                    <?= htmlspecialchars($invoice['contact']) ?></p>
                </div>
            </div>
            <div class="col-lg-4 col-md-4">
                <div class="text-end mb-2">
                    <img src="https://bookspublisherhub.com/images/fav.webp" alt="Logo" style="height:50px;margin-bottom:20px">
                </div>
                <h1 class="invoice-title text-end mb-0">INVOICE</h1>
                <div class="invoice-number text-end">#<?= htmlspecialchars($invoice['po_no']) ?></div>
                <p class="mb-1 mt-3 d-flex justify-content-between"><strong>Date:</strong> <?= date('M d, Y', strtotime($invoice['created_at'])) ?></p>
                <?php if ($isPaid): ?>
                <p class="mb-1 d-flex justify-content-between" style="text-transform:capitalize;"><strong>Payment Method:</strong> <?=$paymentMethod?></p>
                <?php endif; ?>
                <p class="mb-1 d-flex justify-content-between"><strong>Due Date:</strong> <?= date('M d, Y', strtotime($invoice['due_date'])) ?></p>
                <p class="mb-1 d-flex justify-content-between"><strong>PO Number:</strong> <?= htmlspecialchars($invoice['po_no']) ?></p>
                <div class="balance-due d-flex justify-content-between m-0 text-start" style="padding-left:0;padding-right:0;">
                    <span>Balance Due:</span> <?=$currency;?><?= number_format($totalAmount, 2) ?>
                </div>
            </div>
        </div>
    </div>
    <table class="items-table" width="100%">
        <thead>
        <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th style="text-align:end">Rate</th>
            <th style="text-align:end">Amount</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($items as $item): ?>
            <tr>
                <td><?= htmlspecialchars($item['item_name']) ?></td>
                <td><?= htmlspecialchars($item['quantity']) ?></td>
                <td style="text-align:end"><?=$currency;?><?= number_format($item['rate'], 2) ?></td>
                <td style="text-align:end"><?=$currency;?><?= number_format($item['amount'], 2) ?></td>
            </tr>
        <?php endforeach; ?>
            <tr class="total-row">
                <td colspan="3" class="text-end">Subtotal</td>
                <td style="text-align:end"><?=$currency;?><?= number_format($subtotal, 2) ?></td>
            </tr>
            <!--<tr>-->
            <!--    <td colspan="3" class="text-end">Discount (<?= number_format($discountPercent, 2) ?>%)</td>-->
            <!--    <td style="text-align:end">(<?=$currency;?><?= number_format($discountAmount, 2) ?>)</td>-->
            <!--</tr>-->
            <tr>
                <td colspan="3" class="text-end">Tax (<?= number_format($taxPercent, 2) ?>%)</td>
                <td style="text-align:end"><?=$currency;?><?= number_format($taxAmount, 2) ?></td>
            </tr>
            <tr class="total-row">
                <td colspan="3" class="text-end">Total</td>
                <td style="text-align:end"><?=$currency;?><?= number_format($totalAmount, 2) ?></td>
            </tr>
        </tbody>
    </table>
    

    <?php if (!$isPaid): ?>
        <?php if ($paymentMethod === 'paypal'): ?>
            <div class="payment-form">
                <h4>Pay Now</h4>
                <div id="paypal-button-container"></div>
            </div>
        
            <!-- PayPal Advanced Checkout JS SDK -->
            <script src="https://www.paypal.com/sdk/js?client-id=<?= PAYPAL_CLIENT_ID ?>&currency=<?= $invoice['currency'] ?>&components=buttons,marks&intent=capture&enable-funding=paylater"></script>
        
            <script>
            paypal.Buttons({
                createOrder: function(data, actions) {
                    return fetch('/invoice/secure/paypal/paypal-create-order.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            amount: <?= json_encode($paypalTotalAmount) ?>,
                            currency: <?= json_encode($invoice['currency']) ?>,
                            invoice_id: <?= json_encode($invoiceId) ?>,
                            uuid: <?= json_encode($uuid) ?>,
                            hash: <?= json_encode($clientHash) ?>
                        })
                    }).then(res => res.json())
                      .then(order => order.id); // make sure create order returns { "id": "..." }
                },
                onApprove: function(data, actions) {
                    return fetch('/invoice/secure/paypal/paypal-capture-order.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            orderID: data.orderID,
                            invoice_id: <?= json_encode($invoiceId) ?>,
                            currency: <?= json_encode($invoice['currency']) ?>,
                            uuid: <?= json_encode($uuid) ?>,
                            hash: <?= json_encode($clientHash) ?>
                        })
                    })
                    .then(res => res.json())
                    .then(resData => {
                        if(resData.success){
                            // Reload invoice page to show PAID stamp
                            window.location.href = `/invoice/secure/<?= $uuid ?>/<?= $clientHash ?>`;
                        } else {
                            alert('Payment failed!');
                        }
                    });
                }
            }).render('#paypal-button-container');
            </script>
            
            
    <?php elseif ($paymentMethod === 'authorize'): ?>
       
      
       
       
            <div class="form_sect">
                <h2 class="text-center mb-4">Confirm Purchase</h2>
                <form method="post" id="registrationForm" action="/invoice/secure/authorize/process.php">
                    <div class="row">
                        <!-- Name -->
                        <div class="col-lg-6 mb-3">
                            <label for="name">Name:</label>
                            <input type="text" class="form-control" id="name" placeholder="Ex. Jason Smith" name="name" required>
                        </div>
                        <!-- Email -->
                        <div class="col-lg-6 mb-3">
                            <label for="email">Email:</label>
                            <input type="email" class="form-control" id="email" placeholder="example@xyz.com" name="email" required>
                        </div>
                        <!-- Card Number -->
                        <div class="col-lg-12 mb-3">
                            <label for="cardNo">Card No:</label>
                            <div class="d-flex gap-3 align-items-center">
                                <input type="text" class="form-control" id="cardNo" placeholder="1111 1111 1111 1111" name="card_number" required>
                                <img src="/invoice/secure/images/default.webp" alt="Payment Card" class="card_img" id="cardImage">
                            </div>
                        </div>
                        <!-- Expiry Date -->
                        <div class="col-lg-6 mb-3">
                            <label for="expiryMonth">Expiry Date:</label>
                            <div class="d-flex gap-2 align-items-center">
                                <input type="text" class="form-control" id="expiryMonth" placeholder="MM" name="card_exp_month" maxlength="2" style="width:60px" required> /
                                <input type="text" class="form-control" id="expiryYear" placeholder="YYYY" name="card_exp_year" maxlength="4" style="width:70px" required>
                            </div>
                            <div id="expiryError" class="text-danger error-message mt-1"></div>
                        </div>
                        <!-- CVC -->
                        <div class="col-lg-6 mb-3">
                            <label for="cvc">CVC Code:</label>
                            <input type="text" class="form-control" id="cvc" placeholder="CVC Code" name="card_cvc" maxlength="3" required>
                        </div>
                        <!-- Submit Button -->
                        <div class="col-lg-12 text-center">
                            <button type="submit" class="btn btn-primary w-100 mb-3">
                                Pay Now(<?= $currency; ?><?= number_format($totalAmount, 2, '.', '') ?>)
                            </button>
                            <input type="hidden" name="invoice_id" value="<?php echo $invoiceId; ?>">
                            <input type="hidden" name="uuid" value="<?php echo $uuid; ?>">
                            <input type="hidden" name="hash" value="<?php echo $clientHash; ?>">
                            <input type="hidden" name="desc" value="Payment Terminal">
                            <input type="hidden" name="amount" value="<?= number_format($totalAmount, 2, '.', '') ?>">
                            <img src="/invoice/secure/images/cards-collection.webp" alt="cards" class="img-fluid mt-4">
                        </div>
                    </div>
                </form>
            </div>


            
            <!-- jQuery and Authorize.Net Accept.js -->
            <script src="https://code.jquery.com/jquery-3.7.1.min.js"
                integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
            <script type="text/javascript" src="https://js.authorize.net/v1/Accept.js"></script>
            
            <script>
                $(document).ready(function() {
                    // Allow only numeric input for expiry and amount
                    $("#expiryMonth, #expiryYear, #amount").on("input", function() {
                        this.value = this.value.replace(/\D/g, '');
                    });
                
                    // Card input formatting and card type detection
                    $("#cardNo").on("input", function() {
                        let cardNumber = $(this).val().replace(/\D/g, ''); // keep only digits
                        let cardImage = $("#cardImage");
                
                        // Detect card type
                        let cardType = '';
                        if (/^4/.test(cardNumber)) cardType = 'visa';
                        else if (/^5[1-5]/.test(cardNumber)) cardType = 'mastercard';
                        else if (/^3[47]/.test(cardNumber)) cardType = 'amex';
                        else if (/^6(?:011|5)/.test(cardNumber)) cardType = 'discover';
                        else if (/^35[2-8]/.test(cardNumber)) cardType = 'jcb';
                        else if (/^3(?:0[0-5]|[68])/.test(cardNumber)) cardType = 'diners';
                        else cardType = 'default';
                
                        // Update card image
                        cardImage.attr("src", `/invoice/secure/images/${cardType}.webp`);
                
                        // Set max digits based on card type
                        let maxDigits = cardType === 'amex' ? 15 : 16;
                        cardNumber = cardNumber.slice(0, maxDigits);
                
                        // Format card number
                        let formatted = '';
                        if (cardType === 'amex') {
                            // Amex 4-6-5
                            formatted = cardNumber.replace(/^(\d{0,4})(\d{0,6})(\d{0,5})$/, function(_, g1, g2, g3) {
                                return [g1, g2, g3].filter(Boolean).join(' ');
                            });
                        } else {
                            // Other cards: groups of 4
                            formatted = cardNumber.replace(/(.{4})/g, '$1 ').trim();
                        }
                
                        $(this).val(formatted);
                
                        // Adjust CVC length
                        $("#cvc").attr("maxlength", cardType === 'amex' ? 4 : 3);
                    });
                
                    // Expiry date validation
                    $("#expiryMonth, #expiryYear").on("input", validateExpiryDate);
                    function validateExpiryDate() {
                        let month = parseInt($("#expiryMonth").val());
                        let year = parseInt($("#expiryYear").val());
                        let currentYear = new Date().getFullYear();
                        let currentMonth = new Date().getMonth() + 1;
                        let error = $("#expiryError");
                
                        if (isNaN(month) || month < 1 || month > 12) {
                            error.text("Invalid month (1-12).");
                            return false;
                        }
                        if (!isNaN(year)) {
                            if (year < currentYear || year > currentYear + 10) {
                                error.text("Invalid year. Enter a future year.");
                                return false;
                            }
                            if (year === currentYear && month < currentMonth) {
                                error.text("Invalid month. Expiry has passed.");
                                return false;
                            }
                        }
                        error.text("");
                        return true;
                    }
                
                    // Form submit using Accept.js
                    $("#registrationForm").submit(function(e) {
                        e.preventDefault();
                        if (!validateExpiryDate()) return false;
                
                        let secureData = {
                            authData: {
                                clientKey: "<?php echo AUTHORIZE_PUBLIC_KEY; ?>",
                                apiLoginID: "<?php echo AUTHORIZE_API_LOGIN_ID; ?>"
                            },
                            cardData: {
                                cardNumber: $("#cardNo").val().replace(/\s+/g, ''),
                                month: $("#expiryMonth").val(),
                                year: $("#expiryYear").val(),
                                cardCode: $("#cvc").val()
                            }
                        };
                
                        Accept.dispatchData(secureData, function(response) {
                            if (response.messages.resultCode === "Error") {
                                alert(response.messages.message[0].text);
                            } else {
                                if (!$("#dataValue").length) {
                                    $("#registrationForm").append('<input type="hidden" name="dataValue" id="dataValue">');
                                    $("#registrationForm").append('<input type="hidden" name="dataDescriptor" id="dataDescriptor">');
                                }
                                $("#dataValue").val(response.opaqueData.dataValue);
                                $("#dataDescriptor").val(response.opaqueData.dataDescriptor);
                
                                // Remove sensitive data before submission
                                $("#cardNo, #expiryMonth, #expiryYear, #cvc").remove();
                                $("#registrationForm")[0].submit();
                            }
                        });
                    });
                });
            </script>


            <?php elseif ($paymentMethod === 'epd'): ?>
            
            

                <div class="payment-form">
                    <h4>Pay with Easy Pay Direct</h4>
                
                    <form id="epdPaymentForm" method="POST" action="/invoice/secure/epd/process.php">
                
                        <!-- Hidden invoice & customer details -->
                        <input type="hidden" name="invoice_id" value="<?= $invoiceId ?>">
                        <input type="hidden" name="uuid" value="<?= $uuid ?>">
                        <input type="hidden" name="hash" value="<?= $clientHash ?>">
                        <input type="hidden" name="amount" value="<?= number_format($totalAmount,2,'.','') ?>">
                        <input type="hidden" name="currency" value="<?= htmlspecialchars($invoice['currency']) ?>">
                        <input type="hidden" name="customer_name" value="<?= htmlspecialchars($invoice['name']) ?>">
                        <input type="hidden" name="customer_email" value="<?= htmlspecialchars($invoice['email']) ?>">
                        <input type="hidden" name="customer_contact" value="<?= htmlspecialchars($invoice['contact']) ?>">
                
                        <div class="form-group mb-2">
                            <label>Card Number</label>
                            <input type="text" id="cardNumber" name="cardNumber" class="form-control" placeholder="Card Number">
                        </div>
                
                        <div class="row">
                            <div class="col-2">
                                <label>MM</label>
                                <input type="text" id="expiryMonth" name="expiryMonth" class="form-control" placeholder="MM" maxlength="2">
                            </div>
                            <div class="col-2">
                                <label>YY</label>
                                <input type="text" id="expiryYear" name="expiryYear" class="form-control" placeholder="YY" maxlength="2">
                            </div>
                            <div class="col-3">
                                <label>CVV</label>
                                <input type="text" id="cvv" name="cvv" class="form-control" placeholder="CVV">
                            </div>
                        </div>
                
                        <button type="submit" class="btn btn-primary mt-3">
                            Pay <?= $currency ?><?= number_format($totalAmount,2) ?>
                        </button>
                    </form>
                
                    <!-- Expiry error display -->
                    <div id="expiryError" style="color:red; margin-top:5px;"></div>
                </div>
                
                <script src="https://code.jquery.com/jquery-3.7.1.min.js"
                        integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
                <script>
                $(document).ready(function() {
                
                    // Only numeric input
                    $("#expiryMonth, #expiryYear, #cvv").on("input", function() {
                        this.value = this.value.replace(/\D/g, '');
                    });
                
                    // Card formatting
                    $("#cardNumber").on("input", function() {
                        let cardNumber = $(this).val().replace(/\D/g, '');
                        let cardType = '';
                
                        if (/^4/.test(cardNumber)) cardType = 'visa';
                        else if (/^5[1-5]/.test(cardNumber)) cardType = 'mastercard';
                        else if (/^3[47]/.test(cardNumber)) cardType = 'amex';
                        else if (/^6(?:011|5)/.test(cardNumber)) cardType = 'discover';
                        else if (/^35[2-8]/.test(cardNumber)) cardType = 'jcb';
                        else if (/^3(?:0[0-5]|[68])/.test(cardNumber)) cardType = 'diners';
                        else cardType = 'default';
                
                        let maxDigits = cardType === 'amex' ? 15 : 16;
                        cardNumber = cardNumber.slice(0, maxDigits);
                
                        let formatted = '';
                        if (cardType === 'amex') {
                            formatted = cardNumber.replace(/^(\d{0,4})(\d{0,6})(\d{0,5})$/, function(_, g1, g2, g3) {
                                return [g1, g2, g3].filter(Boolean).join(' ');
                            });
                        } else {
                            formatted = cardNumber.replace(/(.{4})/g, '$1 ').trim();
                        }
                
                        $(this).val(formatted);
                        $("#cvv").attr("maxlength", cardType === 'amex' ? 4 : 3);
                    });
                
                    // Expiry date validation
                    function validateExpiryDate() {
                        let month = parseInt($("#expiryMonth").val());
                        let year = parseInt($("#expiryYear").val());
                        let currentYear = new Date().getFullYear() % 100; // YY
                        let currentMonth = new Date().getMonth() + 1;
                        let error = $("#expiryError");
                
                        if (isNaN(month) || month < 1 || month > 12) {
                            error.text("Invalid month (1-12).");
                            return false;
                        }
                
                        if (!isNaN(year)) {
                            if (year < currentYear || year > currentYear + 20) {
                                error.text("Invalid year. Enter a future year.");
                                return false;
                            }
                            if (year === currentYear && month < currentMonth) {
                                error.text("Invalid month. Expiry has passed.");
                                return false;
                            }
                        }
                        error.text("");
                        return true;
                    }
                
                    $("#expiryMonth, #expiryYear").on("input", validateExpiryDate);
                
                    // Form submission
                    $("#epdPaymentForm").submit(function(e) {
                        e.preventDefault();
                
                        let cardNumber = $("#cardNumber").val().replace(/\s+/g, '');
                        let cvv = $("#cvv").val();
                        let month = $("#expiryMonth").val();
                        let year = $("#expiryYear").val();
                
                        if (!cardNumber || cardNumber.length < 13) { 
                            alert("Please enter a valid card number."); 
                            return false; 
                        }
                        if (!validateExpiryDate()) return false;
                        if (!cvv || cvv.length < 3) { 
                            alert("Please enter a valid CVV."); 
                            return false; 
                        }
                
                        this.submit();
                    });
                
                });
                </script>





        <?php elseif ($paymentMethod === 'stripe'): ?>
    <div class="payment-form">
        <h4>Pay Now with Stripe</h4>
        <p>Use the form below to pay **<?=$currency;?><?= number_format($totalAmount, 2) ?>**</p>
        <div id="card-element" class="mb-3">
            </div>
        <div id="card-errors" role="alert" style="color: red; margin-bottom: 15px;"></div>
        
        <button id="stripe-card-button" class="btn btn-primary">Pay <?=$currency;?><?= number_format($totalAmount, 2) ?></button>
        <form id="stripe-payment-form" method="POST" action="/invoice/secure/pay-stripe.php" style="display: none;">
            <input type="hidden" name="invoice_id" value="<?= htmlspecialchars($invoiceId) ?>">
            <input type="hidden" name="uuid" value="<?= htmlspecialchars($uuid) ?>">
            <input type="hidden" name="hash" value="<?= htmlspecialchars($clientHash) ?>">
            <input type="hidden" name="amount" value="<?= number_format($totalAmount, 2, '.', '') ?>">
            <input type="hidden" id="stripe_client_secret" name="client_secret" value=""> 
            <input type="hidden" id="stripe_payment_intent_id" name="payment_intent_id" value=""> 
        </form>
    </div>
    <script>
        // The Stripe client-side setup
        const stripe = Stripe('<?= STRIPE_PUBLISHABLE_KEY ?>');
        const elements = stripe.elements();
        
        // Create an instance of the card Element.
        const card = elements.create('card');
        
        // Add an instance of the card Element into the `card-element` div.
        card.mount('#card-element');
        
        // Handle real-time validation errors from the card Element.
        card.addEventListener('change', function(event) {
            const displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });

        // Handle form submission: 1. Get Client Secret, 2. Confirm Payment
        document.getElementById('stripe-card-button').addEventListener('click', async function(ev) {
            ev.preventDefault();
            const button = document.getElementById('stripe-card-button');
            const errorDisplay = document.getElementById('card-errors');
            
            button.disabled = true;
            button.textContent = 'Processing...';
            errorDisplay.textContent = ''; // Clear previous errors

            try {
                // 1. **AJAX Call:** Get the client_secret from the server
                // NOTE: You MUST create a PHP file at this URL to return the client_secret
                const response = await fetch('https://bookspublisherhub.com/invoice/secure/create-payment-intent.php', { 
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        invoice_id: <?= json_encode($invoiceId) ?>,
                        amount: <?= json_encode(round($totalAmount * 100)) ?>, // Amount in cents
                        currency: '<?= htmlspecialchars($invoice['currency']) ?>'
                    })
                });

                const data = await response.json();

                if (data.error) {
                    throw new Error(data.error);
                }

                const paymentIntentClientSecret = data.client_secret;
                
                // 2. **Confirm Payment:** Use the client secret to confirm the card payment
                const { paymentIntent, error } = await stripe.confirmCardPayment(paymentIntentClientSecret, {
                    payment_method: {
                        card: card,
                        billing_details: {
                            name: '<?= addslashes($invoice['name']) ?>'
                        }
                    }
                });

                if (error) {
                    // Show error to your customer (e.g., card declined)
                    errorDisplay.textContent = error.message;
                } else {
                    // The payment has been processed!
                    if (paymentIntent.status === 'succeeded') {
                        // 3. **Submit Form:** Send confirmation data to your final server endpoint
                        document.getElementById('stripe_payment_intent_id').value = paymentIntent.id;
                        document.getElementById('stripe-payment-form').submit();
                    } else {
                         // Handle other statuses (e.g., requires_action) if needed
                         errorDisplay.textContent = 'Payment status: ' + paymentIntent.status + '. Action may be required.';
                    }
                }
            } catch (e) {
                errorDisplay.textContent = e.message;
            } finally {
                // Re-enable the button after process completes or fails
                button.disabled = false;
                button.textContent = `Pay <?=$currency;?><?= number_format($totalAmount, 2) ?>`;
            }
        });
    </script>
        <?php else: ?>
            <div class="payment-form">
        <h4>Pay Now with Square</h4>
        <p>Use the form below to pay **<?=$currency;?><?= number_format($totalAmount, 2) ?>**</p>
        <div id="card-container" class="mb-3"></div>
        <button id="card-button" class="btn btn-primary">Pay <?=$currency;?><?= number_format($totalAmount, 2) ?></button>
        <form id="payment-form" method="POST" action="/pay">
            <input type="hidden" id="nonce" name="nonce">
            <input type="hidden" name="invoice_id" value="<?= htmlspecialchars($invoiceId) ?>">
            <input type="hidden" name="uuid" value="<?= htmlspecialchars($uuid) ?>">
            <input type="hidden" name="hash" value="<?= htmlspecialchars($clientHash) ?>">
            <input type="hidden" name="amount" value="<?= number_format($totalAmount, 2, '.', '') ?>">
        </form>
    </div>
    <script>
        const appId = '<?= SQUARE_APPLICATION_ID ?>';
        const locationId = '<?= SQUARE_LOCATION_ID ?>';
        async function initializeCard(payments) {
            const card = await payments.card();
            await card.attach('#card-container');
            return card;
        }
        document.addEventListener('DOMContentLoaded', async function () {
            const payments = window.Square.payments(appId, locationId);
            const card = await initializeCard(payments);
            document.getElementById('card-button').addEventListener('click', async function () {
                const result = await card.tokenize();
                if (result.status === 'OK') {
                    document.getElementById('nonce').value = result.token;
                    document.getElementById('payment-form').submit();
                } else {
                    alert('Card tokenization failed: ' + (result.errors?.[0]?.message || 'Unknown error'));
                }
            });
        });
    </script>
        <?php endif; ?>
   
    <?php endif; ?>
    
    <div class="foot_desc" style="padding-top:25px">
        <small style="text-align:center;display:block;font-size:12px;">On your bank statement, the descriptor will appear as <strong><?php echo $merchantName?></strong> as the merchant name.</small>
    </div>
    
</div>
</body>
</html>
<?php $conn->close(); ?>