<?php
if (session_status() === PHP_SESSION_NONE) session_start();

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

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/module_definitions.php';

$module_key  = trim($_GET['module'] ?? '');
$reason      = trim($_GET['reason'] ?? '');
$def         = EDUTRACK_MODULES[$module_key] ?? null;
$license     = checkLicense();
$current_plan = $license['plan'] ?? 'starter';
$school_name  = getSettingValue('school_name') ?: (defined('SITE_NAME') ? SITE_NAME : 'EduTrack School');

// Plan metadata
$plans = [
    'starter' => [
        'label'    => 'Starter',
        'price'    => 'GHS 150',
        'period'   => '/month',
        'limit'    => '200 students',
        'color'    => '#6c757d',
        'gradient' => 'linear-gradient(135deg,#495057,#6c757d)',
        'badge'    => null,
        'modules'  => getPlanModules('starter'),
    ],
    'growth'  => [
        'label'    => 'Growth',
        'price'    => 'GHS 250',
        'period'   => '/month',
        'limit'    => '500 students',
        'color'    => '#0d6efd',
        'gradient' => 'linear-gradient(135deg,#0056d2,#0d6efd)',
        'badge'    => 'Most Popular',
        'modules'  => getPlanModules('growth'),
    ],
    'premium' => [
        'label'    => 'Premium',
        'price'    => 'GHS 400',
        'period'   => '/month',
        'limit'    => 'Unlimited students',
        'color'    => '#6f42c1',
        'gradient' => 'linear-gradient(135deg,#4e2a8e,#6f42c1)',
        'badge'    => 'All-Inclusive',
        'modules'  => getPlanModules('premium'),
    ],
];

// Contact details
$wa_number  = '233537793106'; // 0537793106 → Ghana international
$biz_email  = 'info@oricnetwork.com';
$biz_phone  = '0537 793 106';

$module_label = $def ? $def['label'] : ($module_key ?: 'this feature');
$wa_text  = "Hello! I'm using EduTrack ({$school_name}) on the " . strtoupper($current_plan) .
            " plan and would like to unlock \"{$module_label}\". Please advise on upgrading.";
$wa_link  = "https://wa.me/{$wa_number}?text=" . rawurlencode($wa_text);
$em_subj  = rawurlencode("Upgrade Request – {$school_name}");
$em_body  = rawurlencode("Hello,\n\nI am using EduTrack ({$school_name}) on the " . strtoupper($current_plan) .
            " plan and would like to unlock \"{$module_label}\".\n\nPlease advise.\n\nThank you.");
