<?php
// index.php

require_once __DIR__ . '/config/config.php';
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/Helpers/Language.php';
require_once __DIR__ . '/src/Helpers/Auth.php';
require_once __DIR__ . '/src/Controllers/CourseController.php';
require_once __DIR__ . '/src/Controllers/PortalController.php';

// Initialize Database automatically if needed
if (DB_DRIVER === 'sqlite' && !file_exists(DB_SQLITE_PATH)) {
    require_once __DIR__ . '/database/setup_sqlite.php';
}

Language::init();
$lang = Language::current();
$user = Auth::user();

// Page Router
$page = $_GET['page'] ?? 'home';

// Fetch courses data if on homepage
$search = $_GET['search'] ?? null;
$category = $_GET['category'] ?? null;
$courses = CourseController::getAllCourses($search, $category);
$categories = CourseController::getCategories();

// Fetch enrolled course IDs if logged in
$enrolledCourseIds = [];
if ($user) {
    $userEnrollments = PortalController::getStudentEnrollments($user['id']);
    $enrolledCourseIds = array_column($userEnrollments, 'course_id');
}
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= Language::dir() ?>">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title><?= Language::t('academyName') ?></title>
  
  <!-- Tailwind CSS CDN for instant rendering -->
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            teal: {
              850: '#0F484B',
              950: '#072C2E',
            }
          }
        }
      }
    }
  </script>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Amiri:ital,wght@0,400;0,700;1,400&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Plus Jakarta Sans', sans-serif;
    }
    [dir="rtl"] body {
      font-family: 'Amiri', 'Plus Jakarta Sans', serif;
    }
  </style>
