<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
requireLogin();
$uid  = $_SESSION['user_id'];
$user = getCurrentUser();
$pro  = isProUser($user);

$priceMonthly = (float)getSiteSetting('pro_price_monthly', PRO_PRICE_MONTHLY_DEFAULT);
$priceYearly  = (float)getSiteSetting('pro_price_yearly', PRO_PRICE_YEARLY_DEFAULT);
$currency     = getSiteSetting('pro_currency', 'LKR');
$freeAiLimit    = (int)getSiteSetting('free_ai_daily_limit', FREE_AI_DAILY_LIMIT_DEFAULT);
$freeSubLimit   = (int)getSiteSetting('free_subject_limit', FREE_SUBJECT_LIMIT_DEFAULT);
$freeMusicLimit = (int)getSiteSetting('free_music_search_daily_limit', FREE_MUSIC_SEARCH_DAILY_LIMIT_DEFAULT);
$subCountStmt   = $pdo->prepare("SELECT COUNT(*) FROM subjects WHERE user_id=?");
$subCountStmt->execute([$uid]);
$subjectCount   = (int)$subCountStmt->fetchColumn();

// ── Create a pending order + hand back PayHere checkout params ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'start_checkout') {
        $plan = ($_POST['plan'] ?? '') === 'yearly' ? 'yearly' : 'monthly';
        $amount = $plan === 'yearly' ? $priceYearly : $priceMonthly;
        $orderId = 'ST-' . $uid . '-' . strtoupper(bin2hex(random_bytes(4))) . '-' . time();

        $pdo->prepare("INSERT INTO payhere_payments (user_id, order_id, plan, amount, currency, status) VALUES (?,?,?,?,?,'pending')")
            ->execute([$uid, $orderId, $plan, $amount, $currency]);

        $hash = payhereCheckoutHash($orderId, $amount, $currency);
        $nameParts = explode(' ', trim($user['name']), 2);

        jsonResponse([
            'success' => true,
            'checkout_url' => PAYHERE_CHECKOUT_URL,
            'fields' => [
                'merchant_id'  => PAYHERE_MERCHANT_ID,
                'return_url'   => SITE_URL . '/payhere-return.php',
                'cancel_url'   => SITE_URL . '/payhere-cancel.php',
                'notify_url'   => SITE_URL . '/payhere-notify.php',
                'order_id'     => $orderId,
                'items'        => 'StudyTrack Pro (' . ucfirst($plan) . ')',
                'currency'     => $currency,
                'amount'       => number_format($amount, 2, '.', ''),
                'first_name'   => $nameParts[0] ?? 'Student',
                'last_name'    => $nameParts[1] ?? '',
                'email'        => $user['email'],
                'phone'        => '0770000000',
                'address'      => 'N/A',
                'city'         => 'Colombo',
                'country'      => 'Sri Lanka',
                'hash'         => $hash,
            ],
        ]);
    }
    jsonResponse(['success' => false, 'message' => 'Unknown action']);
}

