<?php include "header.php"; ?>
<?php
// NOTE: header.php already opens <html><head>...<body> and includes config.php
// ($conn, $userdata). The previous version of this file printed a second,
// completely separate <!DOCTYPE html><head><body> here — two nested HTML
// documents on one page. Removed; we now render straight into the shared
// shell like every other admin page.
$query = $conn->query("SELECT * FROM `subscription_plan` WHERE status='Active' ORDER BY amount ASC");
$plans = [];
if ($query) { while ($r = $query->fetch_assoc()) { $plans[] = $r; } }

include_once __DIR__ . '/../includes/subscription_lib.php';
$currentSub = getActiveSubscription($conn, $userdata['id'] ?? 0);
$currentPlanId = $currentSub ? (int)$currentSub['plan_id'] : null;

// A trial plan should only ever be offered to a user once. If they've had
// any subscription (active, expired, or cancelled) against a trial plan
// before, drop trial plans from the list they see here.
$uid = (int)($userdata['id'] ?? 0);
$usedTrialRes = $conn->query("
    SELECT COUNT(*) AS c FROM user_subscriptions us
    JOIN subscription_plan sp ON sp.id = us.plan_id
    WHERE us.user_id = $uid AND sp.is_trial = 1
");
$hasUsedTrial = $usedTrialRes && (int)$usedTrialRes->fetch_assoc()['c'] > 0;
if ($hasUsedTrial) {
    $plans = array_values(array_filter($plans, function($p) { return (int)($p['is_trial'] ?? 0) === 0; }));
}

$planCount = count($plans);
// Middle plan (or the only plan) gets the "Popular" ribbon — same heuristic
// the old version used, just computed relative to how many plans exist
// instead of a hardcoded "counter == 2".
$popularIndex = $planCount >= 3 ? (int)ceil($planCount / 2) : ($planCount == 2 ? 2 : 1);
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
    :root{
        --p:#6c63ff; --p2:#e040fb;
        --g: linear-gradient(135deg,#6c63ff,#e040fb);
        --success:#43e97b; --danger:#ff6584; --warning:#f5b93b; --info:#3ea6ff;
    }
    *{box-sizing:border-box}
    html, body, .content-wrapper{ background:#0a0a12 !important; }
    body{ font-family:'Inter',sans-serif; color:#fff; }
    .content-wrapper{min-height:100vh}

    .sub-wrap{padding:20px;max-width:1200px;margin:0 auto;animation:pageIn .4s ease both}
    @keyframes pageIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}

    .sub-head{text-align:center;margin-bottom:8px}
    .sub-head h1{font-size:1.6rem;font-weight:800;margin:0 0 6px;display:flex;align-items:center;justify-content:center;gap:10px}
    .sub-head h1 .icn{
        width:38px;height:38px;border-radius:12px;background:var(--g);display:inline-flex;
        align-items:center;justify-content:center;font-size:16px;box-shadow:0 6px 18px rgba(108,99,255,.35);
    }
    .sub-head p{color:rgba(255,255,255,.45);font-size:.88rem;margin:0}

    .note-banner{
        display:flex;align-items:flex-start;gap:12px;background:rgba(255,101,132,.08);
        border:1px solid rgba(255,101,132,.25);border-left:3px solid var(--danger);
        border-radius:12px;padding:14px 16px;margin:24px 0;font-size:.84rem;color:rgba(255,255,255,.75);
    }
    .note-banner i{color:var(--danger);margin-top:2px}
    .note-banner b{color:#fff}

    .plans-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:20px;margin-top:10px}

    .plan-card{
        background:rgba(255,255,255,.04);backdrop-filter:blur(20px);
        border:1px solid rgba(255,255,255,.08);border-radius:20px;overflow:hidden;
        display:flex;flex-direction:column;transition:.3s;position:relative;
        animation:fadeUp .5s ease both;
    }
    @keyframes fadeUp{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}}
    .plan-card:hover{transform:translateY(-6px);border-color:rgba(108,99,255,.35);box-shadow:0 20px 40px rgba(0,0,0,.35)}
    .plan-card.popular{border:1.5px solid var(--p);box-shadow:0 0 0 1px rgba(108,99,255,.25),0 20px 45px rgba(108,99,255,.15)}

    .popular-ribbon{
        position:absolute;top:14px;right:-32px;background:var(--g);color:#fff;
        padding:5px 40px;transform:rotate(45deg);font-size:.68rem;font-weight:800;
        letter-spacing:.5px;text-transform:uppercase;box-shadow:0 4px 10px rgba(0,0,0,.3);
    }

    .plan-head{padding:26px 22px 20px;text-align:center;border-bottom:1px solid rgba(255,255,255,.07)}
    .plan-name{font-size:1.05rem;font-weight:700;color:#a99bff;margin-bottom:10px;text-transform:uppercase;letter-spacing:.4px}
    .plan-price{display:flex;align-items:flex-start;justify-content:center;gap:2px;font-size:2.3rem;font-weight:800;color:#fff;line-height:1;white-space:nowrap}
    .plan-price .cur{font-size:1.05rem;font-weight:700;margin-top:8px;line-height:1}
    .plan-price .amt{font-size:2.3rem;font-weight:800;line-height:1}
    .plan-duration{font-size:.8rem;color:rgba(255,255,255,.4);margin-top:6px}

    .plan-body{padding:20px 22px;flex:1}
    .feature-list{list-style:none;padding:0;margin:0}
    .feature-list li{display:flex;align-items:flex-start;gap:10px;padding:8px 0;font-size:.85rem;color:rgba(255,255,255,.75)}
    .feature-list i{color:var(--success);margin-top:2px;font-size:.8rem;flex-shrink:0}
    .feature-list b{color:#fff}

    .plan-footer{padding:18px 22px 24px}
    .btn-plan{
        width:100%;background:var(--g);border:none;color:#fff;padding:12px;border-radius:12px;
        font-size:.9rem;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;
        transition:.2s;box-shadow:0 6px 18px rgba(108,99,255,.3);
    }
    .btn-plan:hover{transform:translateY(-2px);box-shadow:0 10px 26px rgba(108,99,255,.45);color:#fff}
    .btn-plan:active{transform:translateY(0)}

    .empty-state{text-align:center;padding:60px 20px;color:rgba(255,255,255,.35)}
    .empty-state i{font-size:2.4rem;margin-bottom:14px;display:block;color:rgba(255,255,255,.15)}
    .empty-state h4{color:rgba(255,255,255,.55);font-size:1rem;margin-bottom:6px}

    @media(max-width:600px){
        .sub-wrap{padding:14px}
        .plans-grid{grid-template-columns:1fr}
    }
</style>

<div class="sub-wrap">
    <div class="sub-head">
        <h1><span class="icn"><i class="fas fa-crown"></i></span>Subscription Plans</h1>
        <p>Choose the plan that fits your transaction volume</p>
    </div>

    <div class="note-banner">
        <i class="fas fa-exclamation-circle"></i>
        <div><b>Note:</b> Your old plan will be automatically deactivated after purchasing a new plan and is non-refundable.</div>
    </div>

    <?php if ($planCount === 0): ?>
        <div class="empty-state">
            <i class="fas fa-box-open"></i>
            <h4>No active plans right now</h4>
            <p>Check back soon, or contact support for a custom plan.</p>
        </div>
    <?php else: ?>
    <div class="plans-grid">
        <?php foreach ($plans as $i => $row):
            $isPopular = ($i + 1) === $popularIndex && $planCount > 1;
            $planPeriodType = !empty($row['period_type']) ? $row['period_type'] : 'month';
            $planPeriodUnitLabel = ucfirst($planPeriodType) . (((int)$row['expiry'] > 1) ? 's' : '');
            $cashierLimit = (int)($row['cashier_limit'] ?? 1);
            $splLimit = (int)($row['static_paylink_limit'] ?? 1);
            $isCurrentPlan = $currentPlanId !== null && $currentPlanId === (int)$row['id'];
        ?>
        <div class="plan-card<?php echo $isPopular ? ' popular' : ''; ?>" style="animation-delay:<?php echo $i * 0.08; ?>s">
            <?php if ($isPopular): ?><span class="popular-ribbon">Popular</span><?php endif; ?>
            <div class="plan-head">
                <div class="plan-name"><?php echo htmlspecialchars($row['plan_name']); ?></div>
                <div class="plan-price"><span class="cur">₹</span><span class="amt"><?php echo number_format($row['amount']); ?></span></div>
                <div class="plan-duration"><?php echo htmlspecialchars($row['expiry']); ?> <?php echo htmlspecialchars($planPeriodUnitLabel); ?> Plan</div>
            </div>
            <div class="plan-body">
                <ul class="feature-list">
                    <li>
                        <i class="fas fa-check-circle"></i>
                        <span>
                            <b><?php echo ((int)$row['max_transactions'] > 0) ? number_format($row['max_transactions']) : 'Unlimited'; ?></b> Transactions
                            <?php if ((int)$row['max_transactions'] > 0): ?> per <?php echo htmlspecialchars($planPeriodType); ?><?php endif; ?>
                        </span>
                    </li>
                    <li><i class="fas fa-check-circle"></i><span>Valid for <b><?php echo htmlspecialchars($row['expiry']); ?> <?php echo htmlspecialchars($planPeriodUnitLabel); ?></b></span></li>
                    <li><i class="fas fa-check-circle"></i><span><b><?php echo $cashierLimit; ?></b> Cashier<?php echo $cashierLimit > 1 ? 's' : ''; ?>/Merchant<?php echo $cashierLimit > 1 ? 's' : ''; ?> Allowed</span></li>
                    <li><i class="fas fa-check-circle"></i><span><b><?php echo $splLimit > 0 ? $splLimit : 'Unlimited'; ?></b> Static Paylink<?php echo $splLimit > 1 ? 's' : ''; ?></span></li>
                    <li><i class="fas fa-check-circle"></i><span>₹0 Setup Fee, Realtime Transactions</span></li>
                    <li><i class="fas fa-check-circle"></i><span>24×7 WhatsApp Support</span></li>
                </ul>
            </div>
            <div class="plan-footer">
                <?php if ($isCurrentPlan): ?>
                    <button type="button" class="btn-plan" disabled style="opacity:.6;cursor:default;background:rgba(255,255,255,.08)"><i class="fas fa-circle-check"></i> Current Plan</button>
                <?php else: ?>
                <form method="POST" action="lib/pay">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                    <input type="hidden" name="amount" value="<?php echo htmlspecialchars($row['amount']); ?>">
                    <input type="hidden" name="planid" value="<?php echo htmlspecialchars($row['id']); ?>">
                    <button name="upigate" class="btn-plan"><i class="fas fa-cart-shopping"></i> Buy Now</button>
                </form>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<script src="./assets/vendors/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="./assets/vendors/popper.js/dist/umd/popper.min.js" type="text/javascript"></script>
<script src="./assets/vendors/bootstrap/dist/js/bootstrap.min.js" type="text/javascript"></script>
<script src="./assets/vendors/metisMenu/dist/metisMenu.min.js" type="text/javascript"></script>
<script src="./assets/vendors/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="assets/js/app.min.js" type="text/javascript"></script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function () {
    var params = new URLSearchParams(window.location.search);
    if (params.get('payment_failed') === '1') {
        Swal.fire({
            icon: 'error', title: 'Payment Failed',
            text: 'Your payment could not be completed. No amount has been deducted for a successful plan activation. Please try again.',
            confirmButtonText: 'Try Again', background: '#14141f', color: '#fff'
        });
    } else if (params.get('payment_pending') === '1') {
        Swal.fire({
            icon: 'info', title: 'Payment Processing',
            text: "We haven't received confirmation yet. If money was deducted, it will reflect shortly — please check back in a few minutes.",
            confirmButtonText: 'OK', background: '#14141f', color: '#fff'
        });
    }
    if (params.get('payment_failed') || params.get('payment_pending')) {
        var url = new URL(window.location.href);
        url.searchParams.delete('payment_failed');
        url.searchParams.delete('payment_pending');
        url.searchParams.delete('reason');
        window.history.replaceState({}, document.title, url.toString());
    }
})();
</script>
</body>
</html>
