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

$items_per_page = 15;
$current_page   = max(1, (int)($_GET['page'] ?? 1));
$offset         = ($current_page - 1) * $items_per_page;

try {
    $count = (int)$pdo->prepare("SELECT COUNT(*) FROM gift_card_orders WHERE user_id = :uid")->execute(['uid'=>$user['id']]);
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM gift_card_orders WHERE user_id = :uid");
    $count_stmt->execute(['uid' => $user['id']]);
    $total = (int)$count_stmt->fetchColumn();
    $total_pages = (int)ceil($total / $items_per_page);

    $stmt = $pdo->prepare("SELECT * FROM gift_card_orders WHERE user_id = :uid ORDER BY id DESC LIMIT :lim OFFSET :off");
    $stmt->bindValue(':uid', $user['id']);
    $stmt->bindValue(':lim', $items_per_page, PDO::PARAM_INT);
    $stmt->bindValue(':off', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $orders = []; $total = 0; $total_pages = 1; }

// Stats
try {
    $stats_stmt = $pdo->prepare(
        "SELECT COUNT(*) as total,
                SUM(CASE WHEN status='completed' THEN 1 ELSE 0 END) as completed,
                SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status='completed' THEN charge ELSE 0 END) as total_spent
         FROM gift_card_orders WHERE user_id = :uid"
    );
    $stats_stmt->execute(['uid' => $user['id']]);
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $stats = ['total'=>0,'completed'=>0,'pending'=>0,'total_spent'=>0];
}
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<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: 14px;
}
.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);
}

.ord-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; margin-bottom: 10px;
}
.ord-card:hover { border-color: rgba(77,20,140,.25); }

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

.code-box {
    background: rgba(77,20,140,.06);
    border: 1px solid rgba(77,20,140,.2);
    border-radius: 9px; padding: 8px 12px;
    font-family: monospace; font-size: .85rem;
    font-weight: 700; color: #4D148C;
    word-break: break-all;
    display: flex; align-items: center;
    justify-content: space-between; gap: 8px; margin-top: 8px;
}
</style>

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

<!-- Hero -->
<div class="gc-hero anim anim-1">
    <div style="position:absolute;width:140px;height:140px;border-radius:50%;filter:blur(50px);background:radial-gradient(circle,rgba(77,20,140,.3),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-gift" style="color:#c4b5fd"></i>My Gift Card Orders
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">All your digital gift card purchases.</p>
        </div>
        <a href="buy-giftcard" 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>Buy Gift Card
        </a>
    </div>
</div>

