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

// Internal (sm_purchases) logs
try {
    $stmt = $pdo->prepare("SELECT p.*, s.service_name, s.service_description, s.login_credentials, s.preview_link, c.category_name, c.category_image FROM sm_purchases p LEFT JOIN sm_services s ON p.service_id = s.id LEFT JOIN sm_categories c ON s.category_id = c.id WHERE p.user_id = :uid ORDER BY p.id DESC");
    $stmt->execute(['uid' => $user['id']]);
    $purchases = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $purchases = []; }

// XtraLogTools API orders
$xtl_orders = [];
try {
    // Ensure table exists
    $pdo->exec("CREATE TABLE IF NOT EXISTS xtralog_orders (
        id           INT AUTO_INCREMENT PRIMARY KEY,
        user_id      INT           NOT NULL,
        product_id   VARCHAR(100)  NOT NULL,
        product_name VARCHAR(255)  NOT NULL,
        server       TINYINT(1)    NOT NULL DEFAULT 1,
        quantity     INT           NOT NULL DEFAULT 1,
        unit_price   DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        total_charge DECIMAL(10,2) NOT NULL DEFAULT 0.00,
        order_ref    VARCHAR(100)  NOT NULL UNIQUE,
        api_response TEXT,
        logs_data    LONGTEXT,
        status       ENUM('pending','completed','failed') NOT NULL DEFAULT 'pending',
        created_at   TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at   TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        KEY idx_user_id  (user_id),
        KEY idx_status   (status),
        KEY idx_product  (product_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $xtl_stmt = $pdo->prepare("SELECT * FROM xtralog_orders WHERE user_id = :uid ORDER BY id DESC");
    $xtl_stmt->execute(['uid' => $user['id']]);
    $xtl_orders = $xtl_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $xtl_orders = []; }

$total_purchases = count($purchases);
$total_spent = $active_purchases = $refunded_purchases = 0;
foreach ($purchases as $p) {
    if ($p['status'] === 'completed')  { $total_spent += $p['amount']; $active_purchases++; }
    if ($p['status'] === 'refunded')     $refunded_purchases++;
}

// Include API orders in totals
$xtl_completed = 0;
foreach ($xtl_orders as $xo) {
    if ($xo['status'] === 'completed') {
        $total_spent += $xo['total_charge'];
        $xtl_completed++;
    }
}
$total_purchases += count($xtl_orders);
?>
<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}
.log-hero{background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 40%,#4D148C 80%,#4D148C 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;position:relative;overflow:hidden;margin-bottom:14px}
.log-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:14px;padding:14px;transition:border-color .2s}
.log-card:hover{border-color:rgba(77,20,140,.2)}
.stat-card{background:var(--card-bg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);border-radius:12px;padding:12px;display:flex;align-items:center;gap:10px}
.log-btn{font-size:.72rem;font-weight:600;padding:7px 12px;border-radius:8px;cursor:pointer;display:flex;align-items:center;gap:5px;transition:all .15s;text-decoration:none;}
/* Modals */
.modal-overlay{position:fixed;inset:0;z-index:200;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,.55);backdrop-filter:blur(6px);padding:16px;}
.modal-overlay.flex{display:flex;}
.modal-box{background:var(--card-bg);border:1px solid var(--card-border);border-radius:18px;padding:20px;width:100%;max-width:420px;position:relative;box-shadow:0 24px 60px rgba(0,0,0,.2);}
</style>

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

<!-- Hero -->
<div class="log-hero anim anim-1">
    <div style="position:absolute;width:140px;height:140px;border-radius:50%;filter:blur(50px);background:radial-gradient(circle,rgba(245,158,11,.15),transparent);top:-30px;right:-30px;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-bag-shopping text-yellow-300 text-base"></i>My Logs
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem;">All your purchased account logs in one place.</p>
        </div>
        <a href="buy-logs" 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-store text-xs"></i>Browse Logs
        </a>
    </div>
</div>

