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

$items_per_page = 15;
$current_page   = max(1, (int)($_GET['page'] ?? 1));
$offset         = ($current_page - 1) * $items_per_page;
$filter_type    = $_GET['type'] ?? 'all';
$allowed_types  = ['all', 'data', 'airtime', 'cable', 'electricity'];
if (!in_array($filter_type, $allowed_types)) $filter_type = 'all';

$where  = "WHERE user_id = :uid";
$params = ['uid' => $user['id']];
if ($filter_type !== 'all') { $where .= " AND service_type = :type"; $params['type'] = $filter_type; }

try {
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM vtu_history $where");
    $count_stmt->execute($params);
    $total        = (int)$count_stmt->fetchColumn();
    $total_pages  = (int)ceil($total / $items_per_page);

    $hist_stmt = $pdo->prepare("SELECT * FROM vtu_history $where ORDER BY id DESC LIMIT :lim OFFSET :off");
    foreach ($params as $k => $v) $hist_stmt->bindValue(":$k", $v);
    $hist_stmt->bindValue(':lim', $items_per_page, PDO::PARAM_INT);
    $hist_stmt->bindValue(':off', $offset, PDO::PARAM_INT);
    $hist_stmt->execute();
    $records = $hist_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $records = []; $total_pages = 1; $total = 0; }

// Stats
try {
    $stats_stmt = $pdo->prepare(
        "SELECT
            COUNT(*) as total,
            SUM(CASE WHEN service_type='data' THEN 1 ELSE 0 END) as data_count,
            SUM(CASE WHEN service_type='airtime' THEN 1 ELSE 0 END) as air_count,
            SUM(CASE WHEN service_type='cable' THEN 1 ELSE 0 END) as cable_count,
            SUM(CASE WHEN service_type='electricity' THEN 1 ELSE 0 END) as elec_count,
            SUM(amount) as total_spent
         FROM vtu_history WHERE user_id = :uid AND status = 'success'"
    );
    $stats_stmt->execute(['uid' => $user['id']]);
    $stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $stats = ['total'=>0,'data_count'=>0,'air_count'=>0,'cable_count'=>0,'elec_count'=>0,'total_spent'=>0]; }

// Icon / color config per service type
$type_meta = [
    'data'        => ['icon'=>'fas fa-wifi',               'color'=>'#4D148C', 'bg'=>'rgba(77,20,140,.08)',  'border'=>'rgba(77,20,140,.2)',  'label'=>'Data'],
    'airtime'     => ['icon'=>'fas fa-phone',              'color'=>'#7c3aed', 'bg'=>'rgba(124,58,237,.08)', 'border'=>'rgba(124,58,237,.2)', 'label'=>'Airtime'],
    'cable'       => ['icon'=>'fas fa-tv',                 'color'=>'#0369a1', 'bg'=>'rgba(3,105,161,.08)',  'border'=>'rgba(3,105,161,.2)',  'label'=>'Cable TV'],
    'electricity' => ['icon'=>'fas fa-bolt',               'color'=>'#ca8a04', 'bg'=>'rgba(234,179,8,.08)',  'border'=>'rgba(234,179,8,.2)',  'label'=>'Electricity'],
];
$status_meta = [
    'success' => ['color'=>'#4D148C','bg'=>'rgba(77,20,140,.08)','label'=>'Success'],
    'pending' => ['color'=>'#f59e0b','bg'=>'rgba(245,158,11,.08)','label'=>'Pending'],
    'failed'  => ['color'=>'#ef4444','bg'=>'rgba(239,68,68,.08)', 'label'=>'Failed'],
];
?>
<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}
.hero-vtu{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}
.vtu-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}
.vtu-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}
.filter-btn{padding:7px 14px;border-radius:8px;font-size:.75rem;font-weight:600;cursor:pointer;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);text-decoration:none;transition:all .15s}
.filter-btn.active{background:rgba(77,20,140,.08);border-color:rgba(77,20,140,.25);color:#4D148C}
</style>

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

<!-- Hero -->
<div class="hero-vtu 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,.2),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-clock-rotate-left text-emerald-300 text-base"></i>VTU & Bills History
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">All your data, airtime, cable and electricity purchases.</p>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <a href="buy-data"    style="background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);color:white;font-weight:600;font-size:.75rem;padding:8px 14px;border-radius:10px;text-decoration:none"><i class="fas fa-wifi mr-1"></i>Data</a>
            <a href="buy-airtime" style="background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.2);color:white;font-weight:600;font-size:.75rem;padding:8px 14px;border-radius:10px;text-decoration:none"><i class="fas fa-phone mr-1"></i>Airtime</a>
            <a href="cable-tv"   style="background:white;color:#4D148C;font-weight:700;font-size:.75rem;padding:8px 14px;border-radius:10px;text-decoration:none"><i class="fas fa-tv mr-1"></i>Cable</a>
            <a href="electricity"   style="background:white;color:#4D148C;font-weight:700;font-size:.75rem;padding:8px 14px;border-radius:10px;text-decoration:none"><i class="fas fa-bolt mr-1"></i>Electricity</a>
        </div>
    </div>
</div>

