<?php
session_start();
require_once(__DIR__ . '/../includes/db.php');

/* -------------------------------
   User Authentication
-------------------------------- */
if (!isset($_SESSION['user_id'])) {
    header("Location: userlogin.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];

/* -------------------------------
   Fetch User's Approved Hosting Plans
-------------------------------- */
$sql = "SELECT 
            id,
            plan_name,
            domain_name,
            total_disk_space,
            bandwidth_usage,
            server_location,
            activated_at,
            expiry_date
        FROM hosting_plans 
        WHERE user_id = ? AND payment_status='approved'
        ORDER BY expiry_date ASC";

$stmt = $conn->prepare($sql);
if ($stmt === false) {
    die("SQL Prepare Failed: " . $conn->error);
}
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

/* -------------------------------
   Layout
-------------------------------- */
include(__DIR__ . '/../includes/header.php');
include(__DIR__ . '/../includes/navbar.php');
?>

<main class="content">
<div class="topbar mb-4">
    <h4 class="fw-bold">My Hosting Plans</h4>
    <p class="text-muted mb-0">View your active & expired hosting services</p>
</div>

<section class="section">
<div class="card shadow-sm border-0 p-3">

<?php if ($result->num_rows > 0): ?>
    <div class="table-responsive">
        <table class="table table-bordered align-middle text-center">
            <thead class="table-dark">
                <tr>
                    <th>#</th>
                    <th>Plan Name</th>
                    <th>Domain</th>
                    <th>Disk Space</th>
                    <th>Bandwidth</th>
                    <th>Server Location</th>
                    <th>Activated At</th>
                    <th>Expiry Date</th>
                    <th>Days Left</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; ?>
                <?php while ($row = $result->fetch_assoc()): ?>

                    <?php
                    $expiry_ts = strtotime($row['expiry_date']);
                    $today_ts  = strtotime(date('Y-m-d'));
                    $days_left = floor(($expiry_ts - $today_ts) / 86400);

                    if ($days_left <= 0) {
                        $days_left = 0;
                        $status_badge = '<span class="badge bg-danger">Expired</span>';
                    } else {
                        $status_badge = '<span class="badge bg-success">Active</span>';
                    }
                    ?>

                    <tr>
                        <td><?= $i++; ?></td>
                        <td class="fw-semibold"><?= htmlspecialchars($row['plan_name']); ?></td>
                        <td><?= htmlspecialchars($row['domain_name']); ?></td>
                        <td><?= htmlspecialchars($row['total_disk_space']); ?></td>
                        <td><?= htmlspecialchars($row['bandwidth_usage']); ?></td>
                        <td><?= htmlspecialchars($row['server_location']); ?></td>
                        <td><?= $row['activated_at'] ? date('d M Y', strtotime($row['activated_at'])) : '—'; ?></td>
                        <td><?= $row['expiry_date'] ? date('d M Y', $expiry_ts) : '—'; ?></td>
                        <!-- Days Left with data-expiry attribute for JS countdown -->
                        <td class="days-left" data-expiry="<?= $row['expiry_date']; ?>">
                            <?php if ($days_left > 0): ?>
                                <span class="text-success fw-bold"><?= $days_left; ?> days</span>
                            <?php else: ?>
                                <span class="text-danger fw-bold">Expired</span>
                            <?php endif; ?>
                        </td>
                        <td><?= $status_badge; ?></td>
                    </tr>

                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
<?php else: ?>
    <div class="text-center py-4">
        <i class="bi bi-hdd-network fs-1 text-muted"></i>
        <p class="mt-2 mb-0 text-muted">No approved hosting plans found.</p>
    </div>
<?php endif; ?>

</div>
</section>
</main>

<?php
include(__DIR__ . '/../includes/footer.php');
include(__DIR__ . '/../includes/scripts.php');
?>

<!-- ===========================
     Live Countdown Script
=========================== -->
<script>
// Update countdown for all Days Left cells
function updateCountdowns() {
    const rows = document.querySelectorAll('.days-left');
    const now = new Date();

    rows.forEach(td => {
        const expiryStr = td.dataset.expiry;
        if (!expiryStr) return;

        const expiryDate = new Date(expiryStr + 'T23:59:59'); // End of day
        let diff = expiryDate - now;

        if (diff <= 0) {
            td.innerHTML = '<span class="text-danger fw-bold">Expired</span>';
        } else {
            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
            const minutes = Math.floor((diff / (1000 * 60)) % 60);
            const seconds = Math.floor((diff / 1000) % 60);

            td.innerHTML = `<span class="text-success fw-bold">${days}d ${hours}h ${minutes}m ${seconds}s</span>`;
        }
    });
}

// Initial call & update every second
updateCountdowns();
setInterval(updateCountdowns, 1000);
</script>
