<?php declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../../includes/auth.php';
require_role(['student','super_admin','branch_admin']);
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/helpers.php';
require_once __DIR__ . '/../../includes/layout_top.php';
require_once __DIR__ . '/../../includes/scope.php';

/* inputs */
$course_id = (int)($_GET['course_id'] ?? 0);
$batch_id  = (int)($_GET['batch_id'] ?? 0);

/* data */
$courses = elms_all_courses($mysqli);
$batches = $course_id ? elms_batches_for_course($mysqli, $course_id) : [];

/* helpers */
function esc2($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

?>
<style>
  /* Unlock theme container caps and use a two-column layout for Learn page */
  .page-content, .container, .container-fluid { max-width:100% !important; width:100% !important; }
  .learn-grid { display:grid; grid-template-columns: 28% 72%; gap:18px }
  @media (max-width: 992px){ .learn-grid{ grid-template-columns:1fr } }
  .pane{ background:#fff;border:1px solid #e6eaf3;border-radius:16px;box-shadow:0 12px 28px rgba(2,8,23,.06); padding:16px; min-width:0 }
  .title{ font-weight:800; margin:0 0 10px }
  .list-group a{ display:block; text-decoration:none }
  #learnViewer iframe, #learnViewer video { width:100%; max-height:82vh; border:0 }
</style>

<h1 class="h5 mb-3">Learn</h1>

<form class="row g-2 mb-3" method="get">
  <div class="col-auto">
    <select name="course_id" class="form-select" required onchange="this.form.submit()">
      <option value="">Select course…</option>
      <?php foreach ($courses as $cid => $ctitle): ?>
      <option value="<?= (int)$cid ?>" <?= $cid===$course_id?'selected':'' ?>><?= esc2($ctitle) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="col-auto">
    <select name="batch_id" class="form-select" required onchange="this.form.submit()">
      <option value="">Select batch…</option>
      <?php foreach ($batches as $bid => $bcode): ?>
      <option value="<?= (int)$bid ?>" <?= $bid===$batch_id?'selected':'' ?>><?= esc2($bcode) ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="col-auto"><button class="btn btn-primary">Load</button></div>
</form>

<?php if ($course_id && $batch_id): 
  $stmt = $mysqli->prepare('
    SELECT r.id AS rel_id, ci.id AS content_id, u.title AS unit_title, ci.title AS item_title, ci.type, ci.source_path_or_url, r.release_at, r.close_at
    FROM lms_content_release r
    JOIN lms_content_items ci ON ci.id = r.content_id
    JOIN lms_units u ON u.id = ci.unit_id
    WHERE r.batch_id=? AND r.visible=1 AND r.release_at <= NOW() AND (r.close_at IS NULL OR r.close_at >= NOW()) AND u.course_id=?
    ORDER BY u.sort_order, ci.sort_order, r.release_at DESC
  ');
  $stmt->bind_param('ii', $batch_id, $course_id);
  $stmt->execute();
  $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
?>
  <div class="learn-grid">
    <!-- LEFT: release list -->
    <div class="pane">
      <h6 class="title">Released Content</h6>
      <div class="list-group">
        <?php foreach ($rows as $row): 
          $href = (string)$row['source_path_or_url'];
          $title = esc2($row['unit_title']).' · '.esc2($row['item_title']);
          $time  = date('Y-m-d H:i', strtotime($row['release_at']));
        ?>
          <a class="list-group-item list-group-item-action open-learn" href="<?= esc2($href) ?>">
            <div class="d-flex w-100 justify-content-between">
              <h6 class="mb-1"><?= $title ?></h6>
              <small><?= $time ?></small>
            </div>
            <small class="text-muted"><?= esc2($row['type']) ?></small>
          </a>
        <?php endforeach; ?>
        <?php if (!$rows): ?>
          <div class="list-group-item">No released content yet.</div>
        <?php endif; ?>
      </div>
    </div>

    <!-- RIGHT: inline preview -->
    <div class="pane">
      <h6 class="title">Preview</h6>
      <div id="learnViewer">
        <div class="p-4 text-center" style="font-size:13.5px;color:#64748b">Select an item to preview here.</div>
      </div>
    </div>
  </div>

  <script>
    // Intercept clicks and try to preview PDFs/videos/images/links inline
    (function(){
      const viewer = document.getElementById('learnViewer');
      document.addEventListener('click', async (e)=>{
        const a = e.target.closest('a.open-learn'); if(!a) return;
        e.preventDefault();
        const url = a.getAttribute('href') || '';
        viewer.innerHTML = '<div class="p-4 text-center" style="font-size:13.5px;color:#64748b">Loading…</div>';

        // YouTube / Vimeo smart embeds
        const yt = url.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([\w\-]{6,})/i);
        if (yt){
          const src='https://www.youtube.com/embed/'+encodeURIComponent(yt[1])+'?rel=0';
          viewer.innerHTML = '<div class="ratio ratio-16x9"><iframe src="'+src+'" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen style="height:72vh;border:0;width:100%"></iframe></div>';
          return;
        }
        const vim = url.match(/vimeo\.com\/(?:video\/)?(\d+)/i);
        if (vim){
          const src='https://player.vimeo.com/video/'+encodeURIComponent(vim[1]);
          viewer.innerHTML = '<div class="ratio ratio-16x9"><iframe src="'+src+'" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen style="height:72vh;border:0;width:100%"></iframe></div>';
          return;
        }

        // Simple guesses by extension
        if (/\.(pdf)(\?|$)/i.test(url)){
          viewer.innerHTML = '<iframe src="'+url+'#toolbar=1&navpanes=0" style="height:82vh;width:100%;border:0"></iframe>'; return;
        }
        if (/\.(mp4|webm|ogg|mov|mkv)(\?|$)/i.test(url)){
          viewer.innerHTML = '<video controls src="'+url+'" style="width:100%;max-height:82vh"></video>'; return;
        }
        if (/\.(jpg|jpeg|png|gif|webp|svg)(\?|$)/i.test(url)){
          viewer.innerHTML = '<img src="'+url+'" style="max-width:100%;height:auto">'; return;
        }

        // Fallback: load in an iframe
        viewer.innerHTML = '<iframe src="'+url+'" style="height:82vh;width:100%;border:0"></iframe>';
      });
    })();
  </script>
<?php endif; ?>

<?php require_once __DIR__ . '/../../includes/layout_bottom.php'; ?>
