<?php
// Session Start
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once 'config/database.php';

// ডাটাবেস এরর যাতে স্পষ্টভাবে দেখা যায়
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// =========================================================
// 🚀 1. DYNAMIC API CONFIGURATION
// =========================================================
$system_settings = [];
try {
    $stmt = $db->query("SELECT * FROM system_settings WHERE id = 1");
    $system_settings = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}

$api_key = $system_settings['domain_api_key'] ?? '';
$api_email = $system_settings['domain_api_email'] ?? '';
$api_endpoint = rtrim($system_settings['domain_api_url'] ?? '', '/');

function callResellerAPI($action, $method = 'GET', $params = []) {
    global $api_key, $api_email, $api_endpoint;
    
    $token = base64_encode(hash_hmac("sha256", $api_key, $api_email . ":" . gmdate("y-m-d H")));
    $headers = [
        "username: " . $api_email,
        "token: " . $token
    ];

    $curl = curl_init();
    $url = $api_endpoint . $action;

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    if ($method === 'POST') {
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    }

    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);

    if ($err) return ['result' => 'error', 'message' => "cURL Error: $err"];
    
    $decoded = json_decode($response, true);
    if ($decoded === null) {
        return ['result' => 'error', 'message' => "Invalid API Response"];
    }
    return $decoded;
}

// লগইন চেক এবং ইউজার ডাটা আনা
$is_user_logged_in = isset($_SESSION['user_id']);
$user_balance = 0.00;
$user_details = [];

if ($is_user_logged_in) {
    try {
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user_details = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user_details) {
            $user_balance = $user_details['balance'];
        }
    } catch (PDOException $e) {}
}

// Auto Create Orders Table Columns
try {
    $db->exec("ALTER TABLE `orders` ADD COLUMN `item_type` VARCHAR(50) DEFAULT 'domain' AFTER `user_id`");
    $db->exec("ALTER TABLE `orders` ADD COLUMN `item_name` VARCHAR(255) NULL AFTER `item_type`");
    $db->exec("ALTER TABLE `orders` ADD COLUMN `period` INT DEFAULT 1 AFTER `total_amount`");
} catch(PDOException $e) {}

