<?php
require_once 'config/database.php';
require_once 'config/settings.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'payment/zarinpal.php';

Auth::requireLogin();
Auth::checkSessionTimeout();

$pageTitle = 'تکمیل خرید | کیف‌لند';
$db       = Database::getInstance()->getConnection();
$settings = SiteSettings::getInstance();
$user     = Auth::currentUser();

$stmt = $db->prepare("SELECT c.*, p.name, p.price, p.discount_price, p.stock, p.sku FROM cart c JOIN products p ON c.product_id = p.id WHERE c.user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$cartItems = $stmt->fetchAll();

if (!$cartItems) { header('Location: cart.php'); exit; }

$total = 0;
foreach ($cartItems as &$item) {
    $item['final_price'] = $item['discount_price'] ?: $item['price'];
    $item['subtotal']    = $item['final_price'] * $item['quantity'];
    $total              += $item['subtotal'];
}
unset($item);

$shipping  = getShippingCost($total);
$tax       = calculateTax($total, 9);
$final     = $total + $shipping + $tax;
$error     = '';

// موجودی کیف پول
$wq = $db->prepare("SELECT wallet_balance FROM users WHERE id=?");
$wq->execute([$_SESSION['user_id']]);
$walletBal = (int)$wq->fetchColumn();

$card_number = $settings->get('card_number','');
$card_owner  = $settings->get('card_owner','');
$card_bank   = $settings->get('card_bank','');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Auth::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'خطای امنیتی.';
    } else {
        $full_name      = sanitize($_POST['full_name']);
        $phone          = sanitize($_POST['phone']);
        $city           = sanitize($_POST['city']);
        $address        = sanitize($_POST['address']);
        $postal_code    = sanitize($_POST['postal_code']);
        $payment_method = $_POST['payment_method'] ?? 'online';
        $notes          = sanitize($_POST['notes'] ?? '');
        $receipt_number = sanitize($_POST['receipt_number'] ?? '');
        $use_wallet     = isset($_POST['use_wallet']) && $_POST['use_wallet'] == '1';
        $wallet_amount  = 0;
        $remaining      = $final;

        // محاسبه مبلغ کیف پول
        if ($use_wallet && $walletBal > 0) {
            $wallet_amount = min($walletBal, $final);
            $remaining     = $final - $wallet_amount;
        }

        if (empty($full_name)||empty($phone)||empty($city)||empty($address)||empty($postal_code)) {
            $error = 'تمام فیلدهای الزامی را پر کنید.';
        } elseif ($payment_method === 'card_transfer' && empty($receipt_number) && $remaining > 0) {
            $error = 'شماره پیگیری واریز الزامی است.';
        } else {
            try {
                $db->beginTransaction();

                foreach ($cartItems as $item) {
                    $s = $db->prepare("SELECT stock FROM products WHERE id=? FOR UPDATE");
                    $s->execute([$item['product_id']]);
                    if ($item['quantity'] > (int)$s->fetchColumn())
                        throw new Exception('موجودی «'.$item['name'].'» کافی نیست.');
                }

                $order_number   = generateOrderNumber();
                $payment_status = $remaining == 0 ? 'paid' : 'unpaid';

                $stmt = $db->prepare("INSERT INTO orders (user_id,order_number,total_amount,discount_amount,shipping_cost,tax_amount,final_amount,wallet_used,remaining_amount,shipping_address,shipping_city,shipping_postal_code,shipping_phone,payment_method,notes,status,payment_status,created_at,updated_at) VALUES (?,?,?,0,?,?,?,?,?,?,?,?,?,?,?,'pending',?,NOW(),NOW())");
                $stmt->execute([$_SESSION['user_id'],$order_number,$total,$shipping,$tax,$final,$wallet_amount,$remaining,$address,$city,$postal_code,$phone,$payment_method,$notes,$payment_status]);
                $order_id = $db->lastInsertId();

                foreach ($cartItems as $item) {
                    $db->prepare("INSERT INTO order_items (order_id,product_id,product_name,product_sku,quantity,price,subtotal) VALUES (?,?,?,?,?,?,?)")
                       ->execute([$order_id,$item['product_id'],$item['name'],$item['sku']??'',$item['quantity'],$item['final_price'],$item['subtotal']]);
                    $db->prepare("UPDATE products SET stock=stock-?,sales_count=sales_count+? WHERE id=?")
                       ->execute([$item['quantity'],$item['quantity'],$item['product_id']]);
                }

                // کسر از کیف پول
                if ($wallet_amount > 0) {
                    $db->prepare("UPDATE users SET wallet_balance=wallet_balance-? WHERE id=?")->execute([$wallet_amount,$_SESSION['user_id']]);
                    $newBal = $db->query("SELECT wallet_balance FROM users WHERE id=".$_SESSION['user_id'])->fetchColumn();
                    $db->prepare("INSERT INTO wallet_transactions (user_id,type,amount,balance_after,description,order_id,status,created_at) VALUES (?,'purchase',?,?,?,?,'success',NOW())")
                       ->execute([$_SESSION['user_id'],$wallet_amount,$newBal,'پرداخت سفارش '.$order_number,$order_id]);
                }

                $db->prepare("DELETE FROM cart WHERE user_id=?")->execute([$_SESSION['user_id']]);
                $db->commit();

                Auth::logActivity('order_create','سفارش: '.$order_number.' | کیف پول: '.number_format($wallet_amount).' | باقیمانده: '.number_format($remaining));

                // اعلان تلگرام
                try {
                    require_once 'config/telegram.php';
                    $telegram = new TelegramBot();
                    if ($telegram->isConfigured()) {
                        $telegram->sendOrderNotification([
                            'order_number' => $order_number,
                            'customer_name' => $full_name,
                            'shipping_phone' => $phone,
                            'final_amount' => $final,
                            'payment_method' => $payment_method,
                            'status' => 'pending'
                        ], $cartItems);
                    }
                } catch (Exception $e) { error_log("Telegram error: " . $e->getMessage()); }

                // اگه همه از کیف پول پرداخت شد
                if ($remaining == 0) {
                    $db->prepare("UPDATE orders SET status='processing' WHERE id=?")->execute([$order_id]);
                    header('Location: order-success.php?id='.$order_id.'&method=wallet'); exit;
                }

                // پرداخت باقیمانده آنلاین
                if ($payment_method === 'online') {
                    $merchantId  = $settings->get('zarinpal_merchant') ?: (defined('ZARINPAL_MERCHANT_ID')?ZARINPAL_MERCHANT_ID:'');
                    $callbackUrl = (isset($_SERVER['HTTPS'])?'https':'http').'://'.$_SERVER['HTTP_HOST'].'/payment/callback.php';
                    $zarinpal    = new ZarinPal($merchantId, $callbackUrl);
                    $result      = $zarinpal->request((int)$remaining,'پرداخت سفارش '.$order_number,$user['email'],$user['phone']??'');
                    if ($result['success']) {
                        $db->prepare("UPDATE orders SET authority=? WHERE id=?")->execute([$result['authority'],$order_id]);
                        header('Location: '.$result['url']); exit;
                    } else {
                        $db->prepare("UPDATE orders SET status='cancelled' WHERE id=?")->execute([$order_id]);
                        $error = 'خطا در درگاه: '.$result['error'];
                    }
                } else {
                    // کارت به کارت
                    if ($receipt_number) {
                        $db->prepare("UPDATE orders SET notes=CONCAT(IFNULL(notes,''),' | پیگیری: $receipt_number') WHERE id=?")->execute([$order_id]);
                    }
                    header('Location: order-success.php?id='.$order_id.'&method=card_transfer'); exit;
                }

            } catch (Exception $e) {
                if ($db->inTransaction()) $db->rollBack();
                $error = $e->getMessage();
            }
        }
    }
}

