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

// ── Fetch orders from all servers ────────────────────────────────
$all_numbers = [];

// Server 1 & 2 (active_number table — original S1/S2 system)
try {
    $stmt = $pdo->prepare(
        "SELECT id, user_id, number, service_name, service_price AS our_price, status, sms_text AS sms_code, '' AS sms_full_msg, buy_time AS created_at, provider,
                CASE WHEN provider = 'smspva' THEN 'server1' ELSE 'server2' END AS server_label
         FROM active_number WHERE user_id = :uid ORDER BY buy_time DESC"
    );
    $stmt->execute(['uid' => $user['id']]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) {
        // Map active_number status: 1=received, 2=waiting, 3=cancelled/refunded
        $s = $r['status'];
        if ($s == '1' || (!empty($r['sms_code']) && $r['sms_code'] !== '')) $r['status'] = 'received';
        elseif ($s == '2') $r['status'] = 'waiting';
        elseif ($s == '3') $r['status'] = 'cancelled';
        else $r['status'] = 'waiting';
        $r['provider'] = 'server12';
        $r['country_name'] = '';
        $all_numbers[] = $r;
    }
} catch (PDOException $e) {}

// Server 1 & 2 (smsman_orders — newer smsman system, if used)
try {
    $stmt = $pdo->prepare(
        "SELECT id, user_id, number, country_name, app_name AS service_name, our_price, status, sms_code, sms_full_msg, created_at, 'smsman' AS provider
         FROM smsman_orders WHERE user_id = :uid ORDER BY created_at DESC"
    );
    $stmt->execute(['uid' => $user['id']]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) $all_numbers[] = $r;
} catch (PDOException $e) {}

// Server 3 (fivesim_orders)
try {
    $stmt = $pdo->prepare(
        "SELECT id, user_id, phone AS number, country_name, product AS service_name, our_price, status, sms_code, sms_text AS sms_full_msg, created_at, '5sim' AS provider
         FROM fivesim_orders WHERE user_id = :uid ORDER BY created_at DESC"
    );
    $stmt->execute(['uid' => $user['id']]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) $all_numbers[] = $r;
} catch (PDOException $e) {}

// Server 4 (smsbus_orders)
try {
    $stmt = $pdo->prepare(
        "SELECT id, user_id, phone AS number, country_title AS country_name, project_title AS service_name, our_price, status, sms_code, '' AS sms_full_msg, created_at, 'smsbus' AS provider
         FROM smsbus_orders WHERE user_id = :uid ORDER BY created_at DESC"
    );
    $stmt->execute(['uid' => $user['id']]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as $r) $all_numbers[] = $r;
} catch (PDOException $e) {}

// Sort all by created_at descending
usort($all_numbers, function($a, $b) {
    return strtotime($b['created_at']) - strtotime($a['created_at']);
});

