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

// Load active sell types
try {
    $types = $pdo->query("SELECT * FROM sell_giftcard_types WHERE status = 1 ORDER BY name ASC")
                 ->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $types = []; }
?>
<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}

.sell-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;
}
.sell-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}

.type-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;margin-top:12px}
.type-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}
.type-card:hover{border-color:rgba(77,20,140,.4);transform:translateY(-2px);box-shadow:0 6px 18px rgba(77,20,140,.12)}
.type-card.selected{border-color:#4D148C;background:rgba(77,20,140,.07);box-shadow:0 0 0 3px rgba(77,20,140,.12)}
.type-card img{width:56px;height:38px;object-fit:contain;display:block;margin:0 auto 6px}

.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)}
.form-textarea{resize:vertical;min-height:80px}

.sell-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}
.sell-btn:hover{transform:translateY(-1px);box-shadow:0 6px 20px rgba(77,20,140,.35)}
.sell-btn:disabled{opacity:.6;cursor:not-allowed;transform:none;box-shadow:none}

.payout-preview{background:rgba(77,20,140,.06);border:1px solid rgba(77,20,140,.2);
                border-radius:13px;padding:14px;margin-bottom:16px}
.summary-row{display:flex;justify-content:space-between;align-items:center;
             padding:7px 0;border-bottom:1px solid var(--card-border);font-size:.8rem}
.summary-row:last-child{border-bottom:none}

/* File upload */
.upload-zone{border:2px dashed var(--card-border);border-radius:12px;padding:24px;text-align:center;
             cursor:pointer;transition:all .2s;position:relative}
.upload-zone:hover,.upload-zone.drag-over{border-color:rgba(77,20,140,.5);background:rgba(77,20,140,.03)}
.upload-zone input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.upload-preview{max-width:100%;max-height:180px;border-radius:10px;object-fit:contain;display:none;margin:10px auto 0}
</style>

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

<!-- Hero -->
<div class="sell-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-tags" style="color:#c4b5fd"></i>Sell Gift Card
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">Upload your gift card — get paid in NGN instantly to your bank.</p>
        </div>
        <a href="sell-giftcard-orders" 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-clock-rotate-left" style="font-size:.7rem"></i>My Sales
        </a>
    </div>
</div>

<?php if (empty($types)): ?>
<div class="gc-card anim anim-1" style="text-align:center;padding:40px">
    <i class="fas fa-tags" 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 Accepted Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto">We are not accepting any gift cards right now. Please check back shortly.</p>
</div>
<?php else: ?>

<!-- Step 1: Select Gift Card Type -->
<div class="gc-card anim anim-1">
    <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>
        Step 1 — Select Gift Card Type
    </h3>
    <p style="font-size:.72rem;color:var(--text-muted);margin-bottom:4px">Choose the type of gift card you want to sell.</p>

    <!-- Search -->
    <div style="margin-bottom:12px;margin-top:12px">
        <input type="text" id="typeSearch" class="form-input" placeholder="Search gift card (e.g. Amazon, iTunes)…" oninput="filterTypes()">
    </div>

    <div class="type-grid" id="typeGrid">
        <?php foreach ($types as $t): ?>
        <div class="type-card"
             data-id="<?php echo (int)$t['id']; ?>"
             data-name="<?php echo htmlspecialchars($t['name'], ENT_QUOTES); ?>"
             data-rate="<?php echo (float)$t['ngn_rate']; ?>"
             data-min="<?php echo (float)$t['min_usd']; ?>"
             data-max="<?php echo (float)$t['max_usd']; ?>"
             data-currency="<?php echo htmlspecialchars($t['currency'], ENT_QUOTES); ?>">
            <?php if ($t['image_url']): ?>
            <img src="<?php echo htmlspecialchars($t['image_url']); ?>"
                 alt="<?php echo htmlspecialchars($t['name']); ?>"
                 loading="lazy" onerror="this.style.display='none'">
            <?php else: ?>
            <div style="width:56px;height:38px;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:.73rem;color:var(--text-primary);line-height:1.3;margin-bottom:2px"><?php echo htmlspecialchars($t['name']); ?></p>
            <p style="font-size:.62rem;color:#4D148C;font-weight:600">₦<?php echo number_format($t['ngn_rate'], 0); ?>/<?php echo htmlspecialchars($t['currency']); ?></p>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Step 2: Card & Payout Details -->