<!-- Stats -->
<div class="anim anim-1" style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:14px;" class="md:grid-cols-4">
    <?php foreach([
        ['fas fa-bag-shopping','rgba(77,20,140,.1)','#4D148C',$total_purchases,'Total'],
        ['fas fa-check-circle','rgba(77,20,140,.1)','#6b23c2',$active_purchases,'Active'],
        ['fas fa-dollar-sign','rgba(59,130,246,.1)','#2563eb','₦'.number_format($total_spent,2),'Spent'],
        ['fas fa-rotate-left','rgba(245,158,11,.1)','#d97706',$refunded_purchases,'Refunded'],
    ] as [$ic,$bg,$col,$val,$lbl]): ?>
    <div class="stat-card">
        <div style="width:36px;height:36px;border-radius:9px;background:<?php echo $bg; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="<?php echo $ic; ?>" style="font-size:.85rem;color:<?php echo $col; ?>;"></i>
        </div>
        <div>
            <p style="font-size:.68rem;color:var(--text-muted);font-weight:500;"><?php echo $lbl; ?></p>
            <p style="font-weight:800;font-size:.95rem;color:var(--text-primary);font-family:monospace;"><?php echo $val; ?></p>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Purchases List -->
<?php if (!empty($purchases)): ?>
<div class="anim anim-2" style="display:flex;flex-direction:column;gap:8px;">
    <?php foreach ($purchases as $p):
        switch ($p['status']) {
            case 'completed':      $bc='rgba(77,20,140,.1)'; $tc='#6b23c2'; $si='fa-check-circle'; $st='Active'; break;
            case 'cancelled':      $bc='rgba(100,116,139,.08)'; $tc='#64748b'; $si='fa-times-circle'; $st='Cancelled'; break;
            case 'refund_pending': $bc='rgba(245,158,11,.1)'; $tc='#d97706'; $si='fa-clock'; $st='Refund Pending'; break;
            case 'refunded':       $bc='rgba(59,130,246,.08)'; $tc='#2563eb'; $si='fa-rotate-left'; $st='Refunded'; break;
            default:               $bc='rgba(100,116,139,.08)'; $tc='#64748b'; $si='fa-circle'; $st=ucfirst($p['status']);
        }
        $mins_since     = (time() - strtotime($p['purchase_date'])) / 60;
        $can_refund     = ($mins_since <= 30) && ($p['status'] === 'completed');
        $remaining_mins = $can_refund ? (int)ceil(30 - $mins_since) : 0;
        $display_name   = $p['service_name'] ?? 'Deleted Service';
    ?>
    <div class="log-card">
        <div style="display:flex;flex-wrap:wrap;align-items:flex-start;gap:10px;">
            <!-- Category image -->
            <?php if (!empty($p['category_image'])): ?>
            <img src="<?php echo htmlspecialchars($p['category_image']); ?>" alt=""
                 style="width:44px;height:44px;border-radius:10px;object-fit:contain;border:1px solid var(--card-border);flex-shrink:0;"
                 onerror="this.style.display='none'">
            <?php endif; ?>

            <!-- Info -->
            <div style="flex:1;min-width:0;">
                <p style="font-weight:700;font-size:.85rem;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:6px;">
                    <?php echo htmlspecialchars($display_name); ?>
                </p>
                <div style="display:flex;flex-wrap:wrap;align-items:center;gap:5px;margin-bottom:5px;">
                    <span style="font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:99px;background:rgba(77,20,140,.08);color:#4D148C;">
                        <?php echo htmlspecialchars($p['category_name'] ?? '—'); ?>
                    </span>
                    <span style="font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:99px;background:<?php echo $bc; ?>;color:<?php echo $tc; ?>;display:flex;align-items:center;gap:3px;">
                        <i class="fas <?php echo $si; ?>" style="font-size:.55rem;"></i><?php echo $st; ?>
                    </span>
                    <span style="font-size:.65rem;color:var(--text-muted);">
                        <i class="fa-regular fa-calendar mr-1"></i><?php echo date('M d, Y • h:i A', strtotime($p['purchase_date'])); ?>
                    </span>
                </div>
                <?php if ($p['status'] === 'completed' && $can_refund): ?>
                <p style="font-size:.68rem;color:#d97706;margin-top:3px;"><i class="fas fa-clock mr-1"></i><?php echo $remaining_mins; ?> min left to request refund</p>
                <?php elseif ($p['status'] === 'completed' && !$can_refund): ?>
                <p style="font-size:.68rem;color:var(--text-muted);margin-top:3px;"><i class="fas fa-lock mr-1"></i>Refund window closed</p>
                <?php endif; ?>
            </div>

            <!-- Right: price + actions -->
            <div style="display:flex;flex-wrap:wrap;align-items:center;gap:6px;flex-shrink:0;">
                <span style="font-weight:800;font-size:1rem;color:#4D148C;font-family:monospace;">₦<?php echo number_format($p['amount'],2); ?></span>

                <?php if ($p['status'] === 'completed'): ?>
                <button onclick='showCredentials(<?php echo $p["id"]; ?>,"<?php echo htmlspecialchars(addslashes($display_name)); ?>",`<?php echo htmlspecialchars($p["login_credentials"]); ?>`)'
                        class="log-btn" style="background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;border:none;">
                    <i class="fas fa-eye text-xs"></i>View Log
                </button>
                <?php if (!empty($p['preview_link'])): ?>
                <a href="<?php echo htmlspecialchars($p['preview_link']); ?>" target="_blank"
                   class="log-btn" style="background:var(--btn-bg);color:var(--text-primary);border:1px solid var(--card-border);">
                    <i class="fas fa-external-link-alt text-xs"></i>Preview
                </a>
                <?php endif; ?>
                <?php if ($can_refund): ?>
                <button onclick='requestRefund(<?php echo $p["id"]; ?>,"<?php echo htmlspecialchars(addslashes($display_name)); ?>")'
                        class="log-btn" style="background:rgba(239,68,68,.07);color:#dc2626;border:1px solid rgba(239,68,68,.15);">
                    <i class="fas fa-rotate-left text-xs"></i>Refund
                </button>
                <?php else: ?>
                <button disabled class="log-btn" style="background:var(--btn-bg);color:var(--text-muted);border:1px solid var(--card-border);opacity:.5;cursor:not-allowed;" title="Refund window closed">
                    <i class="fas fa-lock text-xs"></i>Refund
                </button>
                <?php endif; ?>

                <?php elseif ($p['status'] === 'refund_pending'): ?>
                <p style="font-size:.72rem;color:#d97706;font-style:italic;"><i class="fas fa-hourglass-half mr-1"></i>Pending admin review</p>
                <?php elseif ($p['status'] === 'refunded'): ?>
                <p style="font-size:.72rem;color:#2563eb;"><i class="fas fa-check-circle mr-1"></i>Refunded</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="anim anim-2" style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:16px;padding:40px;text-align:center;">
    <div style="width:56px;height:56px;border-radius:50%;background:rgba(77,20,140,.07);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;">
        <i class="fas fa-bag-shopping" style="font-size:1.4rem;color:var(--text-muted);"></i>
    </div>
    <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:6px;">No Purchases Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto 16px;">Browse our logs marketplace to find what you need.</p>
    <a href="buy-logs" style="display:inline-flex;align-items:center;gap:8px;padding:11px 22px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.82rem;border-radius:10px;text-decoration:none;box-shadow:0 4px 14px rgba(77,20,140,.25);">
        <i class="fas fa-store"></i>Browse Logs
    </a>