// Stats
$total_numbers = count($all_numbers);
$total_spent = 0;
$received_count = 0;
$cancelled_count = 0;
foreach ($all_numbers as $n) {
    $total_spent += (float)$n['our_price'];
    if ($n['status'] === 'received' || $n['status'] === 'finished') $received_count++;
    if (in_array($n['status'], ['cancelled', 'timeout', 'expired'])) $cancelled_count++;
}
?>
<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}
.num-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}
.num-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:8px}
.num-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-chip{font-size:.72rem;font-weight:600;padding:6px 14px;border-radius:99px;border:1.5px solid var(--card-border);background:var(--btn-bg);color:var(--text-muted);cursor:pointer;transition:all .2s}
.filter-chip.active{background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;border-color:transparent}
.provider-badge{font-size:.6rem;font-weight:700;padding:2px 7px;border-radius:6px;text-transform:uppercase;letter-spacing:.03em}
.provider-smsman{background:rgba(77,20,140,.08);color:#4D148C}
.provider-server12{background:rgba(77,20,140,.08);color:#4D148C}
.provider-5sim{background:rgba(77,20,140,.08);color:#4D148C}
.provider-smsbus{background:rgba(77,20,140,.08);color:#4D148C}
</style>

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

<!-- Hero -->
<div class="num-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,.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-sim-card text-emerald-300 text-base"></i>Number History
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem;">All your virtual number purchases across all servers.</p>
        </div>
        <a href="virtual-numbers" 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 text-xs"></i>Buy Number
        </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',$total_numbers,'Total'],
        ['fas fa-circle-check','rgba(16,185,129,.1)','#059669',$received_count,'Received'],
        ['fas fa-ban','rgba(100,116,139,.1)','#64748b',$cancelled_count,'Cancelled'],
        ['fas fa-naira-sign','rgba(59,130,246,.1)','#2563eb','₦'.number_format($total_spent,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:14px;">
    <button class="filter-chip active" data-filter="all">All</button>
    <button class="filter-chip" data-filter="received">Received</button>
    <button class="filter-chip" data-filter="waiting">Waiting</button>
    <button class="filter-chip" data-filter="cancelled">Cancelled</button>
    <button class="filter-chip" data-filter="server12">Server 1</button>
    <button class="filter-chip" data-filter="5sim">Server 2</button>
    <button class="filter-chip" data-filter="smsbus">Server 3</button>
</div>

<!-- Number List -->
<?php if (!empty($all_numbers)): ?>
<div class="anim anim-3" id="numbers-list">
    <?php foreach ($all_numbers as $n):
        $status = $n['status'];
        switch ($status) {
            case 'received':
            case 'finished':
                $bc='rgba(16,185,129,.08)'; $tc='#059669'; $ic='fa-circle-check'; $sl='Received'; break;
            case 'waiting':
                $bc='rgba(245,158,11,.08)'; $tc='#d97706'; $ic='fa-clock'; $sl='Waiting'; break;
            case 'cancelled':
                $bc='rgba(100,116,139,.08)'; $tc='#64748b'; $ic='fa-ban'; $sl='Cancelled'; break;
            case 'timeout':
            case 'expired':
                $bc='rgba(239,68,68,.08)'; $tc='#dc2626'; $ic='fa-clock-rotate-left'; $sl='Expired'; break;
            default:
                $bc='rgba(100,116,139,.08)'; $tc='#64748b'; $ic='fa-question'; $sl=ucfirst($status); break;
        }
        $provider = $n['provider'];
        $providerLabel = ($provider === 'server12' || $provider === 'smsman') ? 'Server 1' : ($provider === '5sim' ? 'Server 2' : 'Server 3');
        $phone = $n['number'] ? (strpos($n['number'], '+') === 0 ? $n['number'] : '+' . $n['number']) : '—';
        $sms = !empty($n['sms_code']) ? $n['sms_code'] : (!empty($n['sms_full_msg']) ? $n['sms_full_msg'] : '');
        $filterStatus = in_array($status, ['received','finished']) ? 'received' : (in_array($status, ['cancelled','timeout','expired']) ? 'cancelled' : $status);
    ?>
    <div class="num-card" data-status="<?php echo $filterStatus; ?>" data-provider="<?php echo $provider; ?>">
        <div style="display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap;">
            <!-- Left info -->
            <div style="flex:1;min-width:0;">
                <div style="display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:6px;">
                    <span class="provider-badge provider-<?php echo $provider; ?>"><?php echo $providerLabel; ?></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 $sl; ?>
                    </span>
                    <?php if (!empty($n['country_name'])): ?>
                    <span style="font-size:.65rem;color:var(--text-muted);">
                        <i class="fas fa-globe text-xs"></i> <?php echo htmlspecialchars($n['country_name']); ?>
                    </span>
                    <?php endif; ?>
                </div>
                <p style="font-weight:700;font-size:.85rem;color:var(--text-primary);margin-bottom:4px;">
                    <?php echo htmlspecialchars($n['service_name'] ?: '—'); ?>
                </p>
                <p style="font-size:.82rem;color:#4D148C;font-family:'Courier New',monospace;font-weight:700;margin-bottom:4px;">
                    <?php echo htmlspecialchars($phone); ?>
                </p>
                <?php if ($sms): ?>
                <div style="background:rgba(16,185,129,.06);border:1px solid rgba(16,185,129,.15);border-radius:8px;padding:8px 10px;margin-top:6px;">
                    <p style="font-size:.68rem;color:#059669;font-weight:600;margin-bottom:2px;">
                        <i class="fas fa-message text-xs"></i> SMS Received
                    </p>
                    <p style="font-size:.82rem;color:var(--text-primary);font-family:monospace;font-weight:700;word-break:break-all;">
                        <?php echo htmlspecialchars($sms); ?>
                    </p>
                </div>
                <?php endif; ?>
            </div>
            <!-- Right meta -->
            <div style="text-align:right;flex-shrink:0;">
                <p style="font-weight:800;font-size:1rem;color:#4D148C;font-family:monospace;">₦<?php echo number_format((float)$n['our_price'], 2); ?></p>
                <p style="font-size:.68rem;color:var(--text-muted);margin-top:3px;"><?php echo date('M d, Y', strtotime($n['created_at'])); ?></p>
                <p style="font-size:.65rem;color:var(--text-muted);"><?php echo date('h:i A', strtotime($n['created_at'])); ?></p>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php else: ?>
<div class="anim anim-3" 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-sim-card" 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 Numbers Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:280px;margin:0 auto 16px;">You haven't purchased any virtual numbers yet. Get started now!</p>
    <a href="virtual-numbers" 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-sim-card"></i>Buy First Number
    </a>
</div>
<?php endif; ?>

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

<script>
document.querySelectorAll('.filter-chip').forEach(function(chip) {
    chip.addEventListener('click', function() {
        document.querySelectorAll('.filter-chip').forEach(function(c){ c.classList.remove('active'); });
        this.classList.add('active');

        var filter = this.dataset.filter;
        var cards = document.querySelectorAll('.num-card');

        cards.forEach(function(card) {
            var status = card.dataset.status;
            var provider = card.dataset.provider;

            if (filter === 'all') {
                card.style.display = '';
            } else if (filter === 'server12') {
                card.style.display = (provider === 'server12' || provider === 'smsman') ? '' : 'none';
            } else if (filter === '5sim' || filter === 'smsbus') {
                card.style.display = (provider === filter) ? '' : 'none';
            } else {
                card.style.display = (status === filter) ? '' : 'none';
            }
        });
    });
});
</script>

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