<div class="gc-card anim anim-2" id="detailsSection" 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>
        Step 2 — Card & Payment Details
        <span id="selectedTypeName" style="font-size:.75rem;color:#4D148C;font-weight:600"></span>
    </h3>

    <!-- Card Value -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="usdAmount">
            Gift Card Amount / Value (<span id="lbl_currency">USD</span>)
            <span id="lbl_range" style="font-weight:400;color:var(--text-muted)"></span>
        </label>
        <input type="number" id="usdAmount" class="form-input" placeholder="e.g. 50" min="0" step="0.01" oninput="calcPayout()">
    </div>

    <!-- Payout Preview -->
    <div class="payout-preview" id="payoutBox" style="display:none">
        <p style="font-size:.75rem;font-weight:700;color:#4D148C;margin-bottom:10px;display:flex;align-items:center;gap:6px">
            <i class="fas fa-calculator"></i> Payout Preview
        </p>
        <div class="summary-row"><span style="color:var(--text-muted)">Card Type</span><span id="sum_type" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Card Value</span><span id="sum_value" style="font-weight:700;color:var(--text-primary)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">Rate</span><span id="sum_rate" style="font-weight:600;color:var(--text-muted)">—</span></div>
        <div class="summary-row"><span style="color:var(--text-muted)">You Receive (NGN)</span><span id="sum_payout" style="font-weight:800;color:#4D148C;font-family:monospace;font-size:.95rem">—</span></div>
    </div>

    <!-- Card Code / PIN -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="cardCode">Card Code / Redemption Code</label>
        <input type="text" id="cardCode" class="form-input" placeholder="Enter the gift card code">
    </div>
    <div style="margin-bottom:14px">
        <label class="form-label" for="cardPin">Card PIN <span style="font-weight:400;color:var(--text-muted)">(if applicable)</span></label>
        <input type="text" id="cardPin" class="form-input" placeholder="Leave blank if no PIN">
    </div>

    <!-- Snapshot Upload -->
    <div style="margin-bottom:14px">
        <label class="form-label">Gift Card Snapshot / Photo <span style="color:#ef4444">*</span></label>
        <div class="upload-zone" id="uploadZone">
            <input type="file" id="cardImage" accept="image/*" onchange="previewImage(this)">
            <div id="uploadPlaceholder">
                <i class="fas fa-cloud-upload-alt" style="font-size:1.5rem;color:rgba(77,20,140,.4);margin-bottom:8px;display:block"></i>
                <p style="font-size:.8rem;font-weight:600;color:var(--text-muted)">Click or drag to upload a clear photo of the gift card</p>
                <p style="font-size:.7rem;color:var(--text-muted)">JPG, PNG — max 5MB</p>
            </div>
            <img id="imagePreview" class="upload-preview" alt="Preview">
        </div>
    </div>

    <!-- Phone -->
    <div style="margin-bottom:14px">
        <label class="form-label" for="userPhone">Your Phone Number</label>
        <input type="tel" id="userPhone" class="form-input" placeholder="e.g. 08012345678" maxlength="11">
    </div>

    <!-- Payment Details -->
    <div style="background:rgba(77,20,140,.04);border:1px solid rgba(77,20,140,.12);border-radius:13px;padding:14px;margin-bottom:16px">
        <p style="font-size:.75rem;font-weight:700;color:#4D148C;margin-bottom:12px;display:flex;align-items:center;gap:6px">
            <i class="fas fa-building-columns"></i> Bank Account for Payment
        </p>
        <div style="margin-bottom:12px">
            <label class="form-label" for="bankName">Bank Name</label>
            <input type="text" id="bankName" class="form-input" placeholder="e.g. GTBank, Access Bank, Opay">
        </div>
        <div style="margin-bottom:12px">
            <label class="form-label" for="accountNumber">Account Number</label>
            <input type="text" id="accountNumber" class="form-input" placeholder="10-digit account number" maxlength="12">
        </div>
        <div>
            <label class="form-label" for="accountName">Account Name</label>
            <input type="text" id="accountName" class="form-input" placeholder="Full name on the account">
        </div>
    </div>

    <!-- Hidden -->
    <input type="hidden" id="hTypeId" value="">
    <input type="hidden" id="hTypeName" value="">
    <input type="hidden" id="hNgnRate" value="">
    <input type="hidden" id="hNgnPayout" value="">
    <input type="hidden" id="hCurrency" value="">

    <button class="sell-btn" id="sellBtn" disabled>
        <i class="fas fa-paper-plane"></i> <span id="sellBtnText">Submit for Review</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>
        Payment is processed within 5 - 30 Minutes after card verification.
    </p>