$email_link = "mailto:{$biz_email}?subject={$em_subj}&body={$em_body}";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upgrade Your Plan – EduTrack</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<style>
/* ── Hero ── */
.upgrade-hero {
  background: linear-gradient(135deg, #0f0c29 0%, #302b63 50%, #24243e 100%);
  border-radius: 20px;
  overflow: hidden;
  position: relative;
}
.upgrade-hero::before {
  content:'';
  position:absolute; inset:0;
  background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E") repeat;
  opacity:.5;
}
.upgrade-hero .hero-inner { position:relative; z-index:1; }
.lock-icon-wrap {
  width:90px; height:90px;
  background: rgba(255,255,255,.1);
  border-radius:50%;
  display:flex; align-items:center; justify-content:center;
  margin:0 auto 1.5rem;
  border:2px solid rgba(255,255,255,.2);
}
.lock-icon-wrap i { font-size:2.5rem; color:#fff; }

/* ── Plan Cards ── */
.plan-card {
  border-radius: 18px;
  overflow: hidden;
  transition: transform .25s, box-shadow .25s;
  border: 2px solid transparent;
}
.plan-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 20px 50px rgba(0,0,0,.15);
}
.plan-card.is-current { border-color: #0d6efd; }
.plan-card.is-recommended { border-color: #6f42c1; }
.plan-card-header {
  padding: 1.75rem 1.5rem 1.25rem;
  color: #fff;
  text-align: center;
}
.plan-price-big { font-size: 2.5rem; font-weight: 800; line-height:1; }
.plan-price-big span { font-size:1rem; font-weight:400; opacity:.7; }
.feature-row { display:flex; align-items:center; padding:.35rem 0; font-size:.9rem; }
.feature-row .icon-yes { color:#198754; }
.feature-row .icon-no  { color:#dee2e6; }
.feature-row.locked-feat { color:#adb5bd; }
.badge-popular {
  background: linear-gradient(135deg,#ff6b35,#f7c59f);
  color:#fff; font-size:.7rem; padding:3px 10px; border-radius:20px;
}
.badge-allinc {
  background: linear-gradient(135deg,#6f42c1,#a78bfa);
  color:#fff; font-size:.7rem; padding:3px 10px; border-radius:20px;
}

/* ── Contact Card ── */
.contact-card {
  background: linear-gradient(135deg,#f8f9ff,#eef2ff);
  border-radius:18px; border:1px solid #e0e7ff;
}
.contact-method {
  display:flex; align-items:center; gap:1rem;
  background:#fff; border-radius:12px; padding:1rem 1.25rem;
  text-decoration:none; color:inherit;
  border:1px solid #e9ecef;
  transition:all .2s;
}
.contact-method:hover {
  border-color:#0d6efd;
  box-shadow:0 4px 16px rgba(13,110,253,.1);
  transform:translateY(-2px);
  color:inherit;
}
.contact-icon {
  width:46px; height:46px; border-radius:12px;
  display:flex; align-items:center; justify-content:center;
  font-size:1.2rem; color:#fff; flex-shrink:0;
}
.addon-card {
  border-radius:16px;
  border:2px dashed #ffc107;
  background:linear-gradient(135deg,#fffdf0,#fff9e6);
}

/* ── Misc ── */
.section-title { font-weight:800; font-size:1.4rem; }
.plan-divider { height:3px; width:40px; border-radius:2px; margin:0 auto .75rem; }
</style>
</head>
<body>
<div class="wrapper">

  <!-- Sidebar -->
  <nav id="sidebar" class="sidebar">
    <?php echo buildSidebar('upgrade.php'); ?>
  </nav>

  <div class="main-content">
    <!-- Header -->
    <header class="header">
      <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
      <div class="header-right">
        <div class="dropdown">
          <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
            <i class="fas fa-user-circle me-2"></i><?= htmlspecialchars($_SESSION['full_name'] ?? 'User') ?>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
          </ul>
        </div>
      </div>
    </header>

    <div class="content p-4">

      <!-- Breadcrumb -->
      <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="dashboard.php"><i class="fas fa-home me-1"></i>Dashboard</a></li>
          <li class="breadcrumb-item active">Upgrade Plan</li>
        </ol>
      </nav>

      <!-- ── Hero ── -->
      <div class="upgrade-hero p-4 p-md-5 mb-5 text-center">
        <div class="hero-inner">
          <div class="lock-icon-wrap">
            <i class="fas <?= $def ? htmlspecialchars($def['icon']) : 'fa-lock' ?>"></i>
          </div>

          <?php if ($reason === 'limit'): ?>
            <?php $limit = (int) ($_GET['limit'] ?? 0); ?>
            <h2 class="fw-bold text-white mb-2">Student Limit Reached</h2>
            <p class="text-white-50 lead mb-1">
              Your <span class="badge bg-secondary fs-6"><?= ucfirst($current_plan) ?></span> plan allows up to
              <strong class="text-white"><?= number_format($limit) ?> students</strong>.
            </p>
            <p class="text-white-50 mb-4">Upgrade to add more students and unlock additional features.</p>

          <?php elseif ($def): ?>
            <h2 class="fw-bold text-white mb-2">
              <?= htmlspecialchars($def['label']) ?> is Locked
            </h2>
            <p class="text-white-50 lead mb-1">
              This module is not included in your
              <span class="badge bg-secondary fs-6"><?= ucfirst($current_plan) ?></span> plan.
            </p>
            <p class="text-white-50 mb-4">
              Upgrade your plan to unlock <strong class="text-white"><?= htmlspecialchars($def['label']) ?></strong>
              and <?= count($plans['premium']['modules']) - count($license['modules'] ?? []) ?> other features.
            </p>

          <?php else: ?>
            <h2 class="fw-bold text-white mb-2">Unlock More Features</h2>
            <p class="text-white-50 lead mb-4">
              You're on the <span class="badge bg-secondary fs-6"><?= ucfirst($current_plan) ?></span> plan.
              Upgrade to access the full power of EduTrack.
            </p>
          <?php endif; ?>

          <div class="d-flex flex-wrap gap-3 justify-content-center">
            <a href="<?= $wa_link ?>" target="_blank" rel="noopener"
               class="btn btn-success btn-lg px-5 rounded-pill fw-semibold">
              <i class="fab fa-whatsapp me-2"></i>WhatsApp Us
            </a>
            <a href="<?= $email_link ?>"
               class="btn btn-outline-light btn-lg px-5 rounded-pill fw-semibold">
              <i class="fas fa-envelope me-2"></i>Send Email
            </a>
          </div>
          <p class="text-white-50 small mt-3 mb-0">
            <i class="fas fa-bolt me-1"></i>We typically respond within <strong class="text-white">1 business hour</strong> &mdash; Mon–Fri, 8am–6pm GMT
          </p>
        </div>
      </div>

      <!-- ── Add-On Option (if a specific module has an addon key) ── -->
      <?php if ($def && $def['addon_key'] && !in_array($module_key, $license['modules'] ?? [])): ?>
      <div class="addon-card p-4 mb-5">
        <div class="row align-items-center g-3">
          <div class="col-md-8">
            <div class="d-flex align-items-center gap-3 mb-2">
              <div style="width:48px;height:48px;background:linear-gradient(135deg,#ffc107,#ff9f00);border-radius:12px;display:flex;align-items:center;justify-content:center;">
                <i class="fas <?= htmlspecialchars($def['icon']) ?> text-white"></i>
              </div>
              <div>
                <h5 class="fw-bold mb-0"><?= htmlspecialchars($def['label']) ?> — Add-On</h5>
                <span class="text-muted small">Available on your current plan without full upgrade</span>
              </div>
            </div>
            <p class="mb-0 text-muted">
              Keep your <strong><?= ucfirst($current_plan) ?></strong> plan and add this single module for
              only <strong class="text-dark fs-5">GHS <?= number_format($def['addon_price'] ?? 0, 0) ?>/month</strong>.
              Perfect if you only need this specific feature.
            </p>
          </div>
          <div class="col-md-4 text-md-end">
            <a href="<?= $wa_link ?>" target="_blank" rel="noopener"
               class="btn btn-warning fw-semibold rounded-pill px-4 me-2">
              <i class="fab fa-whatsapp me-2"></i>Add On via WhatsApp
            </a>
          </div>
        </div>
      </div>
      <?php endif; ?>

      <!-- ── Plan Cards ── -->
      <div class="d-flex align-items-center justify-content-between mb-4">
        <h4 class="section-title mb-0"><i class="fas fa-rocket me-2 text-primary"></i>Choose Your Plan</h4>
        <span class="text-muted small">All plans include a free setup &amp; onboarding</span>
      </div>
      <div class="row g-4 mb-5">
        <?php foreach ($plans as $pk => $plan):
          $is_current     = ($pk === $current_plan);
          $is_recommended = ($pk === 'growth' && $current_plan === 'starter') ||
                            ($pk === 'premium' && $current_plan === 'growth');
          $plan_modules   = $plan['modules'];
          $wa_upgrade_txt = "Hello! I'd like to upgrade EduTrack ({$school_name}) from " . strtoupper($current_plan) . " to the " . strtoupper($pk) . " plan. Please advise.";
          $wa_upgrade     = "https://wa.me/{$wa_number}?text=" . rawurlencode($wa_upgrade_txt);
        ?>
        <div class="col-md-4">
          <div class="card plan-card h-100 shadow-sm <?= $is_current ? 'is-current' : '' ?> <?= $is_recommended ? 'is-recommended' : '' ?>">
            <!-- Card Header -->
            <div class="plan-card-header" style="background:<?= $plan['gradient'] ?>">
              <?php if ($plan['badge']): ?>
              <div class="mb-2">
                <?php if ($pk === 'growth'): ?>
                <span class="badge-popular"><i class="fas fa-fire me-1"></i><?= $plan['badge'] ?></span>
                <?php else: ?>
                <span class="badge-allinc"><i class="fas fa-star me-1"></i><?= $plan['badge'] ?></span>
                <?php endif; ?>
              </div>
              <?php elseif ($is_current): ?>
              <div class="mb-2"><span class="badge bg-white text-dark small">Current Plan</span></div>
              <?php else: ?>
              <div class="mb-2" style="height:22px"></div>
              <?php endif; ?>
              <div class="plan-divider" style="background:rgba(255,255,255,.4)"></div>
              <h4 class="fw-bold mb-1"><?= $plan['label'] ?></h4>
              <div class="plan-price-big"><?= $plan['price'] ?><span><?= $plan['period'] ?></span></div>
              <div class="mt-1 opacity-75 small"><i class="fas fa-users me-1"></i><?= $plan['limit'] ?></div>
            </div>

            <!-- Card Body: module list -->
            <div class="card-body px-4 py-3">
              <?php
              $section = 'core';
              foreach (EDUTRACK_MODULES as $mk => $md):
                // Section divider
                $m_section = $md['core'] ? 'core' : (count($md['plans']) === 1 && $md['plans'][0] === 'premium' ? 'premium' : 'growth');
                if ($m_section !== $section) {
                    $section = $m_section;
                    $sec_label = $section === 'premium' ? 'AI & Premium' : 'Optional Modules';
                    echo '<div class="text-muted mt-2 mb-1" style="font-size:.65rem;font-weight:700;letter-spacing:.08em;text-transform:uppercase">' . $sec_label . '</div>';
                }
                $included = in_array($mk, $plan_modules);
              ?>
              <div class="feature-row <?= $included ? '' : 'locked-feat' ?>">
                <i class="fas <?= $included ? 'fa-check-circle icon-yes' : 'fa-times-circle icon-no' ?> me-2 flex-shrink-0"></i>
                <span><?= htmlspecialchars($md['label']) ?></span>
              </div>
              <?php endforeach; ?>
            </div>

            <!-- Card Footer -->
            <div class="card-footer border-0 bg-transparent px-4 pb-4">
              <?php if ($is_current): ?>
              <div class="btn w-100 rounded-pill disabled"
                   style="background:<?= $plan['gradient'] ?>;color:#fff;opacity:.6;">
                <i class="fas fa-check-circle me-1"></i>Active Plan
              </div>
              <?php else: ?>
              <a href="<?= $wa_upgrade ?>" target="_blank" rel="noopener"
                 class="btn w-100 rounded-pill fw-semibold text-white"
                 style="background:<?= $plan['gradient'] ?>">
                <i class="fab fa-whatsapp me-2"></i>Upgrade to <?= $plan['label'] ?>
              </a>
              <?php endif; ?>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>

      <!-- ── Contact Section ── -->
      <div class="contact-card p-4 p-md-5 mb-4">
        <div class="text-center mb-4">
          <h4 class="section-title mb-1">Talk to Us Directly</h4>
          <p class="text-muted mb-0">Our team will help you choose the right plan and set everything up.</p>
        </div>
        <div class="row g-3 justify-content-center">
          <div class="col-md-5">
            <a href="<?= $wa_link ?>" target="_blank" rel="noopener" class="contact-method">
              <div class="contact-icon" style="background:linear-gradient(135deg,#25d366,#128c7e)">
                <i class="fab fa-whatsapp"></i>
              </div>
              <div>
                <div class="fw-semibold">WhatsApp</div>
                <div class="text-muted small"><?= $biz_phone ?></div>
              </div>
              <i class="fas fa-chevron-right ms-auto text-muted"></i>
            </a>
          </div>
          <div class="col-md-5">
            <a href="<?= $email_link ?>" class="contact-method">
              <div class="contact-icon" style="background:linear-gradient(135deg,#0d6efd,#0056d2)">
                <i class="fas fa-envelope"></i>
              </div>
              <div>
                <div class="fw-semibold">Email</div>
                <div class="text-muted small"><?= $biz_email ?></div>
              </div>
              <i class="fas fa-chevron-right ms-auto text-muted"></i>
            </a>
          </div>
          <div class="col-md-5">
            <a href="tel:+233537793106" class="contact-method">
              <div class="contact-icon" style="background:linear-gradient(135deg,#6f42c1,#4e2a8e)">
                <i class="fas fa-phone"></i>
              </div>
              <div>
                <div class="fw-semibold">Call Us</div>
                <div class="text-muted small"><?= $biz_phone ?></div>
              </div>
              <i class="fas fa-chevron-right ms-auto text-muted"></i>
            </a>
          </div>
          <div class="col-md-5">
            <div class="contact-method" style="cursor:default">
              <div class="contact-icon" style="background:linear-gradient(135deg,#20c997,#087f5b)">
                <i class="fas fa-clock"></i>
              </div>
              <div>
                <div class="fw-semibold">Business Hours</div>
                <div class="text-muted small">Mon–Fri, 8am–6pm (GMT)</div>
              </div>
            </div>
          </div>
        </div>
        <p class="text-center text-muted small mt-4 mb-0">
          <i class="fas fa-shield-alt me-1 text-success"></i>
          All plans include free data migration, onboarding support, and lifetime updates.
          Powered by <strong>Oric Network Limited</strong>.
        </p>
      </div>

    </div><!-- /.content -->
  </div><!-- /.main-content -->
</div><!-- /.wrapper -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const sidebarToggle = document.getElementById('sidebarToggle');
if (sidebarToggle) {
  sidebarToggle.addEventListener('click', function () {
    document.getElementById('sidebar').classList.toggle('active');
    document.querySelector('.main-content').classList.toggle('active');
  });
}
</script>
</body>
</html>