</head>
<body class="bg-gray-50 text-gray-800 min-h-screen flex flex-col antialiased">

  <!-- Main Header -->
  <?php include __DIR__ . '/views/partials/header.php'; ?>

  <!-- Main Content View Container -->
  <main class="flex-grow">
    <?php if ($page === 'portal'): ?>
      <?php include __DIR__ . '/views/portal.php'; ?>
    <?php else: ?>
      
      <!-- Hero Banner -->
      <section class="bg-gradient-to-br from-teal-950 via-teal-900 to-emerald-950 text-white py-16 px-4 sm:px-6 lg:px-8 border-b border-teal-800/60 relative overflow-hidden">
        <div class="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-12 gap-8 items-center relative z-10">
          <div class="md:col-span-8 space-y-6 text-center md:text-left">
            <span class="inline-block bg-amber-400/20 text-amber-300 text-xs font-extrabold px-3.5 py-1.5 rounded-full border border-amber-400/40 uppercase tracking-widest">
              🎓 Admissions Open for Session 2026/2027
            </span>
            <h1 class="text-3xl sm:text-4xl md:text-5xl font-black leading-tight tracking-tight text-white">
              <?= Language::t('welcomeBanner') ?>
            </h1>
            <p class="text-sm md:text-base text-teal-200/90 leading-relaxed max-w-2xl">
              <?= Language::t('heroTagline') ?>
            </p>
          </div>

          <!-- Hero Search Box -->
          <div class="md:col-span-4 bg-white/10 backdrop-blur-md p-6 rounded-3xl border border-white/20 shadow-2xl">
            <form action="index.php" method="GET" class="space-y-4">
              <h3 class="font-bold text-white text-sm">Find Your Academic Program</h3>
              <input type="text" name="search" value="<?= htmlspecialchars($search ?? '') ?>" placeholder="<?= Language::t('searchPlaceholder') ?>" class="w-full px-4 py-3 rounded-2xl bg-white/90 text-gray-900 text-xs placeholder-gray-500 font-semibold focus:outline-none focus:ring-2 focus:ring-amber-400">
              <button type="submit" class="w-full bg-amber-500 hover:bg-amber-400 text-teal-950 font-extrabold py-3 rounded-2xl text-xs shadow-lg transition-all">
                🔍 Search Programs
              </button>
            </form>
          </div>
        </div>
      </section>

      <!-- Category Filter Pills -->
      <section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-8">
        <div class="flex items-center gap-2 overflow-x-auto pb-2 scrollbar-none">
          <a href="index.php" class="px-4 py-2 rounded-xl text-xs font-bold whitespace-nowrap transition-all <?= empty($category) || $category === 'All' ? 'bg-teal-900 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-gray-100 border border-gray-200' ?>">
            <?= Language::t('allCategories') ?>
          </a>
          <?php foreach ($categories as $cat): 
            $catName = $lang === 'ar' ? $cat['category_ar'] : $cat['category_en'];
          ?>
            <a href="index.php?category=<?= urlencode($cat['category_en']) ?>" class="px-4 py-2 rounded-xl text-xs font-bold whitespace-nowrap transition-all <?= $category === $cat['category_en'] ? 'bg-teal-900 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-gray-100 border border-gray-200' ?>">
              <?= htmlspecialchars($catName) ?>
            </a>
          <?php endforeach; ?>
        </div>
      </section>

      <!-- Course Catalog Grid -->
      <section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
        <div class="flex items-center justify-between">
          <h2 class="text-2xl font-extrabold text-gray-900"><?= Language::t('exploreCourses') ?></h2>
          <span class="text-xs text-gray-500 font-semibold"><?= count($courses) ?> Programs Available</span>
        </div>

        <?php if (empty($courses)): ?>
          <div class="bg-white p-12 rounded-3xl border border-gray-200 text-center space-y-3">
            <span class="text-4xl">🔎</span>
            <h3 class="text-base font-bold text-gray-700">No courses match your query</h3>
            <a href="index.php" class="inline-block text-xs font-bold text-teal-800 underline">View all programs</a>
          </div>
        <?php else: ?>
          <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($courses as $course): ?>
              <?php include __DIR__ . '/views/partials/course-card.php'; ?>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </section>

    <?php endif; ?>
  </main>

  <!-- Footer -->
  <?php include __DIR__ . '/views/partials/footer.php'; ?>

  <!-- Authentication Modals -->
  <?php include __DIR__ . '/views/partials/auth-modals.php'; ?>

  <!-- Paystack Checkout Modal -->
  <?php include __DIR__ . '/views/partials/paystack-modal.php'; ?>

  <!-- Client-side Interactivity Script -->
  <script>
    let selectedPaystackCourseId = '';
    let selectedPaystackCourseTitle = '';
    let selectedPaystackAmount = 0;

    function openModal(type) {
      if (type === 'login') {
        document.getElementById('loginModal').classList.remove('hidden');
      } else if (type === 'register') {
        document.getElementById('registerModal').classList.remove('hidden');
      }
    }

    function closeModal(id) {
      document.getElementById(id).classList.add('hidden');
    }

    function openPaystackModal(courseId, courseTitle, amount) {
      <?php if (!$user): ?>
        openModal('login');
        return;
      <?php else: ?>
        selectedPaystackCourseId = courseId;
        selectedPaystackCourseTitle = courseTitle;
        selectedPaystackAmount = amount;

        document.getElementById('paystackCourseTitle').innerText = courseTitle;
        document.getElementById('paystackAmountDisplay').innerText = '<?= Language::currencySymbol() ?>' + amount.toLocaleString();
        document.getElementById('paystackModal').classList.remove('hidden');
      <?php endif; ?>
    }

    async function handleLoginSubmit(e) {
      e.preventDefault();
      const email = document.getElementById('loginEmail').value;
      const password = document.getElementById('loginPassword').value;
      const alertBox = document.getElementById('loginAlert');

      alertBox.classList.add('hidden');

      const formData = new FormData();
      formData.append('action', 'login');
      formData.append('email', email);
      formData.append('password', password);

      const res = await fetch('api/auth.php', { method: 'POST', body: formData });
      const data = await res.json();

      if (data.success) {
        window.location.reload();
      } else {
        alertBox.innerText = data.message;
        alertBox.classList.remove('hidden');
      }
    }

    async function handleRegisterSubmit(e) {
      e.preventDefault();
      const name = document.getElementById('regName').value;
      const email = document.getElementById('regEmail').value;
      const phone = document.getElementById('regPhone').value;
      const password = document.getElementById('regPassword').value;
      const alertBox = document.getElementById('registerAlert');

      alertBox.classList.add('hidden');

      const formData = new FormData();
      formData.append('action', 'register');
      formData.append('name', name);
      formData.append('email', email);
      formData.append('phone', phone);
      formData.append('password', password);

      const res = await fetch('api/auth.php', { method: 'POST', body: formData });
      const data = await res.json();

      if (data.success) {
        window.location.href = 'index.php?page=portal';
      } else {
        alertBox.innerText = data.message;
        alertBox.classList.remove('hidden');
      }
    }

    async function handleLogout() {
      const formData = new FormData();
      formData.append('action', 'logout');
      await fetch('api/auth.php', { method: 'POST', body: formData });
      window.location.href = 'index.php';
    }

    async function executePaystackPayment() {
      const alertBox = document.getElementById('paystackAlert');
      const submitBtn = document.getElementById('paystackSubmitBtn');

      alertBox.classList.add('hidden');
      submitBtn.disabled = true;
      submitBtn.innerText = 'Processing Gateway...';

      const formData = new FormData();
      formData.append('course_id', selectedPaystackCourseId);
      formData.append('currency', '<?= Language::currency() ?>');

      try {
        const res = await fetch('api/paystack-init.php', { method: 'POST', body: formData });
        const data = await res.json();

        if (data.success) {
          window.location.href = data.authorization_url;
        } else {
          alertBox.innerText = data.message;
          alertBox.classList.remove('hidden');
          submitBtn.disabled = false;
          submitBtn.innerText = '🔒 <?= Language::t('payNow') ?>';
        }
      } catch (err) {
        alertBox.innerText = 'Network error initiating payment.';
        alertBox.classList.remove('hidden');
        submitBtn.disabled = false;
        submitBtn.innerText = '🔒 <?= Language::t('payNow') ?>';
      }
    }

    async function toggleModule(courseId, moduleIndex) {
      const formData = new FormData();
      formData.append('course_id', courseId);
      formData.append('module_index', moduleIndex);

      const res = await fetch('api/progress.php', { method: 'POST', body: formData });
      const data = await res.json();

      if (data.success) {
        window.location.reload();
      }
    }
  </script>
</body>
</html>
