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

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

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

/* Fetch existing 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);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

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

<main class="content container my-5">
    <div class="text-center mb-5">
        <h2 class="fw-bold text-primary">Update or Renew Your Hosting Plan</h2>
        <p class="text-muted">Select a plan from your existing plans or choose a new one</p>
    </div>

    <!-- Existing Plans Table -->
    <div class="card shadow-sm border-0 mb-5">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0">Your Existing Hosting Plans</h5>
        </div>
        <div class="card-body p-0">
            <?php if ($result->num_rows > 0): ?>
            <div class="table-responsive">
                <table class="table table-striped table-hover align-middle text-center mb-0">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>Plan Name</th>
                            <th>Domain</th>
                            <th>Disk Space</th>
                            <th>Bandwidth</th>
                            <th>Server</th>
                            <th>Activated</th>
                            <th>Expiry</th>
                            <th>Days Left</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $i = 1;
                        while ($row = $result->fetch_assoc()): 
                            $expiry_ts = strtotime($row['expiry_date']);
                            $today_ts  = strtotime(date('Y-m-d'));
                            $days_left = floor(($expiry_ts - $today_ts) / 86400);
                            $status_badge = ($days_left > 0) ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Expired</span>';
                        ?>
                        <tr>
                            <td>
                                <?= $i++; ?>
                            </td>
                            <td>
                                <?= 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>
                            <td>
                                <?= ($days_left>0)? "$days_left days":"Expired"; ?>
                            </td>
                            <td>
                                <?= $status_badge; ?>
                            </td>
                            <td>
                                <!-- Directly go to payment.php with the selected plan -->
                                <a href="payment.php?plan=<?= urlencode($row['plan_name']); ?>"
                                    class="btn btn-sm btn-primary">
                                    Renew
                                </a>
                            </td>

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

    <!-- Hosting Plan Cards -->
    <div class="row g-4">
        <?php
        $plans = [
            ["name"=>"Single Domain Plan","old"=>"999","new"=>"550","best"=>"Personal Website, Portfolio","features"=>["Up to 1 Domain","2 Email Accounts","100 GB NVMe SSD","1 GB RAM","2000 MB Email Space / ID","Unlimited Bandwidth","Unlimited Subdomains","cPanel Control Panel","Free SSL Certificate","WordPress 1-Click Install","99.9% Uptime Guarantee","24×7 Technical Support"]],
            ["name"=>"Double Domain Plan","old"=>"1299","new"=>"750","best"=>"Small Businesses","features"=>["Up to 2 Domains","5 Email Accounts","100 GB NVMe SSD","1 GB RAM","2000 MB Email Space / ID","Unlimited Bandwidth","Unlimited Subdomains","cPanel Control Panel","Free SSL Certificate","WordPress 1-Click Install","99.9% Uptime Guarantee","24×7 Technical Support"]],
            ["name"=>"5 Domain Plan","old"=>"1999","new"=>"1050","best"=>"Agencies, Growing Businesses","features"=>["Up to 5 Domains","20 Email Accounts","100 GB NVMe SSD","2 GB RAM","5000 MB Email Space / ID","Unlimited Bandwidth","Unlimited Subdomains","cPanel Control Panel","Free SSL Certificate","WordPress 1-Click Install","Weekly Backups","99.9% Uptime Guarantee","Priority Support"]],
            ["name"=>"10 Domain Plan","old"=>"2999","new"=>"1450","best"=>"Developers, Agencies","features"=>["Up to 10 Domains","Unlimited Email Accounts","Unlimited NVMe SSD Space","3 GB RAM","5000 MB Email Space / ID","Unlimited Bandwidth","Unlimited Subdomains","cPanel Control Panel","Free SSL Certificate","WordPress 1-Click Install","SSH / Terminal Access","Daily Backups","99.99% Uptime Guarantee","Priority Support"]],
            ["name"=>"20 Domains Plan","old"=>"3500","new"=>"1850","best"=>"Small Agencies, Growing Businesses","features"=>["Up to 20 Domains","Unlimited Email Accounts","Unlimited NVMe SSD Space","3 GB RAM","5000 MB Email Space / ID","Unlimited Bandwidth","Unlimited Subdomains","cPanel Control Panel","Free SSL Certificate","WordPress 1-Click Install","SSH / Terminal Access","Daily Backups","99.99% Uptime Guarantee","Priority Support"]],
            ["name"=>"Unlimited Domain Plan","old"=>"4999","new"=>"2050","best"=>"Hosting Resellers, High-Traffic Websites","features"=>["Unlimited Websites / Domains","Unlimited NVMe SSD Space","Unlimited Bandwidth","Unlimited Email Accounts","Unlimited Subdomains","High-Performance RAM & CPU","cPanel Control Panel","Free SSL Certificate (Auto-Renew)","WordPress 1-Click Install","SSH / Terminal Access","Daily Automated Backups","Advanced Security & Firewall","99.99% Uptime Guarantee","Premium 24×7 Support"]]
        ];

        foreach($plans as $p): ?>
        <div class="col-md-6 col-lg-4">
            <div class="card h-100 shadow-sm border-0 plan-card" data-plan="<?= $p['name']; ?>">
                <div class="card-header bg-warning text-dark text-center">
                    <h5 class="mb-0">
                        <?= $p['name']; ?>
                    </h5>
                </div>
                <div class="card-body d-flex flex-column">
                    <p class="old-price text-decoration-line-through text-muted mb-1">₹
                        <?= $p['old']; ?> / Year
                    </p>
                    <p class="new-price fw-bold fs-5 mb-3">₹
                        <?= $p['new']; ?> / Year
                    </p>
                    <ul class="list-unstyled mb-3 small">
                        <?php foreach($p['features'] as $f): ?>
                        <li class="mb-1"><i class="fa-solid fa-circle-check text-success me-2"></i>
                            <?= $f; ?>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <p class="text-center fw-semibold text-primary mb-3">Best for:
                        <?= $p['best']; ?>
                    </p>
                    <a href="payment.php?plan=<?= urlencode($p['name']); ?>&price=<?= $p['new']; ?>"
                        class="btn btn-primary w-100 mt-auto">
                        Update / Order Plan
                    </a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</main>

<!-- MODALS -->
<!-- Choose Existing / New -->
<div class="modal fade" id="chooseUserModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content p-3">
            <h5 class="mb-3 text-center">Proceed as:</h5>
            <button id="existingUserBtn" class="btn btn-success w-100 mb-2">Existing User</button>
            <button id="newUserBtn" class="btn btn-primary w-100">New User</button>
        </div>
    </div>
</div>

<!-- New User Registration -->
<div class="modal fade" id="newUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content p-4">
            <h5 class="mb-3 text-center">Register New Account</h5>
            <form id="newUserForm">
                <input type="hidden" name="plan_name" id="selectedPlan" value="">
                <div class="mb-2"><input type="text" name="name" class="form-control" placeholder="Full Name" required>
                </div>
                <div class="mb-2"><input type="email" name="email" class="form-control" placeholder="Email" required>
                </div>
                <div class="mb-2"><input type="text" name="mobile" class="form-control" placeholder="Mobile Number"
                        required></div>
                <div class="mb-2"><input type="text" name="domain_name" class="form-control" placeholder="Domain Name"
                        required></div>
                <button type="submit" class="btn btn-primary w-100">Register & Pay</button>
            </form>
        </div>
    </div>
</div>

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

<script>
    document.addEventListener('DOMContentLoaded', function () {

        // Plan table & card buttons
        document.querySelectorAll('.update-plan-btn, .plan-order-btn').forEach(btn => {
            btn.addEventListener('click', function () {
                const planName = this.closest('.plan-card') ? this.closest('.plan-card').dataset.plan : this.dataset.plan;
                document.getElementById('selectedPlan').value = planName;
                new bootstrap.Modal(document.getElementById('chooseUserModal')).show();
            });
        });

        // Existing User → payment
        document.getElementById('existingUserBtn').addEventListener('click', function () {
            const planName = document.getElementById('selectedPlan').value;
            window.location.href = 'payment.php?plan=' + encodeURIComponent(planName);
        });

        // New User → show registration modal
        document.getElementById('newUserBtn').addEventListener('click', function () {
            bootstrap.Modal.getInstance(document.getElementById('chooseUserModal')).hide();
            new bootstrap.Modal(document.getElementById('newUserModal')).show();
        });

        // Submit new user form → register then go to payment
        document.getElementById('newUserForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const formData = new FormData(this);
            fetch('register_and_pay.php', {
                method: 'POST',
                body: formData
            }).then(res => res.json()).then(data => {
                if (data.status === 'success') {
                    window.location.href = 'payment.php?plan=' + encodeURIComponent(formData.get('plan_name')) + '&user_id=' + data.user_id;
                } else {
                    alert(data.message);
                }
            }).catch(err => console.error(err));
        });

    });
</script>

<style>
    .plan-card:hover {
        transform: translateY(-5px);
        transition: 0.3s;
    }

    .old-price {
        font-size: 0.9rem;
    }

    .new-price {
        font-size: 1.25rem;
        color: #d63384;
    }

    .table-hover tbody tr:hover {
        background-color: #f8f9fa;
    }
</style>