<!-- Stats Grid -->
<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,.08)','#4D148C',  $stats['total'],      'Total Orders'],
        ['fas fa-wifi','rgba(77,20,140,.08)','#4D148C',  $stats['data_count'], 'Data'],
        ['fas fa-phone','rgba(124,58,237,.08)','#7c3aed', $stats['air_count'],  'Airtime'],
        ['fas fa-tv',   'rgba(3,105,161,.08)', '#0369a1', $stats['cable_count'],'Cable TV'],
        ['fas fa-bolt', 'rgba(234,179,8,.08)', '#ca8a04', $stats['elec_count'], 'Electricity'],
        ['fas fa-naira-sign','rgba(59,130,246,.08)','#2563eb','₦'.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>

<!-- Filters -->
<div class="anim anim-2" style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px">
    <?php foreach(['all'=>'All','data'=>'Data','airtime'=>'Airtime','cable'=>'Cable TV','electricity'=>'Electricity'] as $fv=>$fl): ?>
    <a href="?type=<?php echo $fv; ?>" class="filter-btn <?php echo $filter_type===$fv?'active':''; ?>"><?php echo $fl; ?></a>
    <?php endforeach; ?>
    <span style="flex:1"></span>
    <span style="font-size:.72rem;color:var(--text-muted);align-self:center"><?php echo $total; ?> records</span>
</div>

<!-- Records -->
<?php if (!empty($records)): ?>
<div class="anim anim-2" style="display:flex;flex-direction:column;gap:8px;margin-bottom:14px">
    <?php foreach ($records as $r):
        $tm = $type_meta[$r['service_type']] ?? $type_meta['data'];
        $sm = $status_meta[$r['status']] ?? $status_meta['success'];
    ?>
    <div class="vtu-card">
        <div style="display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap">
            <!-- Icon -->
            <div style="width:40px;height:40px;border-radius:10px;background:<?php echo $tm['bg']; ?>;border:1px solid <?php echo $tm['border']; ?>;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                <i class="<?php echo $tm['icon']; ?>" style="color:<?php echo $tm['color']; ?>;font-size:.9rem"></i>
            </div>
            <!-- Info -->
            <div style="flex:1;min-width:0">
                <div style="display:flex;flex-wrap:wrap;align-items:flex-start;justify-content:space-between;gap:6px;margin-bottom:6px">
                    <div>
                        <p style="font-weight:700;font-size:.88rem;color:var(--text-primary)">
                            <?php echo htmlspecialchars($r['plan_name'] ?? $tm['label']); ?>
                        </p>
                        <p style="font-size:.7rem;color:var(--text-muted);margin-top:1px">
                            <?php echo htmlspecialchars($r['network'] ?? ''); ?>
                            <?php if (!empty($r['phone'])): ?> · <?php echo htmlspecialchars($r['phone']); ?><?php endif; ?>
                        </p>
                    </div>
                    <div style="text-align:right">
                        <p style="font-weight:700;font-size:.82rem;color:#ef4444;font-family:monospace">−₦<?php echo number_format($r['amount'], 2); ?></p>
                        <p style="font-size:.65rem;color:var(--text-muted)"><?php echo date('M d, Y • h:i A', strtotime($r['created_at'] ?? 'now')); ?></p>
                    </div>
                </div>

                <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
                    <!-- Status badge -->
                    <span style="display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:99px;background:<?php echo $sm['bg']; ?>;color:<?php echo $sm['color']; ?>;font-size:.68rem;font-weight:700">
                        <i class="fas fa-<?php echo $r['status']==='success'?'circle-check':($r['status']==='pending'?'clock':'circle-xmark'); ?> text-xs"></i>
                        <?php echo $sm['label']; ?>
                    </span>
                    <!-- Type badge -->
                    <span style="padding:3px 8px;border-radius:99px;background:<?php echo $tm['bg']; ?>;color:<?php echo $tm['color']; ?>;font-size:.65rem;font-weight:600">
                        <?php echo $tm['label']; ?>
                    </span>
                    <!-- Electricity token -->
                    <?php if (!empty($r['token'])): ?>
                    <div style="background:rgba(234,179,8,.07);border:1px solid rgba(234,179,8,.2);border-radius:8px;padding:5px 10px;display:flex;align-items:center;gap:8px;width:100%;margin-top:4px">
                        <div>
                            <p style="font-size:.62rem;color:#ca8a04;font-weight:600;margin-bottom:1px">Electricity Token</p>
                            <p style="font-weight:800;font-size:.9rem;color:#a16207;font-family:monospace;letter-spacing:.06em"><?php echo htmlspecialchars($r['token']); ?></p>
                        </div>
                        <button onclick="navigator.clipboard.writeText('<?php echo addslashes($r['token']); ?>').then(()=>this.innerHTML='<i class=\'fas fa-check\'></i>')"
                                style="margin-left:auto;padding:5px 10px;border-radius:7px;background:rgba(234,179,8,.1);border:1px solid rgba(234,179,8,.2);color:#ca8a04;font-size:.7rem;cursor:pointer;flex-shrink:0">
                            <i class="fa-regular fa-copy"></i>
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
            </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="?type=<?php echo $filter_type; ?>&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-receipt" 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 Records Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto 16px">You haven't made any VTU or bill payments yet.</p>
    <div style="display:flex;gap:8px;justify-content:center;flex-wrap:wrap">
        <a href="buy-data" style="display:inline-flex;align-items:center;gap:8px;padding:10px 18px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.78rem;border-radius:10px;text-decoration:none">
            <i class="fas fa-wifi"></i>Buy Data
        </a>
        <!--<a href="pay-bills" style="display:inline-flex;align-items:center;gap:8px;padding:10px 18px;background:linear-gradient(135deg,#0369a1,#0ea5e9);color:white;font-weight:700;font-size:.78rem;border-radius:10px;text-decoration:none">
            <i class="fas fa-file-invoice-dollar"></i>Pay Bills
        </a> -->
    </div>
</div>
<?php endif; ?>

</div>

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