<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('header.php');
$page_title  = WEB_NAME . " | Buy Gift Card";
$page_title2 = "Gift Cards";

$user_balance = (float)$user['main_balance'];

// ── Load settings ────────────────────────────���──────────────────────────────
try {
    $cfg = $pdo->query("SELECT reloadly_enabled, reloadly_ngn_rate, reloadly_markup FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $cfg = ['reloadly_enabled' => 0]; }

if (empty($cfg['reloadly_enabled'])) {
    echo '<div style="padding:40px;text-align:center;color:var(--text-muted)">Gift cards are currently unavailable. Please check back soon.</div>';
    include('footer.php'); exit;
}

$ngn_rate  = (float)($cfg['reloadly_ngn_rate'] ?? 1600);
$markup    = (float)($cfg['reloadly_markup'] ?? 10);

// ── Load product catalog from DB ────────────────────────────────────────────
try {
    $products_stmt = $pdo->query(
        "SELECT * FROM gift_card_products WHERE status = 1 ORDER BY country_name ASC, brand_name ASC"
    );
    $all_products  = $products_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $all_products = []; }

// Group by country
$by_country = [];
foreach ($all_products as $p) {
    $by_country[$p['country_name'] ?: $p['country_code']][] = $p;
}
$countries_raw = array_keys($by_country);

// Priority order
$priority = [
    'United States','United Kingdom','Germany','France','Italy','Spain',
    'Netherlands','Belgium','Austria','Portugal','Ireland','Finland',
    'Sweden','Denmark','Poland','Greece','Turkey','Switzerland','Norway','Czech Republic',
];

usort($countries_raw, function ($a, $b) use ($priority) {
    $posA = array_search($a, $priority);
    $posB = array_search($b, $priority);
    if ($posA !== false && $posB !== false) return $posA - $posB;
    if ($posA !== false) return -1;
    if ($posB !== false) return 1;
    return strcmp($a, $b);
});

$countries     = $countries_raw;
$first_country = $countries[0] ?? '';

$by_brand = [];
foreach ($all_products as $p) {
    $by_brand[$p['brand_name'] ?: $p['product_name']][] = $p;
}
?>
<title><?php echo htmlspecialchars($page_title); ?></title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}

.gc-hero {
    background: linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 35%,#4D148C 70%,#4D148C 100%);
    border: 1px solid rgba(245,158,11,.15);
    border-radius: 20px; padding: 20px;
    position: relative; overflow: hidden; margin-bottom: 16px;
}
.gc-hero::before {
    content:''; position:absolute; inset:0; pointer-events:none;
    background: repeating-linear-gradient(45deg,transparent,transparent 40px,rgba(77,20,140,.015) 40px,rgba(77,20,140,.015) 41px);
}

.gc-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:16px;padding:18px;margin-bottom:14px}