</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-tags" 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 Submission</h3>
            <p style="font-size:.78rem;color:var(--text-muted)">Please review your gift card details before submitting.</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-paper-plane"></i> Submit
            </button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function () {
    'use strict';
    var sel = null; // selected type

    // ── Type card selection ──────────────────────────────────────
    document.querySelectorAll('.type-card').forEach(function (c) {
        c.addEventListener('click', function () {
            document.querySelectorAll('.type-card').forEach(function (x) { x.classList.remove('selected'); });
            this.classList.add('selected');
            sel = {
                id:       parseInt(this.dataset.id),
                name:     this.dataset.name,
                rate:     parseFloat(this.dataset.rate),
                min:      parseFloat(this.dataset.min),
                max:      parseFloat(this.dataset.max),
                currency: this.dataset.currency
            };
            document.getElementById('hTypeId').value   = sel.id;
            document.getElementById('hTypeName').value  = sel.name;
            document.getElementById('hNgnRate').value   = sel.rate;
            document.getElementById('hCurrency').value  = sel.currency;
            document.getElementById('selectedTypeName').textContent = '— ' + sel.name;
            document.getElementById('lbl_currency').textContent = sel.currency;
            document.getElementById('lbl_range').textContent =
                sel.min && sel.max ? '(' + sel.min + ' – ' + sel.max + ' ' + sel.currency + ')' : '';
            document.getElementById('detailsSection').style.display = 'block';
            document.getElementById('usdAmount').value = '';
            document.getElementById('payoutBox').style.display = 'none';
            document.getElementById('sellBtn').disabled = true;
            document.getElementById('detailsSection').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        });
    });

    // ── Search types ─────────────────────────────────────────────
    window.filterTypes = function () {
        var q = document.getElementById('typeSearch').value.trim().toLowerCase();
        document.querySelectorAll('.type-card').forEach(function (c) {
            c.style.display = (!q || c.dataset.name.toLowerCase().includes(q)) ? 'block' : 'none';
        });
    };

    // ── Calc payout ───────────────────────────────────────────────
    window.calcPayout = function () {
        if (!sel) return;
        var val = parseFloat(document.getElementById('usdAmount').value);
        if (isNaN(val) || val <= 0) {
            document.getElementById('payoutBox').style.display = 'none';
            validateForm();
            return;
        }
        var payout = val * sel.rate;
        document.getElementById('hNgnPayout').value = payout.toFixed(2);
        document.getElementById('sum_type').textContent   = sel.name;
        document.getElementById('sum_value').textContent  = val.toLocaleString() + ' ' + sel.currency;
        document.getElementById('sum_rate').textContent   = '₦' + sel.rate.toLocaleString('en-NG') + ' per ' + sel.currency;
        document.getElementById('sum_payout').textContent = '₦' + payout.toLocaleString('en-NG', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        document.getElementById('payoutBox').style.display = 'block';
        validateForm();
    };

    // ── Image preview & drag ──────────────────────────────────────
    window.previewImage = function (input) {
        var file = input.files[0];
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) {
            alert('Image must be under 5MB.'); input.value = ''; return;
        }
        var reader = new FileReader();
        reader.onload = function (e) {
            var img = document.getElementById('imagePreview');
            img.src = e.target.result;
            img.style.display = 'block';
            document.getElementById('uploadPlaceholder').style.display = 'none';
        };
        reader.readAsDataURL(file);
        validateForm();
    };

    var zone = document.getElementById('uploadZone');
    if (zone) {
        zone.addEventListener('dragover',  function (e) { e.preventDefault(); zone.classList.add('drag-over'); });
        zone.addEventListener('dragleave', function ()  { zone.classList.remove('drag-over'); });
        zone.addEventListener('drop', function (e) {
            e.preventDefault(); zone.classList.remove('drag-over');
            var dt = e.dataTransfer; if (!dt || !dt.files.length) return;
            var inp = document.getElementById('cardImage');
            inp.files = dt.files; previewImage(inp);
        });
    }

    // ── Validate form ─────────────────────────────────────────────
    function validateForm() {
        if (!sel) return;
        var usd      = parseFloat(document.getElementById('usdAmount').value);
        var code     = document.getElementById('cardCode').value.trim();
        var phone    = document.getElementById('userPhone').value.trim();
        var bank     = document.getElementById('bankName').value.trim();
        var accNum   = document.getElementById('accountNumber').value.trim();
        var accName  = document.getElementById('accountName').value.trim();
        var hasImage = !!document.getElementById('cardImage').files.length;

        var ok = sel &&
            !isNaN(usd) && usd >= sel.min && usd <= sel.max &&
            code.length > 2 &&
            phone.length >= 7 &&
            bank.length > 0 &&
            accNum.length >= 8 &&
            accName.length > 2 &&
            hasImage;

        var btn = document.getElementById('sellBtn');
        btn.disabled = !ok;
        var payout = parseFloat(document.getElementById('hNgnPayout').value || 0);
        if (ok && payout > 0) {
            document.getElementById('sellBtnText').textContent =
                'Submit — Receive ₦' + payout.toLocaleString('en-NG', { minimumFractionDigits: 2 });
        } else {
            document.getElementById('sellBtnText').textContent = 'Submit for Review';
        }
    }

    // Watch other fields
    ['cardCode','cardPin','userPhone','bankName','accountNumber','accountName'].forEach(function (id) {
        var el = document.getElementById(id);
        if (el) el.addEventListener('input', validateForm);
    });

    // ── Sell button → modal ───────────────────────────────────────
    document.getElementById('sellBtn').addEventListener('click', function () {
        var usd    = parseFloat(document.getElementById('usdAmount').value);
        var payout = parseFloat(document.getElementById('hNgnPayout').value);
        document.getElementById('modalSummary').innerHTML =
            '<div style="display:flex;flex-direction:column;gap:8px">' +
            row('Card Type',    sel.name) +
            row('Card Value',   usd.toLocaleString() + ' ' + sel.currency) +
            row('Bank',         document.getElementById('bankName').value.trim()) +
            row('Account No.',  document.getElementById('accountNumber').value.trim()) +
            row('Acc. Name',    document.getElementById('accountName').value.trim()) +
            row('You Receive',  '₦' + payout.toLocaleString('en-NG', { minimumFractionDigits: 2 }), '#4D148C') +
            '</div>';
        document.getElementById('confirmModal').style.display = 'flex';
    });

    function row(label, val, col) {
        return '<div style="display:flex;justify-content:space-between;gap:8px">' +
            '<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';
    });

    // ── Submit via FormData (multipart for file) ──────────────────
    document.getElementById('confirmBtn').addEventListener('click', function () {
        var btn = this;
        btn.disabled  = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Submitting…';

        var fd = new FormData();
        fd.append('action',         'submit_sell_giftcard');
        fd.append('type_id',        document.getElementById('hTypeId').value);
        fd.append('type_name',      document.getElementById('hTypeName').value);
        fd.append('currency',       document.getElementById('hCurrency').value);
        fd.append('usd_amount',     document.getElementById('usdAmount').value);
        fd.append('ngn_rate',       document.getElementById('hNgnRate').value);
        fd.append('ngn_payout',     document.getElementById('hNgnPayout').value);
        fd.append('card_code',      document.getElementById('cardCode').value.trim());
        fd.append('card_pin',       document.getElementById('cardPin').value.trim());
        fd.append('phone',          document.getElementById('userPhone').value.trim());
        fd.append('bank_name',      document.getElementById('bankName').value.trim());
        fd.append('account_number', document.getElementById('accountNumber').value.trim());
        fd.append('account_name',   document.getElementById('accountName').value.trim());
        var fileInput = document.getElementById('cardImage');
        if (fileInput.files[0]) fd.append('card_image', fileInput.files[0]);

        fetch('ajax/sell-giftcard-handler.php', { method: 'POST', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (res) {
                document.getElementById('confirmModal').style.display = 'none';
                if (res.status === '1') {
                    Swal.fire({
                        title: '✅ Submitted Successfully!',
                        html:  '<p style="font-size:.85rem">Your gift card has been submitted for review.<br>Payment will be processed within 5 - 30 Minutes after verification.</p>',
                        icon:  'success',
                        confirmButtonColor: '#4D148C',
                        confirmButtonText:  'View My Sales',
                    }).then(function () { window.location.href = 'sell-giftcard-orders'; });
                } else {
                    showAlert(res.msg || 'Submission failed. Please try again.', 'error');
                    btn.disabled  = false;
                    btn.innerHTML = '<i class="fas fa-paper-plane"></i> Submit';
                }
            })
            .catch(function () {
                document.getElementById('confirmModal').style.display = 'none';
                showAlert('Network error. Please try again.', 'error');
                btn.disabled  = false;
                btn.innerHTML = '<i class="fas fa-paper-plane"></i> Submit';
            });
    });

    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'); ?>