<?php
// app/Views/admin/subscription/index.php
$now = time();
$expiryTimestamp = $gate['expiry_timestamp'] ? strtotime($gate['expiry_timestamp']) : 0;
$remainingSeconds = $expiryTimestamp - $now;
?>
<div class="space-y-8 animate-fade-in">
    <!-- Header Summary -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <h2 class="text-xl font-bold text-white">Subscription &amp; Plans</h2>
            <p class="text-slate-400 text-sm mt-1">Manage your active package, view billing history, or upgrade your subscription.</p>
        </div>
        
        <?php if ($gate['expired']): ?>
        <div class="flex items-center gap-3 px-4 py-2.5 rounded-xl border border-red-500/30 bg-red-500/10 text-red-400 animate-pulse text-sm">
            <i class="fas fa-triangle-exclamation text-base"></i>
            <div>
                <p class="font-bold leading-none">Subscription Expired</p>
                <p class="text-xs text-red-400/80 mt-0.5">Please renew your plan to restore full operations.</p>
            </div>
        </div>
        <?php else: ?>
        <div class="flex items-center gap-3 px-4 py-2.5 rounded-xl border border-emerald-500/20 bg-emerald-500/5 text-emerald-400 text-sm">
            <i class="fas fa-check-circle text-base"></i>
            <div>
                <p class="font-bold leading-none">Subscription Active</p>
                <p class="text-xs text-emerald-400/80 mt-0.5">Your restaurant operations are fully active.</p>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <?php if (!empty($pendingSub)): ?>
    <div class="flex items-center gap-3 px-5 py-4 rounded-2xl border border-yellow-500/30 bg-yellow-500/10 text-yellow-400 text-sm">
        <i class="fas fa-clock text-lg"></i>
        <div>
            <p class="font-bold">Subscription Plan Request Pending Approval</p>
            <p class="text-xs text-yellow-400/80 mt-0.5">Your request for plan <strong><?php echo htmlspecialchars($pendingSub['package_name']); ?></strong> is currently pending approval by the Super Admin. Please wait or contact support.</p>
        </div>
    </div>
    <?php endif; ?>

    <!-- Overview Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-5">
        <!-- Plan Name -->
        <div class="rounded-2xl p-5 border border-white/5 relative overflow-hidden" style="background: rgba(255,255,255,0.03);">
            <p class="text-slate-500 text-xs font-semibold uppercase tracking-wider">Current Package</p>
            <p class="text-2xl font-bold text-white mt-2"><?php echo htmlspecialchars($gate['package_name'] ?? 'No Package'); ?></p>
            <span class="absolute bottom-4 right-4 text-3xl opacity-10 text-emerald-400"><i class="fas fa-box-open"></i></span>
        </div>

        <!-- Expiry Date -->
        <div class="rounded-2xl p-5 border border-white/5 relative overflow-hidden" style="background: rgba(255,255,255,0.03);">
            <p class="text-slate-500 text-xs font-semibold uppercase tracking-wider">Expiry Date</p>
            <p class="text-2xl font-bold text-white mt-2">
                <?php echo $gate['expiry_date'] ? date('M d, Y', strtotime($gate['expiry_date'])) : 'Never'; ?>
            </p>
            <span class="absolute bottom-4 right-4 text-3xl opacity-10 text-blue-400"><i class="fas fa-calendar-days"></i></span>
        </div>

        <!-- Days Left -->
        <div class="rounded-2xl p-5 border border-white/5 relative overflow-hidden" style="background: rgba(255,255,255,0.03);">
            <p class="text-slate-500 text-xs font-semibold uppercase tracking-wider">Time Remaining</p>
            <p id="countdown-timer" class="text-2xl font-bold mt-2 transition-colors duration-300">
                <?php 
                if ($gate['expired']) {
                    echo '<span class="text-red-400 font-extrabold flex items-center gap-1.5"><i class="fas fa-circle-exclamation text-sm"></i> Expired</span>';
                } else {
                    echo '<span class="text-emerald-400 font-extrabold">' . ($gate['days_left'] ?? 0) . '</span><span class="text-slate-400 text-sm font-semibold mr-1">d left</span>';
                }
                ?>
            </p>
            <span class="absolute bottom-4 right-4 text-3xl opacity-10 text-purple-400"><i class="fas fa-clock"></i></span>
        </div>

        <!-- Limits Quota Summary -->
        <div class="rounded-2xl p-5 border border-white/5 relative overflow-hidden" style="background: rgba(255,255,255,0.03);">
            <p class="text-slate-500 text-xs font-semibold uppercase tracking-wider">Account Quotas</p>
            <div class="mt-2.5 space-y-1 text-xs text-slate-300">
                <div class="flex justify-between">
                    <span>Floors:</span>
                    <span class="font-bold text-white"><?php echo $gate['features']['max_floors'] === null ? 'Unlimited' : $gate['features']['max_floors']; ?></span>
                </div>
                <div class="flex justify-between">
                    <span>Tables:</span>
                    <span class="font-bold text-white"><?php echo $gate['features']['max_tables'] === null ? 'Unlimited' : $gate['features']['max_tables']; ?></span>
                </div>
            </div>
            <span class="absolute bottom-4 right-4 text-3xl opacity-10 text-amber-500"><i class="fas fa-chart-pie"></i></span>
        </div>
    </div>

    <!-- Plan Renewal / Packages Options -->
    <div class="space-y-4">
        <div class="border-b border-white/5 pb-2">
            <h3 class="text-lg font-bold text-white flex items-center gap-2"><i class="fas fa-circle-nodes text-emerald-400"></i> Purchase / Renew Subscription</h3>
            <p class="text-xs text-slate-400">Select any standard monthly plan below. Upgrades and downgrades take effect immediately.</p>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            <?php foreach ($packages as $pkg): 
                $pkgFeatures = json_decode($pkg['features'], true) ?: [];
                $nameLower = strtolower($pkg['name']);
                
                // Active status check helper
                $isCurrentPlan = ($gate['package_name'] === $pkg['name']);
                
                // Color configuration matching packages names
                if (str_contains($nameLower, 'premium')) {
                    $borderStyle = 'border-color: rgba(59,130,246,0.3);';
                    $accentBg = 'background: rgba(59,130,246,0.08);';
                    $btnStyle = 'background: linear-gradient(135deg,#3b82f6,#2563eb);';
                    $colorClass = 'text-blue-400';
                    $ringClass = 'ring-2 ring-blue-500/50 shadow-lg shadow-blue-500/25 scale-[1.02]';
                } elseif (str_contains($nameLower, 'advanced') || str_contains($nameLower, 'pro')) {
                    $borderStyle = 'border-color: rgba(16,185,129,0.3);';
                    $accentBg = 'background: rgba(16,185,129,0.08);';
                    $btnStyle = 'background: linear-gradient(135deg,#10b981,#059669);';
                    $colorClass = 'text-emerald-400';
                    $ringClass = 'ring-2 ring-emerald-500/50 shadow-lg shadow-emerald-500/25 scale-[1.02]';
                } else {
                    $borderStyle = 'border-color: rgba(139,92,246,0.3);';
                    $accentBg = 'background: rgba(139,92,246,0.08);';
                    $btnStyle = 'background: linear-gradient(135deg,#8b5cf6,#7c3aed);';
                    $colorClass = 'text-purple-400';
                    $ringClass = 'ring-2 ring-purple-500/50 shadow-lg shadow-purple-500/25 scale-[1.02]';
                }
            ?>
            <div class="rounded-2xl border flex flex-col transition-all duration-200 hover:-translate-y-1 hover:shadow-xl <?php echo $isCurrentPlan ? $ringClass : ''; ?>" style="background: rgba(255,255,255,0.02); <?php echo $borderStyle; ?>">
                <!-- Header -->
                <div class="p-6 pb-4 border-b border-white/5 relative">
                    <?php if ($isCurrentPlan): ?>
                    <span class="absolute top-4 right-4 text-2xs font-extrabold uppercase tracking-wide px-2.5 py-1 rounded-full bg-emerald-500/15 border border-emerald-500/30 text-emerald-400">Current Plan</span>
                    <?php endif; ?>
                    <span class="text-xs font-bold uppercase tracking-wider px-3 py-1 rounded-md" style="<?php echo $accentBg; ?>; color: currentColor;"><?php echo htmlspecialchars($pkg['name']); ?></span>
                    <div class="mt-4">
                        <span class="text-3xl font-extrabold text-white"><?php echo htmlspecialchars($pkg['currency'] ?? '$'); ?><?php echo number_format($pkg['price'], 2); ?></span>
                        <span class="text-slate-500 text-xs ml-1">/ <?php echo $pkg['duration_days']; ?> days</span>
                    </div>
                </div>

                <!-- Features list -->
                <div class="p-6 flex-1 space-y-4">
                    <ul class="space-y-2.5 text-xs">
                        <li class="flex items-center justify-between">
                            <span class="text-slate-400"><i class="fas fa-building w-4 text-center mr-1"></i> Max Floors</span>
                            <span class="font-bold text-white"><?php echo $pkgFeatures['max_floors'] === null ? 'Unlimited' : $pkgFeatures['max_floors']; ?></span>
                        </li>
                        <li class="flex items-center justify-between">
                            <span class="text-slate-400"><i class="fas fa-chair w-4 text-center mr-1"></i> Max Tables</span>
                            <span class="font-bold text-white"><?php echo $pkgFeatures['max_tables'] === null ? 'Unlimited' : $pkgFeatures['max_tables']; ?></span>
                        </li>
                        <li class="flex items-center justify-between">
                            <span class="text-slate-400"><i class="fas fa-cash-register w-4 text-center mr-1"></i> Max Cashiers</span>
                            <span class="font-bold text-white"><?php echo $pkgFeatures['max_cashiers'] === null ? 'Unlimited' : $pkgFeatures['max_cashiers']; ?></span>
                        </li>
                        <li class="flex items-center justify-between">
                            <span class="text-slate-400"><i class="fas fa-user-tie w-4 text-center mr-1"></i> Max Waiters</span>
                            <span class="font-bold text-white"><?php echo $pkgFeatures['max_waiters'] === null ? 'Unlimited' : $pkgFeatures['max_waiters']; ?></span>
                        </li>
                        <li class="flex items-center justify-between border-t border-white/5 pt-2.5">
                            <span class="text-slate-400"><i class="fas fa-qrcode w-4 text-center mr-1"></i> QR Table Ordering</span>
                            <span>
                                <?php if (!empty($pkgFeatures['qr_ordering'])): ?>
                                <i class="fas fa-circle-check text-emerald-400"></i>
                                <?php else: ?>
                                <i class="fas fa-circle-xmark text-red-500/50"></i>
                                <?php endif; ?>
                            </span>
                        </li>
                        <li class="flex items-center justify-between">
                            <span class="text-slate-400"><i class="fas fa-tv w-4 text-center mr-1"></i> Kitchen Display System</span>
                            <span>
                                <?php if (!empty($pkgFeatures['kitchen_display'])): ?>
                                <i class="fas fa-circle-check text-emerald-400"></i>
                                <?php else: ?>
                                <i class="fas fa-circle-xmark text-red-500/50"></i>
                                <?php endif; ?>
                            </span>
                        </li>
                        <li class="flex items-center justify-between">
                            <span class="text-slate-400"><i class="fas fa-boxes w-4 text-center mr-1"></i> Inventory Management</span>
                            <span>
                                <?php if (!empty($pkgFeatures['inventory'])): ?>
                                <i class="fas fa-circle-check text-emerald-400"></i>
                                <?php else: ?>
                                <i class="fas fa-circle-xmark text-red-500/50"></i>
                                <?php endif; ?>
                            </span>
                        </li>
                        <li class="flex items-center justify-between">
                            <span class="text-slate-400"><i class="fas fa-users-cog w-4 text-center mr-1"></i> Staff Management</span>
                            <span>
                                <?php if (!empty($pkgFeatures['staff_management'])): ?>
                                <i class="fas fa-circle-check text-emerald-400"></i>
                                <?php else: ?>
                                <i class="fas fa-circle-xmark text-red-500/50"></i>
                                <?php endif; ?>
                            </span>
                        </li>
                    </ul>
                </div>

                <!-- Footer CTA -->
                <div class="p-6 pt-0 mt-auto">
                    <form action="/admin/subscription/purchase" method="POST">
                        <input type="hidden" name="package_id" value="<?php echo $pkg['id']; ?>">
                        <button type="submit" class="w-full py-2.5 px-4 rounded-xl text-xs font-semibold text-white hover:brightness-110 active:scale-[0.98] transition shadow-md shadow-black/25 flex items-center justify-center gap-1.5" style="<?php echo $btnStyle; ?>">
                            <i class="fas fa-cart-shopping text-xs"></i> 
                            <?php echo $isCurrentPlan ? 'Renew Current Plan' : 'Purchase / Change Plan'; ?>
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Subscription History Table -->
    <div class="space-y-4 pt-4">
        <div class="border-b border-white/5 pb-2">
            <h3 class="text-lg font-bold text-white flex items-center gap-2"><i class="fas fa-history text-purple-400"></i> Billing &amp; Subscription History</h3>
            <p class="text-xs text-slate-400 font-medium">Review your historical billing purchases and renewals.</p>
        </div>

        <div class="rounded-2xl overflow-hidden border border-white/5" style="background: rgba(255,255,255,0.02);">
            <div class="overflow-x-auto">
                <table class="w-full text-xs">
                    <thead>
                        <tr class="border-b border-white/5" style="background: rgba(255,255,255,0.015);">
                            <th class="text-left px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Package</th>
                            <th class="text-left px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Purchase Date</th>
                            <th class="text-left px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Duration</th>
                            <th class="text-left px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Amount Paid</th>
                            <th class="text-left px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Status</th>
                            <th class="text-right px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-white/5">
                        <?php if (empty($history)): ?>
                        <tr>
                            <td colspan="6" class="px-5 py-10 text-center text-slate-500 font-medium">No subscription transaction history recorded.</td>
                        </tr>
                        <?php endif; ?>
                        <?php foreach ($history as $h): 
                            $statusStyle = '';
                            if ($h['status'] === 'active') {
                                $statusStyle = 'background: rgba(16,185,129,0.15); color: #6ee7b7; border-color: rgba(16,185,129,0.25);';
                            } elseif ($h['status'] === 'expired') {
                                $statusStyle = 'background: rgba(239,68,68,0.15); color: #fca5a5; border-color: rgba(239,68,68,0.25);';
                            } elseif ($h['status'] === 'pending') {
                                $statusStyle = 'background: rgba(234,179,8,0.15); color: #facc15; border-color: rgba(234,179,8,0.25);';
                            } else {
                                $statusStyle = 'background: rgba(255,255,255,0.06); color: #94a3b8; border-color: rgba(255,255,255,0.1);';
                            }
                        ?>
                        <tr class="hover:bg-white/[0.015] transition">
                            <td class="px-5 py-3.5 font-semibold text-white">
                                <?php echo htmlspecialchars($h['package_name']); ?>
                            </td>
                            <td class="px-5 py-3.5 text-slate-300">
                                <?php echo date('M d, Y', strtotime($h['start_date'])); ?>
                            </td>
                            <td class="px-5 py-3.5 text-slate-400">
                                <?php echo date('M d, Y', strtotime($h['start_date'])) . ' — ' . date('M d, Y', strtotime($h['end_date'])); ?>
                            </td>
                            <td class="px-5 py-3.5 font-bold text-white">
                                <?php echo htmlspecialchars($gate['currency'] ?? '$') . number_format($h['amount'], 2); ?>
                            </td>
                            <td class="px-5 py-3.5">
                                <span class="px-2.5 py-1 rounded-full text-3xs font-extrabold uppercase border" style="<?php echo $statusStyle; ?>">
                                    <?php echo htmlspecialchars($h['status']); ?>
                                </span>
                            </td>
                            <td class="px-5 py-3.5 text-right">
                                <a href="/admin/subscription/invoice?id=<?php echo $h['id']; ?>" target="_blank" class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-slate-400 hover:text-white bg-white/5 hover:bg-white/10 border border-white/10 transition font-semibold">
                                    <i class="fas fa-file-invoice text-xs"></i> Invoice
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <div class="px-5 py-3 border-t border-white/5 flex justify-end">
                <a href="/admin/subscription/invoices" class="text-xs font-semibold text-purple-400 hover:text-purple-300 transition flex items-center gap-1">
                    View All Invoices <i class="fas fa-chevron-right text-3xs"></i>
                </a>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    let remainingSeconds = <?php echo json_encode($remainingSeconds); ?>;
    const timerEl = document.getElementById('countdown-timer');

    if (!timerEl) return;

    function updateTimer() {
        if (remainingSeconds <= 0) {
            timerEl.innerHTML = '<span class="text-red-400 font-extrabold flex items-center gap-1.5"><i class="fas fa-circle-exclamation text-sm"></i> Expired</span>';
            return;
        }

        const days = Math.floor(remainingSeconds / 86400);
        const hours = Math.floor((remainingSeconds % 86400) / 3600);
        const minutes = Math.floor((remainingSeconds % 3600) / 60);
        const seconds = remainingSeconds % 60;

        let displayStr = '';
        if (days > 0) displayStr += `<span class="text-emerald-400 font-extrabold">${days}</span><span class="text-slate-400 text-sm font-semibold mr-1">d </span>`;
        if (days > 0 || hours > 0) displayStr += `<span class="text-emerald-400 font-extrabold">${hours}</span><span class="text-slate-400 text-sm font-semibold mr-1">h </span>`;
        if (days > 0 || hours > 0 || minutes > 0) displayStr += `<span class="text-emerald-400 font-extrabold">${minutes}</span><span class="text-slate-400 text-sm font-semibold mr-1">m </span>`;
        displayStr += `<span class="text-emerald-400 font-extrabold">${seconds}</span><span class="text-slate-400 text-sm font-semibold">s</span>`;

        timerEl.innerHTML = displayStr;
        remainingSeconds--;
    }

    updateTimer();
    const interval = setInterval(() => {
        updateTimer();
        if (remainingSeconds < 0) {
            clearInterval(interval);
        }
    }, 1000);
});
</script>