.product-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px;margin-top:14px}
.product-card{border:1.5px solid var(--card-border);border-radius:13px;padding:12px;cursor:pointer;transition:all .2s;background:var(--card-bg);text-align:center;position:relative;overflow:hidden}
.product-card:hover{border-color:rgba(77,20,140,.4);transform:translateY(-2px);box-shadow:0 6px 18px rgba(77,20,140,.12)}
.product-card.selected{border-color:#4D148C;background:rgba(77,20,140,.07);box-shadow:0 0 0 3px rgba(77,20,140,.12)}

/* ── FIX 1: centre the product image ── */
.product-card img{width:60px;height:40px;object-fit:contain;display:block;margin:0 auto 6px}

.denom-btn{padding:7px 14px;border-radius:9px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);font-weight:700;font-size:.78rem;cursor:pointer;transition:all .15s}
.denom-btn.active{background:rgba(77,20,140,.1);border-color:rgba(77,20,140,.4);color:#4D148C}
.denom-btn:hover:not(.active){border-color:rgba(77,20,140,.25)}

.country-tab{padding:7px 14px;border-radius:9px;font-size:.75rem;font-weight:700;cursor:pointer;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);transition:all .15s;white-space:nowrap}
.country-tab.active{background:rgba(77,20,140,.1);border-color:rgba(77,20,140,.35);color:#4D148C}
.country-tab:hover:not(.active){border-color:rgba(77,20,140,.25);color:var(--text-primary)}

.form-label{font-size:.78rem;font-weight:700;color:var(--text-primary);margin-bottom:6px;display:block}
.form-input{width:100%;padding:11px 14px;border-radius:11px;border:1.5px solid var(--card-border);background:var(--input-bg,var(--card-bg));color:var(--text-primary);font-size:.85rem;outline:none;transition:border-color .2s;box-sizing:border-box}
.form-input:focus{border-color:rgba(77,20,140,.5)}

.buy-btn{width:100%;padding:13px;border-radius:12px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:800;font-size:.9rem;border:none;cursor:pointer;transition:all .25s;display:flex;align-items:center;justify-content:center;gap:8px}
.buy-btn:hover{transform:translateY(-1px);box-shadow:0 6px 20px rgba(77,20,140,.35)}
.buy-btn:disabled{opacity:.6;cursor:not-allowed;transform:none;box-shadow:none}

.summary-row{display:flex;justify-content:space-between;align-items:center;padding:8px 0;border-bottom:1px solid var(--card-border);font-size:.8rem}
.summary-row:last-child{border-bottom:none}

.discount-badge{display:inline-block;padding:2px 8px;border-radius:99px;background:rgba(77,20,140,.1);color:#6b23c2;font-size:.62rem;font-weight:700;margin-left:6px}
.no-products{text-align:center;padding:40px 20px;color:var(--text-muted);font-size:.85rem}
</style>

<div class="max-w-2xl mx-auto">

<!-- Hero -->
<div class="gc-hero anim anim-1">
    <div style="position:absolute;width:160px;height:160px;border-radius:50%;filter:blur(55px);background:radial-gradient(circle,rgba(77,20,140,.3),transparent);top:-40px;right:-40px;pointer-events:none"></div>
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:14px">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;margin-bottom:4px;display:flex;align-items:center;gap:8px">
                <i class="fas fa-gift" style="color:#c4b5fd"></i>Gift Cards
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">Amazon, iTunes, Google Play, Netflix &amp; more — delivered instantly to email.</p>
        </div>
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
            <div style="background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.15);border-radius:10px;padding:10px 16px;text-align:center">
                <p style="font-size:.6rem;color:rgba(255,255,255,.55);font-weight:700;text-transform:uppercase;letter-spacing:.06em">Balance</p>
                <p style="font-weight:800;color:white;font-size:.95rem;font-family:monospace">₦<?php echo number_format($user_balance, 2); ?></p>
            </div>
            <a href="fund-wallet" style="background:white;color:#4D148C;font-weight:700;font-size:.78rem;padding:10px 16px;border-radius:10px;text-decoration:none;display:inline-flex;align-items:center;gap:6px">
                <i class="fas fa-plus" style="font-size:.7rem"></i>Add Funds
            </a>
        </div>
    </div>
</div>

<?php if (empty($all_products)): ?>
<div class="gc-card anim anim-1" style="text-align:center;padding:40px">
    <i class="fas fa-gift" style="font-size:2.5rem;color:rgba(77,20,140,.3);margin-bottom:14px;display:block"></i>
    <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:6px">No Gift Cards Available Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto">The catalog is being loaded. Please check back shortly or contact support.</p>
</div>
<?php else: ?>

<!-- Country Tabs -->
<div class="anim anim-1" style="display:flex;gap:8px;overflow-x:auto;padding-bottom:4px;margin-bottom:14px;-webkit-overflow-scrolling:touch">
    <?php foreach ($countries as $i => $country): ?>
    <button class="country-tab <?php echo $i === 0 ? 'active' : ''; ?>" data-country="<?php echo htmlspecialchars($country); ?>">
        <?php echo htmlspecialchars($country); ?>
    </button>
    <?php endforeach; ?>
</div>

<!-- Product Selection -->
<div class="gc-card anim anim-2">
    <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:4px;display:flex;align-items:center;gap:8px">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(77,20,140,.1);display:inline-flex;align-items:center;justify-content:center">
            <i class="fas fa-gift" style="font-size:.72rem;color:#4D148C"></i>
        </span>
        Select a Gift Card
    </h3>
    <p style="font-size:.72rem;color:var(--text-muted);margin-bottom:14px">Codes are emailed instantly after payment.</p>

    <!-- Search -->
    <div style="margin-bottom:12px">
        <input type="text" id="productSearch" class="form-input" placeholder="Search brand (e.g. Amazon, Netflix)…" oninput="filterProducts()">
    </div>

    <!-- Product grids per country -->
    <?php foreach ($by_country as $country => $prods): ?>
    <div class="product-grid" id="country_<?php echo htmlspecialchars($country); ?>"
         style="display:<?php echo $country === $first_country ? 'grid' : 'none'; ?>">
        <?php foreach ($prods as $p):
            $denoms = $p['denominations'] ? json_decode($p['denominations'], true) : [];
            $has_discount = $p['discount_percent'] > 0;
        ?>
        <div class="product-card"
             data-id="<?php echo (int)$p['product_id']; ?>"
             data-name="<?php echo htmlspecialchars($p['product_name'], ENT_QUOTES); ?>"
             data-brand="<?php echo htmlspecialchars($p['brand_name'] ?? $p['product_name'], ENT_QUOTES); ?>"
             data-currency="<?php echo htmlspecialchars($p['currency_code'], ENT_QUOTES); ?>"
             data-country="<?php echo htmlspecialchars($p['country_code'], ENT_QUOTES); ?>"
             data-rate="<?php echo (float)$p['ngn_sell_rate']; ?>"
             data-markup="<?php echo (float)$p['markup_percent']; ?>"
             data-discount="<?php echo (float)$p['discount_percent']; ?>"
             data-denoms="<?php echo htmlspecialchars($p['denominations'] ?? '[]', ENT_QUOTES); ?>"
             data-isrange="<?php echo (int)$p['is_range']; ?>"
             data-min="<?php echo (float)$p['min_amount']; ?>"
             data-max="<?php echo (float)$p['max_amount']; ?>">
            <?php if ($p['image_url']): ?>
            <img src="<?php echo htmlspecialchars($p['image_url']); ?>"
                 alt="<?php echo htmlspecialchars($p['brand_name'] ?? $p['product_name']); ?>"
                 loading="lazy" onerror="this.style.display='none'">
            <?php else: ?>
            <div style="width:60px;height:40px;border-radius:8px;background:rgba(77,20,140,.08);display:flex;align-items:center;justify-content:center;margin:0 auto 6px">
                <i class="fas fa-gift" style="color:#4D148C;font-size:.9rem"></i>
            </div>
            <?php endif; ?>
            <p style="font-weight:700;font-size:.75rem;color:var(--text-primary);line-height:1.3;margin-bottom:2px"><?php echo htmlspecialchars($p['brand_name'] ?? $p['product_name']); ?></p>
            <p style="font-size:.62rem;color:var(--text-muted)"><?php echo htmlspecialchars($p['currency_code']); ?></p>
            <?php if ($has_discount): ?>
            <span class="discount-badge"><?php echo number_format($p['discount_percent'], 1); ?>% off</span>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endforeach; ?>
</div>

<!-- Order Details -->
<div class="gc-card anim anim-2" id="orderSection" style="display:none">
    <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);margin-bottom:16px;display:flex;align-items:center;gap:8px">
        <span style="width:28px;height:28px;border-radius:8px;background:rgba(77,20,140,.1);display:inline-flex;align-items:center;justify-content:center">
            <i class="fas fa-pen-to-square" style="font-size:.72rem;color:#4D148C"></i>
        </span>
        <span id="selectedProductTitle">Order Details</span>
    </h3>

    <!-- Denominations (fixed) -->
    <div id="denomSection" style="display:none;margin-bottom:16px">
        <label class="form-label">Select Amount (<span id="denom_currency"></span>)</label>
        <div id="denomBtns" style="display:flex;flex-wrap:wrap;gap:8px;margin-top:6px"></div>
    </div>

    <!-- Range amount (open) -->
    <div id="rangeSection" style="display:none;margin-bottom:16px">
        <label class="form-label" for="rangeAmount">Enter Amount (<span id="range_currency"></span>) <span id="range_limits" style="font-weight:400;color:var(--text-muted)"></span></label>
        <input type="number" id="rangeAmount" class="form-input" placeholder="e.g. 10" min="1" step="0.01" oninput="updateRangeSummary()">
    </div>

    <!-- Recipient email -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="recipientEmail">Recipient Email</label>
        <input type="email" id="recipientEmail" class="form-input" placeholder="email@example.com" oninput="updateSummary()">
        <p style="font-size:.68rem;color:var(--text-muted);margin-top:4px"><i class="fas fa-circle-info" style="font-size:.7rem"></i> The gift card code will be sent to this email address.</p>
    </div>

    <!-- Sender name -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="senderName">Your Name (shown on gift card)</label>
        <input type="text" id="senderName" class="form-input" placeholder="e.g. John Doe" value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>" oninput="updateSummary()">
    </div>

    <!-- Summary -->
    <div id="summaryBox" style="display:none;background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.15);border-radius:13px;padding:14px;margin-bottom:16px">
        <p style="font-size:.75rem;font-weight:700;color:#4D148C;margin-bottom:10px;display:flex;align-items:center;gap:6px">
            <i class="fas fa-receipt"></i> Order Summary
        </p>
        <div class="summary-row"><span style="color:var(--text-muted)">Product</span><span id="sum_product" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Amount</span><span id="sum_amount" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <!-- FIX 2: NGN Rate row removed -->
        <div class="summary-row"><span style="color:var(--text-muted)">You Pay</span><span id="sum_pay" style="font-weight:800;color:#4D148C;font-family:monospace">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Balance After</span><span id="sum_balance_after" style="font-weight:700;font-family:monospace;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Delivery</span><span style="color:#6b23c2;font-weight:600"><i class="fas fa-bolt" style="font-size:.7rem"></i> Instant (Email)</span></div>
    </div>

    <!-- Hidden inputs -->
    <input type="hidden" id="hProductId"   value="">
    <input type="hidden" id="hCountryCode" value="">
    <input type="hidden" id="hCurrency"    value="">
    <input type="hidden" id="hUnitPrice"   value="">
    <input type="hidden" id="hRate"        value="">
    <input type="hidden" id="hNgnCharge"   value="">

    <button class="buy-btn" id="buyBtn" disabled>
        <i class="fas fa-credit-card"></i> <span id="buyBtnText">Buy Gift Card</span>
    </button>
    <p style="text-align:center;font-size:.7rem;color:var(--text-muted);margin-top:10px">
        <i class="fas fa-shield-halved" style="font-size:.7rem"></i>
        Secured by Softbillshub &middot; Instant delivery &middot; Non-refundable
    </p>
</div>

<!-- History shortcut -->
<div class="anim anim-3" style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:13px;padding:14px;margin-bottom:16px;display:flex;gap:12px;align-items:center">
    <div style="width:36px;height:36px;border-radius:10px;background:rgba(77,20,140,.08);border:1px solid rgba(77,20,140,.15);display:flex;align-items:center;justify-content:center;flex-shrink:0">
        <i class="fas fa-clock-rotate-left" style="color:#4D148C;font-size:.85rem"></i>
    </div>
    <div style="flex:1">
        <p style="font-weight:700;font-size:.8rem;color:var(--text-primary);margin-bottom:2px">Order History</p>
        <p style="font-size:.72rem;color:var(--text-muted)">View all your previous gift card purchases.</p>
    </div>
    <a href="giftcard-orders" style="font-weight:700;font-size:.75rem;color:#4D148C;text-decoration:none;white-space:nowrap">View All →</a>
</div>

<?php endif; ?>
</div><!-- /max-w -->

<!-- Confirm Modal -->
<div id="confirmModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);z-index:9999;align-items:center;justify-content:center;padding:16px">
    <div style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:20px;padding:24px;max-width:380px;width:100%">
        <div style="text-align:center;margin-bottom:20px">
            <div style="width:56px;height:56px;border-radius:50%;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;margin:0 auto 12px">
                <i class="fas fa-gift" style="font-size:1.3rem;color:#4D148C"></i>
            </div>
            <h3 style="font-weight:800;font-size:1rem;color:var(--text-primary);margin-bottom:4px">Confirm Purchase</h3>
            <p style="font-size:.78rem;color:var(--text-muted)">Please review your order before proceeding.</p>
        </div>
        <div id="modalSummary" style="background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.15);border-radius:12px;padding:14px;margin-bottom:20px;font-size:.8rem"></div>
        <div style="display:flex;gap:10px">
            <button id="cancelBtn" style="flex:1;padding:11px;border-radius:10px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);font-weight:700;cursor:pointer">Cancel</button>
            <button id="confirmBtn" style="flex:2;padding:11px;border-radius:10px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:800;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px">
                <i class="fas fa-check"></i> Pay &amp; Get Code
            </button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function() {
    'use strict';
    var userBalance     = <?php echo json_encode($user_balance); ?>;
    var selectedProduct = null;
    var selectedDenom   = null;

    // ── Country tabs ──────────────────────────────────────────────
    document.querySelectorAll('.country-tab').forEach(function(btn) {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.country-tab').forEach(function(b){ b.classList.remove('active'); });
            this.classList.add('active');
            document.querySelectorAll('[id^="country_"]').forEach(function(el){ el.style.display = 'none'; });
            var grid = document.getElementById('country_' + this.dataset.country);
            if (grid) grid.style.display = 'grid';
            clearSelection();
        });
    });

    // ── Product search ────────────────────────────────────────────
    window.filterProducts = function() {
        var q = document.getElementById('productSearch').value.trim().toLowerCase();
        document.querySelectorAll('.product-card').forEach(function(card) {
            var name = (card.dataset.brand + ' ' + card.dataset.name).toLowerCase();
            card.style.display = (!q || name.includes(q)) ? 'block' : 'none';
        });
        clearSelection();
    };

    // ── Product card selection ────────────────────────────────────
    document.querySelectorAll('.product-card').forEach(function(card) {
        card.addEventListener('click', function() {
            document.querySelectorAll('.product-card').forEach(function(c){ c.classList.remove('selected'); });
            this.classList.add('selected');

            selectedProduct = {
                id:       parseInt(this.dataset.id),
                name:     this.dataset.name,
                brand:    this.dataset.brand,
                currency: this.dataset.currency,
                country:  this.dataset.country,
                rate:     parseFloat(this.dataset.rate),
                markup:   parseFloat(this.dataset.markup),
                discount: parseFloat(this.dataset.discount),
                denoms:   JSON.parse(this.dataset.denoms || '[]'),
                isRange:  parseInt(this.dataset.isrange),
                min:      parseFloat(this.dataset.min || 0),
                max:      parseFloat(this.dataset.max || 0),
            };
            selectedDenom = null;
            document.getElementById('hProductId').value   = selectedProduct.id;
            document.getElementById('hCountryCode').value = selectedProduct.country;
            document.getElementById('hCurrency').value    = selectedProduct.currency;

            renderProductDetails();
        });
    });

    function renderProductDetails() {
        var p = selectedProduct;
        document.getElementById('selectedProductTitle').textContent = p.brand || p.name;
        document.getElementById('orderSection').style.display = 'block';
        document.getElementById('summaryBox').style.display   = 'none';
        document.getElementById('buyBtn').disabled            = true;
        document.getElementById('buyBtnText').textContent     = 'Buy Gift Card';

        if (p.isRange) {
            document.getElementById('denomSection').style.display  = 'none';
            document.getElementById('rangeSection').style.display  = 'block';
            document.getElementById('range_currency').textContent  = p.currency;
            document.getElementById('range_limits').textContent    = p.min && p.max ? '('+p.min+' – '+p.max+' '+p.currency+')' : '';
            document.getElementById('rangeAmount').value           = '';
        } else {
            document.getElementById('denomSection').style.display  = 'block';
            document.getElementById('rangeSection').style.display  = 'none';
            document.getElementById('denom_currency').textContent  = p.currency;
            renderDenoms(p.denoms);
        }
        document.getElementById('orderSection').scrollIntoView({ behavior:'smooth', block:'nearest' });
    }

    function renderDenoms(denoms) {
        var container = document.getElementById('denomBtns');
        container.innerHTML = '';
        (denoms || []).forEach(function(d) {
            var btn = document.createElement('button');
            btn.className      = 'denom-btn';
            btn.textContent    = selectedProduct.currency + ' ' + parseFloat(d).toLocaleString();
            btn.dataset.amount = d;
            btn.addEventListener('click', function() {
                document.querySelectorAll('.denom-btn').forEach(function(b){ b.classList.remove('active'); });
                this.classList.add('active');
                selectedDenom = parseFloat(this.dataset.amount);
                document.getElementById('hUnitPrice').value = selectedDenom;
                computeAndShowSummary(selectedDenom);
            });
            container.appendChild(btn);
        });
    }

    window.updateRangeSummary = function() {
        var val = parseFloat(document.getElementById('rangeAmount').value);
        if (isNaN(val) || val <= 0) {
            document.getElementById('summaryBox').style.display = 'none';
            document.getElementById('buyBtn').disabled = true;
            return;
        }
        selectedDenom = val;
        document.getElementById('hUnitPrice').value = val;
        computeAndShowSummary(val);
    };

    function computeAndShowSummary(faceValue) {
        var p        = selectedProduct;
        var cost_ngn = faceValue * p.rate * (1 + p.markup / 100);
        var after    = userBalance - cost_ngn;

        document.getElementById('hRate').value      = p.rate;
        document.getElementById('hNgnCharge').value = cost_ngn.toFixed(2);

        document.getElementById('sum_product').textContent       = p.brand || p.name;
        document.getElementById('sum_amount').textContent        = faceValue.toLocaleString() + ' ' + p.currency;
        // FIX 2: sum_rate element removed from HTML, so no update needed here
        document.getElementById('sum_pay').textContent           = '₦' + cost_ngn.toLocaleString('en-NG', {minimumFractionDigits:2, maximumFractionDigits:2});
        document.getElementById('sum_balance_after').textContent = after >= 0
            ? '₦' + after.toLocaleString('en-NG', {minimumFractionDigits:2})
            : '⚠ Insufficient balance';

        document.getElementById('summaryBox').style.display = 'block';
        updateSummary();
    }

    window.updateSummary = function() {
        var email  = (document.getElementById('recipientEmail').value || '').trim();
        var name   = (document.getElementById('senderName').value    || '').trim();
        var charge = parseFloat(document.getElementById('hNgnCharge').value || 0);
        var ok     = email.includes('@') && name.length > 1 && charge > 0 && userBalance >= charge;
        var btn    = document.getElementById('buyBtn');
        btn.disabled = !ok;
        if (ok && selectedDenom) {
            document.getElementById('buyBtnText').textContent =
                'Buy ' + selectedProduct.currency + ' ' + selectedDenom.toLocaleString() + ' — ₦' +
                charge.toLocaleString('en-NG', {minimumFractionDigits:2, maximumFractionDigits:2});
        } else {
            document.getElementById('buyBtnText').textContent = 'Buy Gift Card';
        }
    };

    function clearSelection() {
        selectedProduct = null;
        selectedDenom   = null;
        document.querySelectorAll('.product-card').forEach(function(c){ c.classList.remove('selected'); });
        document.getElementById('orderSection').style.display = 'none';
    }

    // ── Buy button → modal ────────────────────────────────────────
    document.getElementById('buyBtn').addEventListener('click', function() {
        var email  = document.getElementById('recipientEmail').value.trim();
        var name   = document.getElementById('senderName').value.trim();
        var charge = parseFloat(document.getElementById('hNgnCharge').value || 0);
        if (!selectedProduct || !selectedDenom) { showAlert('Please select a product and denomination.', 'error'); return; }
        if (!email.includes('@'))               { showAlert('Please enter a valid recipient email.', 'error'); return; }
        if (name.length < 2)                    { showAlert('Please enter your name.', 'error'); return; }
        if (userBalance < charge)               { showAlert('Insufficient wallet balance. Please fund your wallet.', 'error'); return; }

        document.getElementById('modalSummary').innerHTML =
            '<div style="display:flex;flex-direction:column;gap:8px">' +
            row('Product',   (selectedProduct.brand || selectedProduct.name)) +
            row('Amount',    selectedDenom + ' ' + selectedProduct.currency) +
            row('Recipient', email) +
            row('You Pay',   '₦' + charge.toLocaleString('en-NG',{minimumFractionDigits:2,maximumFractionDigits:2}), '#4D148C') +
            '</div>';
        document.getElementById('confirmModal').style.display = 'flex';
    });

    function row(label, val, col) {
        return '<div style="display:flex;justify-content:space-between"><span style="color:var(--text-muted)">'+ label +'</span><strong'+(col?' style="color:'+col+'"':'')+'>'+val+'</strong></div>';
    }

    document.getElementById('cancelBtn').addEventListener('click', function() {
        document.getElementById('confirmModal').style.display = 'none';
    });

    // ── Confirm purchase ──────────────────────────────────────────
    document.getElementById('confirmBtn').addEventListener('click', function() {
        var btn = this;
        btn.disabled  = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing…';

        $.post('ajax/giftcard-handler.php', {
            action:          'buy_giftcard',
            product_id:      document.getElementById('hProductId').value,
            country_code:    document.getElementById('hCountryCode').value,
            currency:        document.getElementById('hCurrency').value,
            unit_price:      document.getElementById('hUnitPrice').value,
            ngn_rate:        document.getElementById('hRate').value,
            ngn_charge:      document.getElementById('hNgnCharge').value,
            recipient_email: document.getElementById('recipientEmail').value.trim(),
            sender_name:     document.getElementById('senderName').value.trim(),
        }, function(res) {
            document.getElementById('confirmModal').style.display = 'none';
            if (res.status === '1') {
                Swal.fire({
                    title: '🎉 Gift Card Purchased!',
                    html:  '<p style="font-size:.85rem">Your gift card code has been sent to <strong>' +
                           document.getElementById('recipientEmail').value.trim() + '</strong>.<br><br>' +
                           (res.card_number ? 'Card Code: <strong style="font-family:monospace">' + res.card_number + '</strong><br>' : '') +
                           (res.card_pin    ? 'PIN: <strong style="font-family:monospace">' + res.card_pin + '</strong>' : '') + '</p>',
                    icon:  'success',
                    confirmButtonColor: '#4D148C',
                    confirmButtonText:  'View Orders',
                }).then(function(){ window.location.href = 'giftcard-orders'; });
            } else {
                showAlert(res.msg || 'Purchase failed. Please try again.', 'error');
                btn.disabled  = false;
                btn.innerHTML = '<i class="fas fa-check"></i> Pay &amp; Get Code';
            }
        }, 'json').fail(function() {
            document.getElementById('confirmModal').style.display = 'none';
            showAlert('Network error. Please try again.', 'error');
            btn.disabled  = false;
            btn.innerHTML = '<i class="fas fa-check"></i> Pay &amp; Get Code';
        });
    });

    function showAlert(msg, type) {
        var el = document.createElement('div');
        el.style.cssText = 'position:fixed;top:20px;left:50%;transform:translateX(-50%);z-index:99999;padding:12px 20px;border-radius:12px;font-size:.82rem;font-weight:700;color:white;background:' + (type==='success'?'#4D148C':'#ef4444') + ';box-shadow:0 4px 16px rgba(0,0,0,.2);max-width:90vw;text-align:center';
        el.textContent = msg;
        document.body.appendChild(el);
        setTimeout(function(){ el.remove(); }, 3500);
    }
})();
</script>

<?php include('footer.php'); ?>