// =========================================================
// 🚀 2. AJAX PAYMENT HANDLER (No Page Reload)
// =========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_pay'])) {
    header('Content-Type: application/json');
    
    if (!$is_user_logged_in) {
        echo json_encode(['status' => 'error', 'message' => 'Please login first.']);
        exit;
    }

    $total_amount = floatval($_POST['total_amount']);
    $invoice_id = $_POST['invoice_id'];

    if ($user_balance < $total_amount) {
        echo json_encode(['status' => 'error', 'message' => 'Insufficient balance! Please add funds to your account.']);
        exit;
    }

    try {
        $db->beginTransaction();

        // ১. ব্যালেন্স কাটা
        $update_balance = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $update_balance->execute([$total_amount, $_SESSION['user_id']]);

        $insert_order = $db->prepare("INSERT INTO orders (invoice_id, user_id, item_type, item_name, domain_name, total_amount, period, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        
        $has_pending_items = false;
        $last_domain_id = 0;

        foreach ($_SESSION['cart'] as $item) {
            $domain_status = 'active'; 
            
            if ($item['type'] == 'domain') {
                $name_parts = explode(' ', trim($user_details['name']), 2);
                $firstname = !empty($name_parts[0]) ? $name_parts[0] : 'Client';
                $lastname = !empty($name_parts[1]) ? $name_parts[1] : 'User';

                $country_code = 'BD';
                $ucountry = strtolower($user_details['country'] ?? 'Bangladesh');
                if($ucountry == 'india') $country_code = 'IN';
                elseif($ucountry == 'united states') $country_code = 'US';
                elseif($ucountry == 'united kingdom') $country_code = 'GB';

                $contact_info = [
                    "firstname" => $firstname,
                    "lastname" => $lastname,
                    "fullname" => trim($user_details['name']),
                    "companyname" => !empty($user_details['company_name']) ? $user_details['company_name'] : 'N/A',
                    "email" => trim($user_details['email']),
                    "address1" => !empty($user_details['address']) ? $user_details['address'] : 'Dhaka, Bangladesh',
                    "city" => !empty($user_details['city']) ? $user_details['city'] : 'Dhaka',
                    "state" => !empty($user_details['state']) ? $user_details['state'] : 'Dhaka',
                    "postcode" => !empty($user_details['postcode']) ? $user_details['postcode'] : '1200',
                    "country" => $country_code,
                    "phonenumber" => !empty($user_details['phone']) ? $user_details['phone'] : '01700000000'
                ];

                $api_params = [
                    "domain" => trim($item['name']),
                    "regperiod" => (int) (!empty($item['period']) ? $item['period'] : 1),
                    "paymentmethod" => "spacepay", // 🚀 Required by WHMCS
                    "nameservers" => [
                        "ns1" => "ns1.plexio.it",
                        "ns2" => "ns2.plexio.it"
                    ],
                    "contacts" => [
                        "registrant" => $contact_info,
                        "tech" => $contact_info,
                        "billing" => $contact_info,
                        "admin" => $contact_info
                    ]
                ];

                $api_res = callResellerAPI("/order/domains/register", "POST", $api_params);

                $is_success = false;
                if (isset($api_res['result']) && strtolower($api_res['result']) === 'success') { $is_success = true; }
                if (isset($api_res['status']) && strtolower($api_res['status']) === 'success') { $is_success = true; }
                if (isset($api_res['success']) && $api_res['success'] === true) { $is_success = true; }

                if (!$is_success) {
                    $domain_status = 'pending';
                    $has_pending_items = true;
                }
            }

            $item_total_price = $item['price'] * $item['period'];
            $insert_order->execute([
                $invoice_id,
                $_SESSION['user_id'], 
                $item['type'], 
                $item['name'], 
                $item['name'], 
                $item_total_price, 
                $item['period'],
                $domain_status 
            ]);
            
            $last_domain_id = $db->lastInsertId();
        }

        $db->commit();
        
        unset($_SESSION['cart']);
        unset($_SESSION['current_invoice_id']);
        
        echo json_encode([
            'status' => 'success',
            'is_pending' => $has_pending_items,
            'manage_id' => $last_domain_id
        ]);
        exit;
        
    } catch(Exception $e) {
        $db->rollBack();
        echo json_encode(['status' => 'error', 'message' => "Transaction error. Contact Support."]);
        exit;
    }
}

// =========================================================
// 3. PAGE RENDER LOGIC
// =========================================================
if (isset($_GET['remove'])) {
    $remove_key = $_GET['remove'];
    if (isset($_SESSION['cart'][$remove_key])) {
        unset($_SESSION['cart'][$remove_key]);
        if(empty($_SESSION['cart'])) unset($_SESSION['current_invoice_id']);
        header("Location: cart.php");
        exit;
    }
}

$cart_items = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
$subtotal = 0;
foreach ($cart_items as $item) { $subtotal += ($item['price'] * $item['period']); }
$tax = 0;
$total = $subtotal + $tax;

$is_checkout_mode = isset($_GET['checkout']) && $_GET['checkout'] == '1';

if ($is_checkout_mode && !$is_user_logged_in) {
    $_SESSION['redirect_url'] = "cart.php?checkout=1";
    header("Location: login.php");
    exit;
}

if ($is_checkout_mode && $is_user_logged_in && !empty($cart_items)) {
    if(!isset($_SESSION['current_invoice_id'])) {
        $_SESSION['current_invoice_id'] = 'PLX-' . strtoupper(substr(uniqid(), -6));
    }
    $current_invoice_id = $_SESSION['current_invoice_id'];
}

$page_title = "Shopping Cart";
require_once 'includes/user_header.php';
require_once 'includes/user_sidebar.php';
?>