$csrfToken = Auth::generateCSRFToken();
include 'includes/header.php';
?>

<section class="checkout-page">
    <h1><i class="fas fa-shopping-cart"></i> تکمیل خرید</h1>

    <?php if($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?></div><?php endif; ?>

    <form method="POST" id="checkoutForm">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
        <input type="hidden" name="use_wallet" id="use_wallet_input" value="0">
        <div class="checkout-layout">
            <div class="checkout-info">

                <!-- اطلاعات -->
                <div class="checkout-section">
                    <h3><i class="fas fa-user"></i> اطلاعات تماس</h3>
                    <div class="form-row">
                        <div class="form-group"><label>نام <span class="req">*</span></label><input type="text" name="full_name" required value="<?= htmlspecialchars($user['full_name']) ?>"></div>
                        <div class="form-group"><label>موبایل <span class="req">*</span></label><input type="tel" name="phone" required value="<?= htmlspecialchars($user['phone']??'') ?>"></div>
                    </div>
                </div>

                <!-- آدرس -->
                <div class="checkout-section">
                    <h3><i class="fas fa-map-marker-alt"></i> آدرس ارسال</h3>
                    <div class="form-row">
                        <div class="form-group"><label>شهر <span class="req">*</span></label><input type="text" name="city" required></div>
                        <div class="form-group"><label>کد پستی <span class="req">*</span></label><input type="text" name="postal_code" required maxlength="10"></div>
                    </div>
                    <div class="form-group"><label>آدرس <span class="req">*</span></label><textarea name="address" rows="3" required></textarea></div>
                </div>

                <!-- کیف پول -->
                <?php if($walletBal > 0): ?>
                <div class="checkout-section wallet-section" id="walletSection">
                    <div class="wallet-header-row">
                        <div class="wallet-icon-wrap"><i class="fas fa-wallet"></i></div>
                        <div class="wallet-text">
                            <h4>کیف پول شما</h4>
                            <p>موجودی: <strong style="color:var(--primary);"><?= number_format($walletBal) ?> تومان</strong></p>
                        </div>
                        <label class="toggle-switch">
                            <input type="checkbox" id="walletToggle" onchange="toggleWallet(this)">
                            <span class="toggle-slider"></span>
                        </label>
                    </div>
                    <div id="walletDetail" style="display:none;margin-top:16px;">
                        <div class="wallet-calc">
                            <div class="wc-row">
                                <span>مبلغ کل سفارش</span>
                                <strong><?= number_format($final) ?> ت</strong>
                            </div>
                            <div class="wc-row" style="color:var(--primary);">
                                <span>کسر از کیف پول</span>
                                <strong>- <?= number_format(min($walletBal,$final)) ?> ت</strong>
                            </div>
                            <?php $remain = $final - min($walletBal,$final); ?>
                            <div class="wc-row total-row">
                                <span>باقیمانده برای پرداخت</span>
                                <strong style="font-size:1.2rem;color:<?= $remain==0?'var(--primary)':'inherit' ?>">
                                    <?= $remain == 0 ? '✓ رایگان!' : number_format($remain).' ت' ?>
                                </strong>
                            </div>
                            <?php if($remain == 0): ?>
                            <div class="wallet-free-badge"><i class="fas fa-gift"></i> موجودی کافی — نیازی به پرداخت اضافی نیست!</div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- روش پرداخت -->
                <div class="checkout-section" id="paymentSection">
                    <h3><i class="fas fa-credit-card"></i> روش پرداخت باقیمانده</h3>
                    <div class="payment-methods">
                        <label class="payment-option">
                            <input type="radio" name="payment_method" value="online" checked onchange="switchPay('online')">
                            <div class="payment-card">
                                <div class="payment-icon"><i class="fas fa-shield-alt" style="color:#8B5CF6;font-size:1.6rem;"></i></div>
                                <span>پرداخت آنلاین</span><small>زرین‌پال</small>
                            </div>
                        </label>
                        <label class="payment-option">
                            <input type="radio" name="payment_method" value="card_transfer" onchange="switchPay('card_transfer')">
                            <div class="payment-card">
                                <div class="payment-icon"><i class="fas fa-exchange-alt" style="color:#f59e0b;font-size:1.6rem;"></i></div>
                                <span>کارت به کارت</span><small>انتقال مستقیم</small>
                            </div>
                        </label>
                    </div>

                    <!-- اطلاعات کارت -->
                    <div id="panel-card_transfer" style="display:none;margin-top:16px;">
                        <div class="card-info-box">
                            <div class="card-info-header"><i class="fas fa-credit-card"></i> واریز به حساب زیر</div>
                            <div class="card-details">
                                <?php if($card_number): ?>
                                <div class="card-detail-row">
                                    <span class="card-label">شماره کارت:</span>
                                    <span class="card-value card-number-display" id="cardNum"><?= htmlspecialchars($card_number) ?></span>
                                    <button type="button" class="copy-btn" onclick="copyCard()"><i class="fas fa-copy"></i> کپی</button>
                                </div>
                                <?php endif; ?>
                                <?php if($card_owner): ?><div class="card-detail-row"><span class="card-label">به نام:</span><span class="card-value"><?= htmlspecialchars($card_owner) ?></span></div><?php endif; ?>
                                <?php if($card_bank):  ?><div class="card-detail-row"><span class="card-label">بانک:</span><span class="card-value"><?= htmlspecialchars($card_bank) ?></span></div><?php endif; ?>
                            </div>
                        </div>
                        <div class="receipt-form" style="margin-top:12px;">
                            <div class="form-group">
                                <label>شماره پیگیری واریز <span class="req">*</span></label>
                                <input type="text" name="receipt_number" id="receiptNum" placeholder="کد پیگیری بانکی" style="direction:ltr;">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- یادداشت -->
                <div class="checkout-section">
                    <h3><i class="fas fa-sticky-note"></i> یادداشت</h3>
                    <textarea name="notes" rows="3" placeholder="یادداشت اختیاری..."></textarea>
                </div>
            </div>

            <!-- خلاصه -->
            <div class="checkout-summary">
                <h3>خلاصه سفارش</h3>
                <div class="order-items">
                    <?php foreach($cartItems as $item): ?>
                    <div class="order-item">
                        <div class="order-item-info"><h4><?= htmlspecialchars($item['name']) ?></h4><p>× <?= $item['quantity'] ?></p></div>
                        <div class="order-item-price"><?= formatPrice($item['subtotal']) ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="summary-row"><span>جمع:</span><span><?= formatPrice($total) ?></span></div>
                <div class="summary-row"><span>ارسال:</span><span><?= formatPrice($shipping) ?></span></div>
                <div class="summary-row"><span>مالیات:</span><span><?= formatPrice($tax) ?></span></div>
                <div class="summary-row wallet-deduct" id="walletDeductRow" style="display:none;color:var(--primary);">
                    <span><i class="fas fa-wallet"></i> کیف پول:</span>
                    <span id="walletDeductAmt">- 0 ت</span>
                </div>
                <div class="summary-row total"><span>قابل پرداخت:</span><span class="total-price" id="finalPriceDisplay"><?= formatPrice($final) ?></span></div>
                <button type="submit" class="btn btn-primary btn-block btn-lg" id="submitBtn">
                    <i class="fas fa-lock"></i> <span id="submitText">پرداخت آنلاین</span>
                </button>
                <div class="secure-checkout"><i class="fas fa-shield-alt"></i> پرداخت امن</div>
            </div>
        </div>
    </form>
</section>

<style>
.checkout-page{padding:30px 4%;min-height:80vh;}
.checkout-page h1{margin-bottom:22px;font-size:1.7rem;display:flex;align-items:center;gap:10px;}
.checkout-layout{display:grid;grid-template-columns:1fr 360px;gap:20px;}
.checkout-info{display:flex;flex-direction:column;gap:14px;}
.checkout-section{background:var(--glass-bg-light);backdrop-filter:blur(20px);border:1px solid var(--glass-border);border-radius:16px;padding:20px;}
.checkout-section h3{margin-bottom:16px;font-size:1rem;display:flex;align-items:center;gap:8px;}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
.form-group{display:flex;flex-direction:column;gap:5px;}
.form-group label{font-size:0.82rem;font-weight:600;color:var(--text-secondary);}
.form-group input,.form-group textarea,.form-group select{padding:10px 14px;background:var(--glass-bg);border:1px solid var(--glass-border);border-radius:10px;font-family:inherit;font-size:0.9rem;color:var(--text-primary);transition:0.2s;}
.form-group input:focus,.form-group textarea:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px var(--primary-glow);}
.req{color:var(--danger);}