require_once 'includes/header.php';
renderHeader('Upgrade to Pro', 'upgrade');
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700;800;900&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap');
.up-wrap{max-width:920px;margin:0 auto;padding-bottom:60px;font-family:'Plus Jakarta Sans',sans-serif;}
.up-hero{text-align:center;padding:20px 10px 34px;}
.up-hero h1{font-family:'Outfit',sans-serif;font-size:30px;font-weight:800;color:var(--text-primary);letter-spacing:-.5px;}
.up-hero p{color:var(--text-muted);font-size:14px;margin-top:8px;}
.up-status{display:inline-flex;align-items:center;gap:8px;background:linear-gradient(135deg,rgba(16,185,129,.15),rgba(16,185,129,.05));border:1px solid rgba(16,185,129,.3);color:#10b981;font-weight:700;font-size:13px;padding:8px 16px;border-radius:999px;margin-top:14px;}
.up-plans{display:grid;grid-template-columns:1fr 1fr;gap:18px;}
@media(max-width:700px){.up-plans{grid-template-columns:1fr;}}
.up-card{background:var(--bg-card);border:1px solid var(--border);border-radius:20px;padding:26px;position:relative;transition:.2s;}
.up-card.featured{border-color:rgba(99,102,241,.5);box-shadow:0 10px 30px rgba(99,102,241,.12);}
.up-badge{position:absolute;top:-12px;right:20px;background:linear-gradient(135deg,#6366f1,#a855f7);color:#fff;font-size:11px;font-weight:800;padding:5px 12px;border-radius:999px;}
.up-plan-name{font-family:'Outfit',sans-serif;font-size:15px;font-weight:700;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.5px;}
.up-price{font-family:'Outfit',sans-serif;font-size:38px;font-weight:800;color:var(--text-primary);margin:10px 0 2px;}
.up-price span{font-size:14px;font-weight:600;color:var(--text-muted);}
.up-save{font-size:12px;color:#10b981;font-weight:700;margin-bottom:14px;}
.up-feats{list-style:none;padding:0;margin:18px 0 22px;display:flex;flex-direction:column;gap:10px;}
.up-feats li{font-size:13.5px;color:var(--text-secondary);display:flex;align-items:center;gap:9px;}
.up-feats li::before{content:'✓';color:#10b981;font-weight:800;}
.up-btn{width:100%;padding:13px;border:none;border-radius:12px;background:linear-gradient(135deg,#6366f1,#a855f7);color:#fff;font-weight:700;font-size:14px;cursor:pointer;transition:.2s;}
.up-btn:hover{opacity:.92;transform:translateY(-1px);}
.up-btn:disabled{opacity:.6;cursor:not-allowed;}
.up-note{text-align:center;color:var(--text-muted);font-size:12.5px;margin-top:24px;}
</style>

<div class="up-wrap">
  <div class="up-hero">
    <h1>⚡ StudyTrack Pro</h1>
    <p>Unlock unlimited AI coaching, unlimited subjects &amp; unlimited music search — no daily limits.</p>
    <?php if ($pro): ?>
      <div class="up-status">✅ Pro active<?= $user['pro_expires_at'] ? ' — renews/expires ' . date('M j, Y', strtotime($user['pro_expires_at'])) : ' (lifetime)' ?></div>
    <?php else: ?>
      <div class="up-status" style="background:rgba(148,163,184,.12);border-color:var(--border);color:var(--text-muted);">Free plan — limited AI, subjects &amp; music search</div>
    <?php endif; ?>
  </div>

  <div class="up-plans" style="grid-template-columns:1fr 1fr 1fr;">
    <div class="up-card" style="opacity:.92;">
      <div class="up-plan-name">Free</div>
      <div class="up-price">0<span>/forever</span></div>
      <ul class="up-feats" style="margin-top:18px;">
        <li><?= $freeAiLimit ?> AI requests/day</li>
        <li>Up to <?= $freeSubLimit ?> subjects</li>
        <li><?= $freeMusicLimit ?> music searches/day</li>
      </ul>
      <?php if (!$pro): ?>
      <div style="text-align:center;font-size:12px;color:var(--text-muted);padding:11px;border:1px dashed var(--border);border-radius:12px;">
        You're on this plan
        <?php if ($subjectCount >= $freeSubLimit): ?><br><span style="color:#f59e0b;">⚠️ Subject limit reached</span><?php endif; ?>
      </div>
      <?php else: ?>
      <button class="up-btn" disabled style="background:var(--bg-secondary);color:var(--text-muted);">Not your plan</button>
      <?php endif; ?>
    </div>
    <div class="up-card">
      <div class="up-plan-name">Monthly</div>
      <div class="up-price"><?= $currency ?> <?= number_format($priceMonthly, 0) ?><span>/mo</span></div>
      <ul class="up-feats">
        <li>Unlimited AI Tips &amp; AI Chat</li>
        <li>Unlimited AI Analysis</li>
        <li>Unlimited subjects</li>
        <li>Unlimited music search</li>
        <li>Priority response speed</li>
      </ul>
      <button class="up-btn" onclick="checkout('monthly')" <?= $pro ? 'disabled' : '' ?>><?= $pro ? 'Already Pro' : 'Get Monthly' ?></button>
    </div>
    <div class="up-card featured">
      <div class="up-badge">BEST VALUE</div>
      <div class="up-plan-name">Yearly</div>
      <div class="up-price"><?= $currency ?> <?= number_format($priceYearly, 0) ?><span>/yr</span></div>
      <div class="up-save">Save <?= round((1 - $priceYearly / ($priceMonthly * 12)) * 100) ?>% vs monthly</div>
      <ul class="up-feats">
        <li>Everything in Monthly</li>
        <li>Unlimited subjects &amp; music search</li>
        <li>2 months free</li>
        <li>Early access to new AI features</li>
      </ul>
      <button class="up-btn" onclick="checkout('yearly')" <?= $pro ? 'disabled' : '' ?>><?= $pro ? 'Already Pro' : 'Get Yearly' ?></button>
    </div>
  </div>

  <p class="up-note">Payments are securely processed by PayHere. Your Pro status activates automatically once payment is confirmed.</p>
</div>

<script>
async function checkout(plan) {
  const fd = new FormData(); fd.append('action', 'start_checkout'); fd.append('plan', plan);
  const r = await fetch(location.href, { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest' }, body: fd });
  const d = await r.json();
  if (!d.success) { alert(d.message || 'Could not start checkout.'); return; }

  const form = document.createElement('form');
  form.method = 'POST'; form.action = d.checkout_url;
  for (const [k, v] of Object.entries(d.fields)) {
    const inp = document.createElement('input');
    inp.type = 'hidden'; inp.name = k; inp.value = v;
    form.appendChild(inp);
  }
  document.body.appendChild(form);
  form.submit();
}
</script>

<?php require_once 'includes/footer.php'; renderFooter(); ?>
