<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
requireLogin();

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

$plans = getPlans();
$isExpired = strtotime($user['plan_expires_at']) <= time();
$planExpiresAt = strtotime($user['plan_expires_at']);
$secondsRemaining = max(0, $planExpiresAt - time());

$pageTitle = 'Plans';
$activeNav = 'plans';
include __DIR__ . '/includes/user_header.php';
?>

<div class="page-head">
  <h1 class="page-title">Plans</h1>
  <p class="page-sub">Pick a plan, pay via UPI QR, and your API stays live for the selected duration.</p>
</div>

<div class="card">
  <div class="justify-between flex flex-wrap items-center" style="gap:16px;">
    <div>
      <h2 class="card-title">Your current plan</h2>
      <div class="card-sub" style="margin-bottom:0;"><?= htmlspecialchars($user['plan_label']) ?> &nbsp;·&nbsp; Valid until <?= date('d M Y, h:i A', $planExpiresAt) ?></div>
    </div>
    <span class="timer <?= $isExpired ? 'expired' : '' ?>" id="expiryTimer" data-seconds="<?= $secondsRemaining ?>">
      <?= $isExpired ? 'Expired' : 'Calculating…' ?>
    </span>
  </div>
</div>

<div class="pricing-grid">
  <?php foreach ($plans as $plan): ?>
    <div class="pricing-card <?= $plan['offer'] ? 'featured' : '' ?>">
      <?php if ($plan['offer']): ?><div class="badge badge-blue" style="align-self:flex-start; margin-bottom:12px;">Popular</div><?php endif; ?>
      <div class="price-label"><?= htmlspecialchars($plan['label']) ?></div>
      <div class="price-row">
        <span class="price">₹<?= (int)$plan['price'] ?></span>
        <?php if (!empty($plan['original_price'])): ?>
          <span class="price-strike">₹<?= (int)$plan['original_price'] ?></span>
        <?php endif; ?>
      </div>
      <ul class="check-list">
        <li><?= (int)$plan['days'] ?> days of API access</li>
        <li>Instant activation after payment</li>
      </ul>
      <button class="btn <?= $plan['offer'] ? 'btn-primary' : 'btn-outline' ?> btn-block" onclick="openPlanModal('<?= htmlspecialchars($plan['id']) ?>', '<?= (int)$plan['price'] ?>')">
        Select plan
      </button>
    </div>
  <?php endforeach; ?>
</div>

<!-- Plan purchase QR modal -->
<div class="modal-overlay" id="planModal">
  <div class="modal">
    <div class="modal-title">Pay for your plan</div>
    <div class="modal-price" id="planModalPrice">₹0</div>
    <div class="qr-frame"><img id="planQrImage" src="" alt="QR Code"></div>
    <div class="qr-hint">Scan with any UPI app</div>
    <div class="modal-status" id="planModalStatus">Generating QR…</div>
    <span class="modal-close" onclick="closePlanModal()">Cancel</span>
  </div>
</div>

<script>
    let planPollInterval = null;

    function openPlanModal(planId, price) {
        document.getElementById('planModalPrice').innerText = '₹' + price;
        document.getElementById('planModalStatus').innerText = 'Generating QR…';
        document.getElementById('planModalStatus').classList.remove('success');
        document.getElementById('planModal').classList.add('active');

        encryptedFetch('api/create_plan_order.php', { plan_id: planId })
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('planQrImage').src = data.data.qr_url;
                    document.getElementById('planModalStatus').innerText = 'Waiting for payment…';
                    pollPlanOrder(data.data.order_id);
                } else {
                    document.getElementById('planModalStatus').innerText = '⚠ ' + (data.message || 'Could not generate QR');
                }
            })
            .catch(() => {
                document.getElementById('planModalStatus').innerText = 'Connection error';
            });
    }

    function pollPlanOrder(orderId) {
        if (planPollInterval) clearInterval(planPollInterval);
        planPollInterval = setInterval(() => {
            encryptedFetch('api/check_plan_order.php', { order_id: orderId })
                .then(data => {
                    if (data.status === 'success') {
                    clearInterval(planPollInterval);
                    window.location.href = 'payment_success.php?order_id=' + encodeURIComponent(orderId);
                } else if (data.status === 'error') {
                        document.getElementById('planModalStatus').innerText = '⚠ ' + data.message;
                    }
                })
                .catch(() => {});
        }, 1200);
    }

    function closePlanModal() {
        document.getElementById('planModal').classList.remove('active');
        if (planPollInterval) clearInterval(planPollInterval);
    }

    document.getElementById('planModal').addEventListener('click', function(e) {
        if (e.target === this) closePlanModal();
    });

    (function() {
        const timerEl = document.getElementById('expiryTimer');
        if (!timerEl) return;
        let seconds = parseInt(timerEl.dataset.seconds, 10);
        if (seconds <= 0) return;

        function formatTime(s) {
            const d = Math.floor(s / 86400);
            const h = Math.floor((s % 86400) / 3600);
            const m = Math.floor((s % 3600) / 60);
            const sec = s % 60;
            if (d > 0) return `${d}d ${h}h ${m}m remaining`;
            if (h > 0) return `${h}h ${m}m ${sec}s remaining`;
            return `${m}m ${sec}s remaining`;
        }

        const interval = setInterval(() => {
            seconds--;
            if (seconds <= 0) {
                timerEl.innerText = 'Expired';
                timerEl.classList.add('expired');
                clearInterval(interval);
                return;
            }
            timerEl.innerText = formatTime(seconds);
        }, 1000);
        timerEl.innerText = formatTime(seconds);
    })();
</script>

<?php include __DIR__ . '/includes/user_footer.php'; ?>