<style>
    body {
        background-color: #ffffff !important;
        background-image: 
            linear-gradient(rgba(37, 99, 235, 0.03) 1px, transparent 1px),
            linear-gradient(90deg, rgba(37, 99, 235, 0.03) 1px, transparent 1px) !important;
        background-size: 30px 30px !important;
        animation: smoothLoad 0.4s ease-in-out;
    }
    @keyframes smoothLoad { from { opacity: 0; } to { opacity: 1; } }
    
    .cart-container { background: #ffffff; border-radius: 20px; border: 1px solid rgba(15, 23, 42, 0.05); box-shadow: 0 10px 40px rgba(0, 0, 0, 0.04); padding: 30px; margin-bottom: 30px; }
    .item-row { border-bottom: 1px solid rgba(15, 23, 42, 0.05); padding: 20px 0; }
    .item-row:last-child { border-bottom: none; }
    .btn-remove { color: #ef4444; background: rgba(239, 68, 68, 0.1); width: 35px; height: 35px; display: flex; align-items: center; justify-content: center; border-radius: 10px; text-decoration: none; transition: 0.3s; }
    .btn-remove:hover { background: #ef4444; color: white; }
    .summary-box { background: #f8fafc; border-radius: 20px; padding: 25px; border: 1px dashed rgba(37, 99, 235, 0.2); }
    .btn-primary-custom { background: #2563eb; color: white; border: none; padding: 14px 20px; border-radius: 12px; font-weight: 700; width: 100%; text-decoration: none; display: block; text-align: center; transition: all 0.3s; }
    .btn-primary-custom:hover { background: #1d4ed8; transform: translateY(-2px); box-shadow: 0 10px 20px rgba(37, 99, 235, 0.3); color: white; }

    /* Invoice Styles */
    .invoice-box { background: white; border: 2px solid #2563eb; border-radius: 20px; padding: 40px; position: relative; overflow: hidden; transition: all 0.3s; }
    .invoice-watermark { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%) rotate(-30deg); font-size: 8rem; color: rgba(37, 99, 235, 0.03); font-weight: 900; pointer-events: none; white-space: nowrap; z-index: 1; }
    
    .invoice-status-stamp {
        position: absolute; top: 20px; right: -35px; transform: rotate(45deg);
        background: #ef4444; color: white; padding: 5px 40px; font-weight: 800; font-size: 14px; z-index: 2; letter-spacing: 2px; transition: all 0.4s;
    }
    .invoice-status-stamp.paid { background: #10b981; }
    .invoice-status-stamp.pending { background: #f59e0b; color: white; }

    .invoice-header { border-bottom: 2px dashed rgba(15, 23, 42, 0.1); padding-bottom: 20px; margin-bottom: 20px; position: relative; z-index: 2; }
    .invoice-content { position: relative; z-index: 2; }
    
    .btn-pay { background: #10b981; color: white; border: none; padding: 15px; border-radius: 12px; font-weight: 800; font-size: 16px; width: 100%; transition: 0.3s; }
    .btn-pay:hover { background: #059669; transform: translateY(-3px); box-shadow: 0 10px 25px rgba(16, 185, 129, 0.4); }

    /* Print Styles */
    @media print {
        body * { visibility: hidden; }
        .invoice-box, .invoice-box * { visibility: visible; }
        .invoice-box { position: absolute; left: 0; top: 0; width: 100%; border: none; padding: 0; }
        .no-print { display: none !important; }
    }
</style>

<div class="main-content flex-grow-1 w-100 d-flex flex-column py-5" style="min-height: calc(100vh - 70px);">
    <div class="container" style="max-width: 1000px;">

        <?php if(empty($cart_items) && !$is_checkout_mode): ?>
            <div class="cart-container text-center py-5">
                <img src="../assets/images/empty-cart.png" alt="Empty Cart" style="max-width: 200px; opacity: 0.5; margin-bottom: 20px;" onerror="this.style.display='none';">
                <i class="fa-solid fa-cart-arrow-down mb-3 text-muted" style="font-size: 60px;"></i>
                <h2 class="fw-bold text-dark">Your Cart is Empty</h2>
                <p class="text-muted mb-4">Looks like you haven't added any domains or hosting yet.</p>
                <a href="register-domain.php" class="btn btn-primary rounded-pill px-4 py-2 fw-bold">Search Domains</a>
            </div>

        <?php elseif($is_checkout_mode && $is_user_logged_in): ?>
            <div class="row">
                <div class="col-12 mb-3 d-flex justify-content-between align-items-center no-print" id="topActionArea">
                    <a href="cart.php" class="text-muted text-decoration-none fw-bold" id="backToCartBtn"><i class="fa-solid fa-arrow-left me-2"></i>Back to Cart</a>
                    <button onclick="window.print()" class="btn btn-outline-dark btn-sm rounded-pill fw-bold"><i class="fa-solid fa-download me-2"></i>Download PDF</button>
                </div>

                <div class="col-lg-8 mb-4">
                    <div class="invoice-box shadow-sm" id="printableInvoice">
                        <div class="invoice-watermark">PLEXIO IT</div>
                        <div class="invoice-status-stamp" id="invoiceStamp">UNPAID</div>
                        
                        <div class="invoice-header d-flex justify-content-between align-items-center">
                            <div><img src="../assets/images/logo-dark.png" alt="Plexio IT" height="40"></div>
                            <div class="text-end">
                                <h4 class="fw-bold text-primary mb-0">INVOICE</h4>
                                <span class="fw-bold text-dark d-block">#<?= $current_invoice_id ?></span>
                                <span class="text-muted" style="font-size: 13px;">Date: <?= date('d M, Y') ?></span>
                            </div>
                        </div>

                        <div class="invoice-content">
                            <div class="row mb-5">
                                <div class="col-sm-6">
                                    <span class="text-muted fw-bold" style="font-size: 13px; text-transform: uppercase;">Billed To:</span>
                                    <h5 class="fw-bold text-dark mt-1 mb-0"><?= htmlspecialchars($user_details['name']) ?></h5>
                                    <div class="text-muted" style="font-size: 14px;">
                                        <?= htmlspecialchars($user_details['email']) ?><br>
                                        <?= htmlspecialchars($user_details['phone'] ?? '') ?><br>
                                        <?= htmlspecialchars($user_details['address'] ?? '') . ', ' . htmlspecialchars($user_details['city'] ?? '') ?>
                                    </div>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-borderless">
                                    <thead class="border-bottom">
                                        <tr class="text-muted" style="font-size: 14px;">
                                            <th>Description</th>
                                            <th class="text-center">Term</th>
                                            <th class="text-end">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($cart_items as $item): ?>
                                        <tr class="border-bottom">
                                            <td class="py-3">
                                                <span class="fw-bold text-dark d-block"><?= htmlspecialchars($item['name']) ?></span>
                                                <span class="badge bg-primary text-uppercase" style="font-size: 10px;"><?= htmlspecialchars($item['type']) ?> Registration</span>
                                            </td>
                                            <td class="py-3 text-center align-middle"><?= $item['period'] ?> Year</td>
                                            <td class="py-3 text-end align-middle fw-bold">৳ <?= number_format($item['price'] * $item['period'], 2) ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td colspan="2" class="text-end py-3 text-muted fw-bold">Total Due:</td>
                                            <td class="text-end py-3 fs-5 fw-bold text-primary">৳ <?= number_format($total, 2) ?></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-4 no-print">
                    <div class="summary-box shadow-sm position-sticky" style="top: 90px;" id="paymentSidebar">
                        <h5 class="fw-bold mb-3 border-bottom pb-2">Payment Summary</h5>
                        <div class="d-flex justify-content-between mb-4">
                            <span class="fs-5 fw-bold text-dark">Total Due:</span>
                            <span class="fs-4 fw-bold text-primary">৳ <?= number_format($total, 2) ?></span>
                        </div>

                        <div class="bg-white p-3 rounded-3 mb-4 border text-center">
                            <span class="text-muted d-block mb-1" style="font-size: 13px;">Your Current Balance</span>
                            <h4 class="fw-bold <?= $user_balance < $total ? 'text-danger' : 'text-success' ?> mb-0" id="currentBalanceText">৳ <?= number_format($user_balance, 2) ?></h4>
                        </div>

                        <button type="button" class="btn-pay" data-bs-toggle="modal" data-bs-target="#payConfirmModal">
                            <i class="fa-solid fa-lock me-2"></i> Pay Now
                        </button>
                    </div>

                    <!-- Success Actions -->
                    <div class="summary-box shadow-sm position-sticky d-none" style="top: 90px;" id="successSidebar">
                        <div class="text-center mb-4">
                            <div class="bg-success bg-opacity-10 text-success rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 70px; height: 70px;" id="successIconBox">
                                <i class="fa-solid fa-check fs-2" id="successIcon"></i>
                            </div>
                            <h4 class="fw-bold text-dark" id="successTitle">Order Successful!</h4>
                            <p class="text-muted" style="font-size: 14px;" id="successDesc">Your invoice has been paid and domain is active.</p>
                        </div>
                        
                        <div class="d-grid gap-3">
                            <button onclick="window.print()" class="btn btn-outline-dark fw-bold rounded-pill"><i class="fa-solid fa-download me-2"></i>Download Invoice</button>
                            <a href="my-domains.php" class="btn btn-primary fw-bold rounded-pill" id="btnManageDomain"><i class="fa-solid fa-gear me-2"></i>Manage Domain</a>
                            <a href="dashboard.php" class="text-muted text-center text-decoration-none fw-bold" style="font-size: 14px;">Go to Dashboard</a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Beautiful Confirmation Modal -->
            <div class="modal fade" id="payConfirmModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content border-0 rounded-4 shadow-lg">
                        <div class="modal-header border-0 pb-0">
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body text-center pb-5 px-4">
                            <div class="mb-4">
                                <div class="bg-light rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 80px; height: 80px;">
                                    <i class="fa-solid fa-wallet text-primary fs-1"></i>
                                </div>
                            </div>
                            <h3 class="fw-bold text-dark mb-2">Confirm Payment</h3>
                            <p class="text-muted fs-5 mb-4">Are you sure you want to pay <strong class="text-primary">৳ <?= number_format($total, 2) ?></strong> from your account balance?</p>
                            
                            <form id="ajaxPaymentForm">
                                <input type="hidden" name="total_amount" value="<?= $total ?>">
                                <input type="hidden" name="invoice_id" value="<?= $current_invoice_id ?>">
                                <input type="hidden" name="ajax_pay" value="1">
                                <div class="d-flex gap-3 justify-content-center">
                                    <button type="button" class="btn btn-light rounded-pill px-4 fw-bold border" data-bs-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-primary rounded-pill px-5 fw-bold shadow-sm" id="btnPayNow">Yes, Pay Now</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

        <?php else: ?>
            <div class="row">
                <div class="col-12"><h2 class="fw-bold text-dark mb-4">Review Your Cart</h2></div>
                <div class="col-lg-8 mb-4">
                    <div class="cart-container">
                        <?php foreach($cart_items as $key => $item): ?>
                            <div class="item-row d-flex justify-content-between align-items-center flex-wrap gap-3">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="bg-light rounded-3 p-3 d-flex align-items-center justify-content-center" style="width: 60px; height: 60px;">
                                        <i class="fa-solid fa-globe fs-3 text-primary"></i>
                                    </div>
                                    <div>
                                        <span class="badge bg-primary text-uppercase mb-1" style="font-size: 10px;"><?= htmlspecialchars($item['type']) ?></span>
                                        <h5 class="fw-bold text-dark mb-0"><?= htmlspecialchars($item['name']) ?></h5>
                                        <span class="text-muted" style="font-size: 13px;">Registration (<?= $item['period'] ?> Year)</span>
                                    </div>
                                </div>
                                <div class="d-flex align-items-center gap-4">
                                    <h4 class="fw-bold text-dark mb-0">৳ <?= number_format($item['price'] * $item['period'], 2) ?></h4>
                                    <a href="cart.php?remove=<?= urlencode($key) ?>" class="btn-remove" title="Remove Item"><i class="fa-solid fa-trash-can"></i></a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="col-lg-4">
                    <div class="summary-box shadow-sm position-sticky" style="top: 90px;">
                        <h5 class="fw-bold mb-4">Order Summary</h5>
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted">Subtotal:</span>
                            <span class="fw-bold text-dark">৳ <?= number_format($subtotal, 2) ?></span>
                        </div>
                        <div class="d-flex justify-content-between mb-4 border-bottom pb-4">
                            <span class="text-muted">Setup Fees:</span>
                            <span class="fw-bold text-success">Free</span>
                        </div>
                        <div class="d-flex justify-content-between mb-4">
                            <span class="fs-5 fw-bold text-dark">Total:</span>
                            <span class="fs-4 fw-bold text-primary">৳ <?= number_format($total, 2) ?></span>
                        </div>
                        <a href="cart.php?checkout=1" class="btn-primary-custom">Proceed to Checkout <i class="fa-solid fa-arrow-right ms-2"></i></a>
                    </div>
                </div>
            </div>
        <?php endif; ?>

    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let paymentForm = document.getElementById('ajaxPaymentForm');
    
    if (paymentForm) {
        paymentForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            let btnPay = document.getElementById('btnPayNow');
            btnPay.disabled = true;
            btnPay.innerHTML = '<i class="fa-solid fa-spinner fa-spin me-2"></i> Processing...';
            
            let formData = new FormData(this);

            fetch('cart.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // Hide Bootstrap Modal cleanly
                    let modalEl = document.getElementById('payConfirmModal');
                    let modalInstance = bootstrap.Modal.getInstance(modalEl);
                    if(modalInstance) { modalInstance.hide(); }
                    
                    document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
                    document.body.classList.remove('modal-open');
                    document.body.style = '';

                    let stamp = document.getElementById('invoiceStamp');

                    if (data.is_pending) {
                        stamp.innerText = 'PENDING';
                        stamp.classList.add('pending');
                        document.getElementById('successTitle').innerText = 'Order Pending!';
                        document.getElementById('successDesc').innerText = 'Your payment was received, but domain registration is pending manual review.';
                        document.getElementById('successIconBox').className = "bg-warning bg-opacity-10 text-warning rounded-circle d-inline-flex align-items-center justify-content-center mb-3";
                        document.getElementById('successIcon').className = "fa-solid fa-clock fs-2";
                    } else {
                        stamp.innerText = 'PAID';
                        stamp.classList.add('paid');
                    }

                    document.getElementById('paymentSidebar').classList.add('d-none');
                    document.getElementById('successSidebar').classList.remove('d-none');
                    document.getElementById('backToCartBtn').classList.add('d-none');

                    if(data.manage_id && data.manage_id > 0) {
                        document.getElementById('btnManageDomain').href = 'manage-domain.php?id=' + data.manage_id;
                    }

                } else {
                    alert(data.message || "An error occurred!");
                    btnPay.disabled = false;
                    btnPay.innerHTML = 'Yes, Pay Now';
                }
            })
            .catch(error => {
                alert("Server connection failed. Please try again.");
                btnPay.disabled = false;
                btnPay.innerHTML = 'Yes, Pay Now';
            });
        });
    }
});
</script>

<?php require_once 'includes/user_footer.php'; ?>