<!-- Stats -->
<div class="anim anim-1" style="display:grid;grid-template-columns:repeat(2,1fr);gap:8px;margin-bottom:14px">
    <?php foreach ([
        ['fas fa-list',          'rgba(77,20,140,.1)',  '#4D148C', $stats['total'],        'Total Orders'],
        ['fas fa-circle-check',  'rgba(77,20,140,.1)',  '#6b23c2', $stats['completed'],     'Completed'],
        ['fas fa-clock',         'rgba(245,158,11,.1)',  '#d97706', $stats['pending'],       'Pending'],
        ['fas fa-naira-sign',    'rgba(77,20,140,.1)',  '#4D148C', '₦'.number_format($stats['total_spent']??0,2), 'Total Spent'],
    ] 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>

<!-- Orders -->
<?php if (!empty($orders)): ?>
<div class="anim anim-2">
    <?php foreach ($orders as $o):
        switch ($o['status']) {
            case 'completed': $bc='rgba(77,20,140,.08)';  $tc='#6b23c2'; $ic='fa-circle-check'; break;
            case 'failed':    $bc='rgba(239,68,68,.08)';   $tc='#dc2626'; $ic='fa-circle-xmark'; break;
            case 'refunded':  $bc='rgba(245,158,11,.08)';  $tc='#d97706'; $ic='fa-rotate-left';  break;
            default:          $bc='rgba(245,158,11,.08)';  $tc='#d97706'; $ic='fa-clock';        break;
        }
    ?>
    <div class="ord-card">
        <div style="display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap">
            <div style="width:40px;height:40px;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-gift" style="color:#4D148C;font-size:.9rem"></i>
            </div>
            <div style="flex:1;min-width:0">
                <div style="display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:5px">
                    <span style="font-size:.65rem;font-weight:700;color:var(--text-muted);font-family:monospace">#<?php echo $o['id']; ?></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:4px">
                        <i class="fas <?php echo $ic; ?>" style="font-size:.55rem"></i><?php echo ucfirst($o['status']); ?>
                    </span>
                    <span style="font-size:.65rem;padding:2px 8px;border-radius:99px;background:rgba(77,20,140,.08);color:#4D148C;font-weight:600">
                        <?php echo htmlspecialchars($o['currency_code']); ?>
                    </span>
                </div>
                <p style="font-weight:700;font-size:.85rem;color:var(--text-primary);margin-bottom:2px"><?php echo htmlspecialchars($o['product_name']); ?></p>
                <p style="font-size:.72rem;color:var(--text-muted);margin-bottom:4px">
                    <i class="fas fa-envelope" style="font-size:.65rem;margin-right:3px"></i><?php echo htmlspecialchars($o['recipient_email']); ?>
                </p>
                <p style="font-size:.68rem;color:var(--text-muted)">
                    <?php echo date('M d, Y · h:i A', strtotime($o['created_at'])); ?>
                </p>

                <!-- Card code (only show if completed) -->
                <?php if ($o['status'] === 'completed' && !empty($o['card_number'])): ?>
                <div class="code-box">
                    <div>
                        <p style="font-size:.58rem;color:#4D148C;font-weight:600;margin-bottom:2px">Card Code</p>
                        <p><?php echo htmlspecialchars($o['card_number']); ?></p>
                        <?php if (!empty($o['card_pin'])): ?>
                        <p style="font-size:.7rem;color:#6b23c2;margin-top:3px">PIN: <?php echo htmlspecialchars($o['card_pin']); ?></p>
                        <?php endif; ?>
                    </div>
                    <button onclick="copyCode('<?php echo addslashes($o['card_number']); ?>')"
                            style="padding:5px 10px;border-radius:7px;background:rgba(77,20,140,.1);border:1px solid rgba(77,20,140,.2);color:#4D148C;font-size:.7rem;cursor:pointer;flex-shrink:0">
                        <i class="fa-regular fa-copy"></i>
                    </button>
                </div>
                <?php if (!empty($o['redeem_url'])): ?>
                <a href="<?php echo htmlspecialchars($o['redeem_url']); ?>" target="_blank"
                   style="display:inline-flex;align-items:center;gap:6px;margin-top:6px;font-size:.7rem;font-weight:600;color:#4D148C;text-decoration:none">
                    <i class="fas fa-external-link" style="font-size:.65rem"></i>Redeem Now
                </a>
                <?php endif; ?>
                <?php endif; ?>
            </div>
            <div style="text-align:right;flex-shrink:0">
                <p style="font-weight:800;font-size:.95rem;color:#4D148C;font-family:monospace">₦<?php echo number_format($o['charge'], 2); ?></p>
                <p style="font-size:.7rem;color:var(--text-muted)"><?php echo $o['unit_price']; ?> <?php echo $o['currency_code']; ?></p>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Pagination -->
<?php if ($total_pages > 1): ?>
<div class="anim anim-3" style="display:flex;justify-content:center;gap:6px;flex-wrap:wrap;margin-bottom:8px">
    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
    <a href="?page=<?php echo $i; ?>"
       style="padding:7px 13px;border-radius:8px;font-size:.78rem;font-weight:600;text-decoration:none;border:1.5px solid var(--card-border);background:<?php echo $i===$current_page?'linear-gradient(135deg,#4D148C,#6b23c2)':'var(--btn-bg)'; ?>;color:<?php echo $i===$current_page?'white':'var(--text-muted)'; ?>">
        <?php echo $i; ?>
    </a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<?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-gift" 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 Gift Card Orders Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto 16px">Purchase your first gift card and the code will be delivered instantly to your email.</p>
    <a href="buy-giftcard" 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,.3)">
        <i class="fas fa-gift"></i>Buy a Gift Card
    </a>
</div>
<?php endif; ?>

</div>

<script>
function copyCode(text) {
    navigator.clipboard.writeText(text).then(function() {
        var el = document.createElement('div');
        el.style.cssText = 'position:fixed;top:20px;left:50%;transform:translateX(-50%);z-index:99999;padding:10px 18px;border-radius:10px;font-size:.8rem;font-weight:700;color:white;background:#4D148C;box-shadow:0 4px 14px rgba(0,0,0,.2)';
        el.textContent = '✓ Code copied!';
        document.body.appendChild(el);
        setTimeout(function(){ el.remove(); }, 2000);
    });
}
</script>

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