</div>
<?php endif; ?>

<?php if (!empty($xtl_orders)): ?>
<!-- ── XtraLogTools API Orders ─────────────────────────────── -->
<div class="anim anim-2" style="margin-top:24px;">
    <div style="display:flex;align-items:center;gap:10px;margin-bottom:12px;">
        <div style="width:28px;height:28px;border-radius:7px;
                    background:linear-gradient(135deg,#059669,#10b981);
                    display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas fa-bolt" style="color:white;font-size:.7rem;"></i>
        </div>
        <h3 style="font-weight:800;font-size:.88rem;color:var(--text-primary);margin:0;">
            API Log Orders
            <span style="font-size:.72rem;font-weight:500;color:var(--text-muted);margin-left:6px;">
                (<?php echo count($xtl_orders); ?> orders via XtraLogTools)
            </span>
        </h3>
    </div>

    <div style="display:flex;flex-direction:column;gap:8px;">
        <?php foreach ($xtl_orders as $xo):
            switch ($xo['status']) {
                case 'completed': $bc='rgba(5,150,105,.1)'; $tc='#059669'; $si='fa-check-circle'; $st='Delivered'; break;
                case 'failed':    $bc='rgba(239,68,68,.08)'; $tc='#dc2626'; $si='fa-times-circle'; $st='Failed'; break;
                default:          $bc='rgba(245,158,11,.1)'; $tc='#d97706'; $si='fa-clock'; $st='Pending';
            }
        ?>
        <div class="log-card">
            <div style="display:flex;flex-wrap:wrap;align-items:flex-start;gap:10px;">
                <!-- Icon -->
                <div style="width:44px;height:44px;border-radius:10px;
                            background:linear-gradient(135deg,#059669,#10b981);
                            display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                    <i class="fas fa-bolt" style="color:white;font-size:.9rem;"></i>
                </div>

                <!-- Info -->
                <div style="flex:1;min-width:0;">
                    <p style="font-weight:700;font-size:.85rem;color:var(--text-primary);
                               white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-bottom:6px;">
                        <?php echo htmlspecialchars($xo['product_name']); ?>
                    </p>
                    <div style="display:flex;flex-wrap:wrap;align-items:center;gap:5px;margin-bottom:5px;">
                        <span style="font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:99px;
                                     background:rgba(5,150,105,.08);color:#059669;">
                            API — Server <?php echo (int)$xo['server']; ?>
                        </span>
                        <span style="font-size:.65rem;font-weight:700;padding:2px 8px;border-radius:99px;
                                     background:<?php echo $bc; ?>;color:<?php echo $tc; ?>;
                                     display:flex;align-items:center;gap:3px;">
                            <i class="fas <?php echo $si; ?>" style="font-size:.55rem;"></i><?php echo $st; ?>
                        </span>
                        <span style="font-size:.65rem;color:var(--text-muted);">
                            Qty: <?php echo (int)$xo['quantity']; ?> ·
                            <i class="fa-regular fa-calendar mr-1"></i><?php echo date('M d, Y • h:i A', strtotime($xo['created_at'])); ?>
                        </span>
                    </div>
                    <p style="font-size:.68rem;color:var(--text-muted);">
                        Ref: <code><?php echo htmlspecialchars($xo['order_ref']); ?></code>
                    </p>
                </div>

                <!-- Right: price + actions -->
                <div style="display:flex;flex-wrap:wrap;align-items:center;gap:6px;flex-shrink:0;">
                    <span style="font-weight:800;font-size:1rem;color:#059669;font-family:monospace;">
                        ₦<?php echo number_format($xo['total_charge'], 2); ?>
                    </span>
                    <?php if ($xo['status'] === 'completed' && !empty($xo['logs_data'])): ?>
                    <button onclick='showApiCredentials(<?php echo $xo["id"]; ?>, "<?php echo htmlspecialchars(addslashes($xo["product_name"])); ?>", `<?php echo htmlspecialchars($xo["logs_data"]); ?>`)'
                            class="log-btn" style="background:linear-gradient(135deg,#059669,#10b981);color:white;border:none;">
                        <i class="fas fa-eye text-xs"></i>View Log
                    </button>
                    <?php elseif ($xo['status'] === 'failed'): ?>
                    <span style="font-size:.72rem;color:#dc2626;"><i class="fas fa-times-circle mr-1"></i>Delivery failed</span>
                    <?php else: ?>
                    <span style="font-size:.72rem;color:#d97706;"><i class="fas fa-hourglass-half mr-1"></i>Processing</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

</div><!-- /max-w -->

<!-- API Credentials Modal -->
<div id="apiCredentialsModal" class="modal-overlay">
    <div class="modal-box">
        <button onclick="closeApiCredentialsModal()" style="position:absolute;top:14px;right:14px;width:32px;height:32px;border-radius:50%;background:var(--btn-bg);border:1px solid var(--card-border);cursor:pointer;display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-times text-xs" style="color:var(--text-muted);"></i>
        </button>
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;padding-right:36px;">
            <div style="width:36px;height:36px;border-radius:9px;background:rgba(5,150,105,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-key" style="color:#059669;font-size:.9rem;"></i>
            </div>
            <div>
                <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);">API Log Credentials</h3>
                <p id="api_cred_service_name" style="font-size:.72rem;color:var(--text-muted);"></p>
            </div>
        </div>
        <div style="background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.15);border-radius:10px;padding:10px 12px;margin-bottom:12px;display:flex;gap:8px;">
            <i class="fas fa-triangle-exclamation text-red-500 text-sm flex-shrink-0 mt-0.5"></i>
            <p style="font-size:.72rem;color:#dc2626;">Keep these credentials safe. Change the password immediately after first login.</p>
        </div>
        <div style="background:var(--btn-bg);border:1px solid var(--card-border);border-radius:10px;padding:12px;max-height:200px;overflow-y:auto;margin-bottom:12px;">
            <pre id="api_cred_text" style="white-space:pre-wrap;word-break:break-words;font-family:monospace;font-size:.8rem;color:var(--text-primary);margin:0;"></pre>
        </div>
        <button onclick="copyApiCredentials()" style="width:100%;background:linear-gradient(135deg,#059669,#10b981);color:white;font-weight:700;padding:11px;border-radius:10px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;font-size:.85rem;">
            <i class="fas fa-copy"></i>Copy Credentials
        </button>
    </div>
</div>

<!-- Credentials Modal -->
<div id="credentialsModal" class="modal-overlay">
    <div class="modal-box">
        <button onclick="closeCredentialsModal()" style="position:absolute;top:14px;right:14px;width:32px;height:32px;border-radius:50%;background:var(--btn-bg);border:1px solid var(--card-border);cursor:pointer;display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-times text-xs" style="color:var(--text-muted);"></i>
        </button>
        <div style="display:flex;align-items:center;gap:10px;margin-bottom:14px;padding-right:36px;">
            <div style="width:36px;height:36px;border-radius:9px;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fas fa-key text-emerald-600 text-sm"></i>
            </div>
            <div>
                <h3 style="font-weight:700;font-size:.88rem;color:var(--text-primary);">Log Credentials</h3>
                <p id="credentials_service_name" style="font-size:.72rem;color:var(--text-muted);"></p>
            </div>
        </div>
        <div style="background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.15);border-radius:10px;padding:10px 12px;margin-bottom:12px;display:flex;gap:8px;">
            <i class="fas fa-triangle-exclamation text-red-500 text-sm flex-shrink-0 mt-0.5"></i>
            <p style="font-size:.72rem;color:#dc2626;">Keep these credentials safe. Change the password immediately after first login.</p>
        </div>
        <div style="background:var(--btn-bg);border:1px solid var(--card-border);border-radius:10px;padding:12px;max-height:200px;overflow-y:auto;margin-bottom:12px;">
            <pre id="credentials_text" style="white-space:pre-wrap;word-break:break-words;font-family:monospace;font-size:.8rem;color:var(--text-primary);margin:0;"></pre>
        </div>
        <button onclick="copyCredentials()" style="width:100%;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;padding:11px;border-radius:10px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;font-size:.85rem;">
            <i class="fas fa-copy"></i>Copy Credentials
        </button>
    </div>
</div>

<!-- Refund Modal -->
<div id="refundModal" class="modal-overlay">
    <div class="modal-box">
        <button onclick="closeRefundModal()" style="position:absolute;top:14px;right:14px;width:32px;height:32px;border-radius:50%;background:var(--btn-bg);border:1px solid var(--card-border);cursor:pointer;display:flex;align-items:center;justify-content:center;">
            <i class="fas fa-times text-xs" style="color:var(--text-muted);"></i>
        </button>
        <div style="text-align:center;margin-bottom:16px;">
            <div style="width:48px;height:48px;background:rgba(239,68,68,.1);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 10px;">
                <i class="fas fa-rotate-left text-red-500 text-lg"></i>
            </div>
            <h3 style="font-weight:700;font-size:.9rem;color:var(--text-primary);">Request Refund</h3>
            <p id="refund_service_name" style="font-size:.75rem;color:var(--text-muted);margin-top:4px;"></p>
        </div>
        <input type="hidden" id="refund_purchase_id">
        <div style="margin-bottom:12px;">
            <label style="display:block;font-size:.75rem;font-weight:600;color:var(--text-muted);margin-bottom:5px;">Reason <span style="color:#ef4444;">*</span></label>
            <textarea id="refund_reason" rows="4" placeholder="Please provide a detailed reason (min 10 characters)..."
                      style="width:100%;padding:10px 12px;border-radius:10px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--hd-title);font-size:.82rem;outline:none;resize:none;transition:border-color .2s;"
                      onfocus="this.style.borderColor='#6b23c2'" onblur="this.style.borderColor=''"></textarea>
        </div>
        <div style="background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.18);border-radius:10px;padding:10px 12px;margin-bottom:14px;display:flex;gap:8px;">
            <i class="fas fa-clock text-amber-500 text-sm flex-shrink-0 mt-0.5"></i>
            <p style="font-size:.72rem;color:#d97706;">Refund requests are only available within <strong>30 minutes</strong> of purchase and require admin approval.</p>
        </div>
        <div style="display:flex;gap:8px;">
            <button onclick="closeRefundModal()" style="flex:1;border:1px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);font-weight:600;padding:10px;border-radius:10px;cursor:pointer;font-size:.82rem;">
                Cancel
            </button>
            <button id="confirmRefundBtn" onclick="confirmRefund()" style="flex:1;background:linear-gradient(135deg,#dc2626,#ef4444);color:white;font-weight:700;padding:10px;border-radius:10px;border:none;cursor:pointer;font-size:.82rem;display:flex;align-items:center;justify-content:center;gap:6px;">
                <i class="fas fa-check text-xs"></i>Submit
            </button>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function showModal(id){const m=document.getElementById(id);m.classList.remove('hidden');m.classList.add('flex');}
function hideModal(id){const m=document.getElementById(id);m.classList.add('hidden');m.classList.remove('flex');}
function closeCredentialsModal(){hideModal('credentialsModal');}
function closeRefundModal(){hideModal('refundModal');}

['credentialsModal','refundModal'].forEach(id=>{
    document.getElementById(id).addEventListener('click',function(e){if(e.target===this)hideModal(id);});
});

function showCredentials(purchaseId,serviceName,credentials){
    document.getElementById('credentials_service_name').textContent=serviceName;
    document.getElementById('credentials_text').textContent=credentials;
    showModal('credentialsModal');
}
function copyCredentials(){
    const text=document.getElementById('credentials_text').textContent;
    if(navigator.clipboard&&navigator.clipboard.writeText){
        navigator.clipboard.writeText(text).then(()=>Swal.fire({title:'Copied!',text:'Credentials copied to clipboard.',icon:'success',timer:1500,showConfirmButton:false})).catch(()=>fallbackCopy(text));
    }else{fallbackCopy(text);}
}
function fallbackCopy(text){
    const ta=document.createElement('textarea');ta.value=text;Object.assign(ta.style,{position:'fixed',top:0,left:0,width:'2em',height:'2em',padding:0,border:'none',outline:'none',boxShadow:'none',background:'transparent'});
    document.body.appendChild(ta);ta.focus();ta.select();
    try{document.execCommand('copy');Swal.fire({title:'Copied!',icon:'success',timer:1500,showConfirmButton:false});}catch(e){Swal.fire('Failed','Could not copy.','error');}
    document.body.removeChild(ta);
}
function requestRefund(purchaseId,serviceName){
    currentRefundId=purchaseId;
    document.getElementById('refund_purchase_id').value=purchaseId;
    document.getElementById('refund_service_name').textContent=serviceName;
    document.getElementById('refund_reason').value='';
    showModal('refundModal');
}
function confirmRefund(){
    const reason=document.getElementById('refund_reason').value.trim();
    if(!reason||reason.length<10){Swal.fire('Validation','Please provide a reason of at least 10 characters.','warning');return;}
    const btn=document.getElementById('confirmRefundBtn');btn.disabled=true;btn.innerHTML='<i class="fas fa-spinner fa-spin text-xs"></i>Processing...';
    $.ajax({url:'ajax/request_log_refund.php',type:'POST',data:{purchase_id:currentRefundId,refund_reason:reason},dataType:'json',
        success(res){btn.disabled=false;btn.innerHTML='<i class="fas fa-check text-xs"></i>Submit';closeRefundModal();
            if(res.status==='1'){Swal.fire({title:'Request Sent',text:res.msg,icon:'success',confirmButtonColor:'#4D148C'}).then(()=>location.reload());}
            else{Swal.fire('Failed',res.msg||'Failed to submit refund request.','error');}
        },
        error(){btn.disabled=false;btn.innerHTML='<i class="fas fa-check text-xs"></i>Submit';closeRefundModal();Swal.fire('Error','An error occurred.','error');}
    });
}

// ── API Credentials Modal ─────────────────────────────────────
function showApiCredentials(orderId, serviceName, credentials) {
    document.getElementById('api_cred_service_name').textContent = serviceName;
    document.getElementById('api_cred_text').textContent = credentials;
    showModal('apiCredentialsModal');
}
function closeApiCredentialsModal() { hideModal('apiCredentialsModal'); }
document.getElementById('apiCredentialsModal')?.addEventListener('click', function(e) {
    if (e.target === this) hideModal('apiCredentialsModal');
});
function copyApiCredentials() {
    const text = document.getElementById('api_cred_text').textContent;
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(function() {
            Swal.fire({ title: 'Copied!', icon: 'success', timer: 1200, showConfirmButton: false });
        });
    } else {
        const ta = document.createElement('textarea');
        ta.value = text;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        Swal.fire({ title: 'Copied!', icon: 'success', timer: 1200, showConfirmButton: false });
    }
}
</script>

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