/* کیف پول */
.wallet-section{border:1px solid rgba(139,92,246,0.2);background:rgba(139,92,246,0.04);}
.wallet-header-row{display:flex;align-items:center;gap:14px;}
.wallet-icon-wrap{width:44px;height:44px;background:rgba(139,92,246,0.12);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:1.2rem;color:var(--primary);flex-shrink:0;}
.wallet-text{flex:1;}
.wallet-text h4{margin:0 0 3px;font-size:0.95rem;}
.wallet-text p{margin:0;font-size:0.82rem;color:var(--text-secondary);}
.toggle-switch{position:relative;width:50px;height:26px;flex-shrink:0;}
.toggle-switch input{display:none;}
.toggle-slider{position:absolute;inset:0;background:var(--glass-border);border-radius:26px;cursor:pointer;transition:0.3s;}
.toggle-slider:before{content:'';position:absolute;width:20px;height:20px;left:3px;top:3px;background:#fff;border-radius:50%;transition:0.3s;}
.toggle-switch input:checked+.toggle-slider{background:var(--primary);}
.toggle-switch input:checked+.toggle-slider:before{transform:translateX(24px);}
.wallet-calc{background:var(--glass-bg);border-radius:12px;padding:14px;border:1px solid var(--glass-border);}
.wc-row{display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px dashed var(--glass-border);font-size:0.88rem;}
.wc-row:last-child{border-bottom:none;}
.total-row{font-weight:700;font-size:0.95rem;}
.wallet-free-badge{margin-top:12px;background:rgba(139,92,246,0.12);border:1px solid rgba(139,92,246,0.3);border-radius:10px;padding:10px 14px;color:var(--primary);font-size:0.85rem;display:flex;align-items:center;gap:8px;font-weight:600;}

/* روش پرداخت */
.payment-methods{display:grid;grid-template-columns:1fr 1fr;gap:10px;}
.payment-option input{display:none;}
.payment-card{padding:14px;border:2px solid var(--glass-border);border-radius:12px;text-align:center;transition:0.2s;background:var(--glass-bg);cursor:pointer;}
.payment-card:hover{border-color:var(--primary);}
.payment-option input:checked+.payment-card{border-color:var(--primary);background:rgba(139,92,246,0.06);box-shadow:0 0 0 2px rgba(139,92,246,0.15);}
.payment-icon{margin-bottom:6px;min-height:32px;display:flex;align-items:center;justify-content:center;}
.payment-card span{display:block;font-weight:600;font-size:0.85rem;}
.payment-card small{display:block;color:var(--text-secondary);font-size:0.72rem;margin-top:3px;}

/* کارت به کارت */
.card-info-box{background:linear-gradient(135deg,#1e3a5f,#2d5a8e);border-radius:14px;padding:16px;color:#fff;}
.card-info-header{display:flex;align-items:center;gap:8px;font-size:0.9rem;font-weight:600;margin-bottom:12px;border-bottom:1px solid rgba(255,255,255,0.2);padding-bottom:10px;}
.card-details{display:flex;flex-direction:column;gap:8px;}
.card-detail-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
.card-label{font-size:0.78rem;opacity:0.8;min-width:75px;}
.card-value{font-weight:600;font-size:0.9rem;}
.card-number-display{letter-spacing:2px;font-family:monospace;font-size:1rem;background:rgba(255,255,255,0.15);padding:3px 8px;border-radius:5px;}
.copy-btn{background:rgba(255,255,255,0.2);border:1px solid rgba(255,255,255,0.3);color:#fff;padding:3px 8px;border-radius:5px;cursor:pointer;font-family:inherit;font-size:0.75rem;}
.receipt-form .form-group label{color:var(--text-secondary);}

/* خلاصه */
.checkout-summary{background:var(--glass-bg-light);border:1px solid var(--glass-border);border-radius:16px;padding:22px;height:fit-content;position:sticky;top:90px;}
.checkout-summary h3{margin-bottom:14px;}
.order-items{max-height:220px;overflow-y:auto;margin-bottom:12px;}
.order-item{display:flex;justify-content:space-between;padding:9px 0;border-bottom:1px solid var(--glass-border);}
.order-item-info h4{font-size:0.82rem;margin-bottom:2px;}
.order-item-info p{font-size:0.75rem;color:var(--text-secondary);}
.order-item-price{font-weight:600;font-size:0.85rem;white-space:nowrap;}
.summary-row{display:flex;justify-content:space-between;padding:8px 0;font-size:0.88rem;border-bottom:1px dashed var(--glass-border);}
.summary-row.total{font-size:1.1rem;font-weight:700;border-top:2px solid var(--glass-border);border-bottom:none;margin-top:6px;padding-top:10px;}
.total-price{color:var(--primary);}
.secure-checkout{text-align:center;padding:10px;background:rgba(139,92,246,0.06);border-radius:10px;margin-top:10px;color:var(--primary);display:flex;align-items:center;justify-content:center;gap:6px;font-size:0.8rem;}
@media(max-width:1024px){.checkout-layout{grid-template-columns:1fr;}.checkout-summary{position:static;}.form-row{grid-template-columns:1fr;}.payment-methods{grid-template-columns:1fr;}}
</style>

<script>
const finalTotal   = <?= $final ?>;
const walletBal    = <?= $walletBal ?>;
const walletUse    = Math.min(walletBal, finalTotal);
const remaining    = finalTotal - walletUse;

function toggleWallet(cb) {
    const using = cb.checked;
    document.getElementById('use_wallet_input').value = using ? '1' : '0';
    document.getElementById('walletDetail').style.display = using ? 'block' : 'none';

    const deductRow = document.getElementById('walletDeductRow');
    const deductAmt = document.getElementById('walletDeductAmt');
    const finalDisp = document.getElementById('finalPriceDisplay');
    const paySection = document.getElementById('paymentSection');
    const submitText = document.getElementById('submitText');

    if (using) {
        deductRow.style.display = 'flex';
        deductAmt.textContent   = '- ' + walletUse.toLocaleString('fa') + ' ت';
        finalDisp.textContent   = remaining.toLocaleString('fa') + ' تومان';

        if (remaining === 0) {
            paySection.style.display = 'none';
            submitText.textContent = '✓ پرداخت از کیف پول (رایگان)';
        } else {
            paySection.style.display = 'block';
            updateSubmitText();
        }
    } else {
        deductRow.style.display  = 'none';
        finalDisp.textContent    = finalTotal.toLocaleString('fa') + ' تومان';
        paySection.style.display = 'block';
        updateSubmitText();
    }
}

function switchPay(method) {
    document.getElementById('panel-card_transfer').style.display = method === 'card_transfer' ? 'block' : 'none';
    const rec = document.getElementById('receiptNum');
    if (rec) rec.required = method === 'card_transfer';
    updateSubmitText();
}

function updateSubmitText() {
    const using    = document.getElementById('walletToggle').checked;
    const method   = document.querySelector('input[name="payment_method"]:checked')?.value;
    const remain   = using ? remaining : finalTotal;
    if (remain === 0) { document.getElementById('submitText').textContent = '✓ پرداخت از کیف پول'; return; }
    const map = { online: 'پرداخت آنلاین — '+remain.toLocaleString('fa')+' ت', card_transfer: 'ثبت سفارش کارت‌به‌کارت' };
    document.getElementById('submitText').textContent = map[method] || 'ثبت سفارش';
}

function copyCard() {
    const num = document.getElementById('cardNum')?.textContent.replace(/\s/g,'');
    if (!num) return;
    navigator.clipboard.writeText(num).then(() => {
        const btn = document.querySelector('.copy-btn');
        btn.innerHTML = '<i class="fas fa-check"></i> کپی شد';
        setTimeout(() => btn.innerHTML = '<i class="fas fa-copy"></i> کپی', 2000);
    });
}

document.getElementById('checkoutForm').addEventListener('submit', function() {
    const btn = document.getElementById('submitBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> در حال پردازش...';
});

switchPay('online');
</script>

<?php include 'includes/footer.php'; ?>