<?php
// minimal, safe diagnostic — shows the *real* fatal instead of a blank 500
declare(strict_types=1);
@ini_set('display_errors','1');
@ini_set('display_startup_errors','1');
error_reporting(E_ALL);

register_shutdown_function(function () {
  $e = error_get_last();
  if ($e && in_array($e['type'], [E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR])) {
    echo "<pre style='font:14px/1.4 system-ui;padding:16px;border:1px solid #fecaca;background:#fff5f5;border-radius:12px;color:#991b1b'>
PHP FATAL: {$e['message']}
FILE: {$e['file']}
LINE: {$e['line']}
</pre>";
  }
});

require_once __DIR__.'/../includes/app.php';
require_once __DIR__.'/../includes/db.php';

echo "<h3 style='font:600 18px system-ui;margin:16px 16px 8px'>Diagnostics</h3><div style='font:14px system-ui;margin:0 16px'>";
echo "<p>PHP ".phpversion()."</p>";

$ok = false;
$errors = [];

function try_msg($label, $ok, $extra=''){
  $c = $ok ? '#166534' : '#991b1b';
  $b = $ok ? '#ecfdf5' : '#fff5f5';
  echo "<div style='margin:8px 0;padding:10px 12px;border:1px solid #e5e7eb;border-radius:10px;background:$b'>
        <strong style='color:$c'>$label:</strong> ".($ok?'OK':'FAIL').($extra? " — <span style=\"color:#334155\">$extra</span>":'')."</div>";
}

$mysqli = null;

// path A: ec_db()
if (function_exists('ec_db')) {
  try { $db = ec_db(); if ($db instanceof mysqli) { $mysqli=$db; $ok=true; try_msg('ec_db()', true); } else { try_msg('ec_db()', false, 'returned non-mysqli'); } }
  catch (Throwable $t) { try_msg('ec_db()', false, htmlspecialchars($t->getMessage())); $errors[]=$t->getMessage(); }
} else { try_msg('ec_db() available', false, 'function not defined'); }

// path B: $conn
if (!$mysqli && isset($conn) && $conn instanceof mysqli) { $mysqli=$conn; $ok=true; try_msg('$conn mysqli', true); }
elseif (!$mysqli) { try_msg('$conn mysqli', false, isset($conn)? 'defined but wrong type':'not defined'); }

// path C: constants
if (!$mysqli && defined('DB_HOST') && defined('DB_USER') && defined('DB_NAME')) {
  $pass = defined('DB_PASS') ? DB_PASS : '';
  $tmp = @new mysqli(DB_HOST, DB_USER, $pass, DB_NAME);
  if (!$tmp->connect_error) { $mysqli = $tmp; $ok=true; try_msg('mysqli via constants', true); }
  else { try_msg('mysqli via constants', false, $tmp->connect_error); }
}

// final status
if ($mysqli instanceof mysqli && !$mysqli->connect_error) {
  $mysqli->set_charset('utf8mb4');
  $res = $mysqli->query("SELECT 1");
  try_msg('Final MySQL connection', (bool)$res, $res?'query OK':'query failed');
  if ($res) $res->close();
} else {
  try_msg('Final MySQL connection', false, 'no working mysqli handle');
}

echo "<p style='margin-top:12px;color:#64748b'>If something above shows FAIL, fix that source (ec_db / \$conn / constants). When green, your modules page should load.</p>";
echo "</div>";
  :root{
    --font:"Inter",ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Noto Sans",Arial,"Helvetica Neue",sans-serif;
    --ink:#0f172a; --muted:#6b7280; --line:#e6eaf3; --shadow:0 12px 28px rgba(2,8,23,.06);
    --radius-lg:16px; --radius-md:12px;
  }
  .mods-scope{font-family:var(--font);font-size:15px;color:var(--ink)}

  /* === Auto-sizing grid by number of courses === */
  .mods-scope{ --left-col: clamp(280px, 32vw, 420px); }
  .mods-scope.courses-1{ --left-col: clamp(260px, 28vw, 360px); }   /* 1 course: content wider */
  .mods-scope.courses-2{ --left-col: clamp(280px, 32vw, 420px); }   /* 2 courses: balanced */
  .mods-scope.courses-3plus{ --left-col: clamp(320px, 38vw, 520px);}/* 3+ courses: left wider */

  .mod-grid{
    display:grid; gap:16px;
    grid-template-columns: var(--left-col) 1fr;
    align-items:start;
  }
  @media (max-width: 1200px){ .mod-grid{ grid-template-columns:1fr } }

  .pane{
    background:#fff;border:1px solid var(--line);border-radius:var(--radius-lg);box-shadow:var(--shadow);
    padding:16px; display:flex; flex-direction:column;
    min-height: calc(100vh - 160px);
    max-height: calc(100vh - 160px);
    overflow:hidden;
  }
  .scroll-area{ margin-top:8px; height:100%; overflow:auto; -webkit-overflow-scrolling:touch; }
  #contentPane{
    height:100%; overflow:auto; -webkit-overflow-scrolling:touch;
    background:#fff;border:1px solid var(--line);border-radius:var(--radius-md);box-shadow:var(--shadow);
  }

  /* Header + Course Banner */
  h6{font-size:16px;font-weight:800;margin:0;letter-spacing:.1px}
  .header-row{display:flex;flex-direction:column;gap:12px}
  .course-banner{
    display:flex; align-items:center; justify-content:space-between; gap:10px;
    border:1px solid var(--line); border-radius:14px; background:#fff; padding:12px 14px;
    box-shadow:0 8px 18px rgba(2,6,23,.05);
  }
  .course-banner .title{font-weight:800;color:#0f172a;font-size:15px}

  /* Course chips (only when >1) */
  .course-rail{ display:flex; gap:10px; overflow:auto; padding:8px; border:1px solid var(--line);
    border-radius:999px; background:linear-gradient(180deg,#fafcff,#ffffff); scrollbar-width:thin; }
  .course-rail::-webkit-scrollbar{height:8px}
  .course-rail::-webkit-scrollbar-thumb{background:#dbe4ff;border-radius:999px}
  .course-btn{ display:inline-flex;align-items:center;gap:8px;white-space:nowrap;
    padding:8px 14px;border-radius:999px;border:1px solid var(--line); background:#fff;
    font-size:13.5px;color:#0f172a;text-decoration:none; box-shadow:0 2px 8px rgba(2,6,23,.04); transition:all .18s; }
  .course-btn:hover{ background:#eef4ff; border-color:#cfe0ff }
  .course-btn.active{ background:linear-gradient(90deg,#2563eb,#3b82f6); color:#fff; border-color:transparent;
    text-shadow:0 1px 1px rgba(0,0,0,.25); box-shadow:0 10px 20px rgba(37,99,235,.22) }

  /* Semesters / modules / items */
  .sem-accordion{display:grid;gap:12px}
  .sem{border:1px solid var(--line);border-radius:var(--radius-md);background:#fff;overflow:hidden}
  .sem-head{width:100%;display:flex;align-items:center;justify-content:space-between;gap:10px;
    padding:12px 14px;font-size:14px;font-weight:800;letter-spacing:.2px;color:#0f172a;
    background:linear-gradient(180deg,#ffffff 0%, #f6f9ff 100%);border:0;cursor:pointer}
  .sem-meta{font-size:12.5px;color:#6b7280;margin-left:6px}
  .chev{transition:transform .2s ease;font-size:12px}
  .sem-head.collapsed .chev{transform:rotate(-90deg)}
  .sem-body{padding:12px 12px 14px;background:#fff}
  .mod{border:1px solid var(--line);background:#fff;border-radius:14px;padding:12px;margin:10px 0;box-shadow:0 8px 18px rgba(2,6,23,.05)}
  .mod-title{font-size:14.5px;font-weight:800;color:#111827}
  .count-badge{display:inline-block;font-size:12px;color:#334155;background:#f8fafc;border:1px solid var(--line);border-radius:999px;padding:6px 10px}
  .items{margin-top:8px}
  .item{display:grid;grid-template-columns:1fr auto;gap:12px;border:1px dashed var(--line);border-radius:12px;
    padding:10px 12px;margin:8px 0;background:#fff;transition:border-color .15s,box-shadow .15s,transform .03s}
  .item:hover{border-color:#cfe0ff;box-shadow:0 10px 20px rgba(37,99,235,.07)}
  .item:active{transform:translateY(1px)}
  .item.active{border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.12)}
  .item-kind{font-size:12.5px;color:#6b7280;text-transform:capitalize}
  .view-btn{background:#fff;color:#0f172a;border:1px solid var(--line);padding:.44rem .72rem;border-radius:10px;text-decoration:none;display:inline-flex;align-items:center;gap:6px}
  .view-btn:hover{background:#eef4ff;border-color:#cfe0ff}
  .empty{color:#6b7280;background:#fff;border:1px dashed var(--line);border-radius:12px;padding:14px;text-align:center;font-size:13.5px}
  .content-title{font-size:14.5px;font-weight:800;margin:0;color:#0f172a}
</style>

<div class="mods-scope <?= esc($layoutClass) ?>">
  <div class="mod-grid">
    <!-- LEFT -->
    <section class="pane">
      <div class="header-row">
        <h6>My Courses · Modules</h6>

        <!-- Course Banner (always visible) -->
        <div class="course-banner">
          <div class="title"><?= esc($course_name) ?></div>
        </div>

        <!-- Show chips only when multiple courses -->
        <?php if ($COURSE_COUNT > 1): ?>
          <nav class="course-rail" aria-label="Choose course">
            <?php foreach($courses as $c):
              $cid = (int)$c['id']; $active = ($cid === $course_id); ?>
              <a class="course-btn <?= $active ? 'active' : '' ?>"
                 href="?course_id=<?= $cid ?>" <?= $active ? 'aria-current="page"' : '' ?>>
                <?= esc($c['course_name']) ?>
              </a>
            <?php endforeach; ?>
          </nav>
        <?php endif; ?>
      </div>

      <div class="scroll-area">
        <?php if ($course_id<=0): ?>
          <div class="empty">No course found for this student.</div>
        <?php else: ?>
          <div class="sem-accordion" data-accordion="single">
            <?php ksort($by_sem); $__i=0; foreach($by_sem as $semNo=>$mods): $open = ($__i++===0); ?>
              <section class="sem">
                <button type="button" class="sem-head <?= $open?'':'collapsed' ?>" aria-expanded="<?= $open?'true':'false' ?>">
                  <div style="display:flex;align-items:center;gap:6px">
                    <span>Semester <?= (int)$semNo ?></span>
                    <span class="sem-meta"><?= count($mods) ?> module<?= count($mods)==1?'':'s' ?></span>
                  </div>
                  <span class="chev">▾</span>
                </button>
                <div class="sem-body" style="<?= $open?'':'display:none' ?>">
                  <?php foreach($mods as $m): ?>
                    <div class="mod">
                      <div class="d-flex align-items-center justify-content-between">
                        <div class="mod-title"><?= esc($m['title']) ?></div>
                        <span class="count-badge"><?= count($m['items']) ?> item<?= count($m['items'])==1?'':'s' ?></span>
                      </div>
                      <div class="items">
                        <?php if (!$m['items']): ?>
                          <div class="empty">No items.</div>
                        <?php else: foreach($m['items'] as $it):
                          $iid=(int)$it['id']; $kind=$it['ctype'];
                          $viewHere = rtrim(dirname($_SERVER['REQUEST_URI'] ?? '/student/modules.php'), '/').'/module_content.php?item_id='.$iid;
                          $ico = kind_icon($kind);
                        ?>
                          <div class="item" data-item-id="<?= $iid ?>">
                            <div class="item-meta">
                              <span class="item-ico"><?= $ico ?></span>
                              <div>
                                <div class="item-title"><?= esc($it['title']) ?></div>
                                <div class="item-kind"><?= esc($kind) ?></div>
                              </div>
                            </div>
                            <div class="btns">
                              <a class="view-btn open-inline" href="<?= esc($viewHere) ?>">View</a>
                            </div>
                          </div>
                        <?php endforeach; endif; ?>
                      </div>
                    </div>
                  <?php endforeach; ?>
                </div>
              </section>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </section>

    <!-- RIGHT -->
    <section class="pane">
      <h6 class="content-title">Content — <?= esc($course_name) ?></h6>
      <div id="contentPane" class="mt-2">
        <div class="p-4 text-center" style="font-size:13.5px;color:#64748b">Select an item to load content here.</div>
      </div>
    </section>
  </div>
</div>

<script>
  // Inline viewer
  const pane = document.getElementById('contentPane');
  document.addEventListener('click', async (e)=>{
    const a = e.target.closest('a.open-inline'); if (!a) return;
    e.preventDefault();
    document.querySelectorAll('.item').forEach(i=>i.classList.remove('active'));
    const host=a.closest('.item'); if (host) host.classList.add('active');
    pane.innerHTML = '<div class="p-4 text-center" style="font-size:13.5px;color:#64748b">Loading…</div>';
    try{
      const r=await fetch(a.href,{credentials:'same-origin'});
      pane.innerHTML = r.ok
        ? await r.text()
        : '<div class="p-4 text-danger">Couldn’t load content (HTTP '+r.status+').</div>';
      pane.scrollTop = 0;
    }catch(_){
      pane.innerHTML='<div class="p-4 text-danger">Network error.</div>';
    }
  });

  // Accordion (single open)
  (function(){
    const root=document.querySelector('.sem-accordion'); if(!root) return;
    const single = root.dataset.accordion==='single';
    root.querySelectorAll('.sem-head').forEach(head=>{
      head.addEventListener('click', ()=>{
        const open = head.getAttribute('aria-expanded')==='true';
        if (!open && single){
          root.querySelectorAll('.sem-head[aria-expanded="true"]').forEach(h=>{
            if(h===head) return;
            h.setAttribute('aria-expanded','false');
            h.classList.add('collapsed');
            const b=h.nextElementSibling; if(b) b.style.display='none';
          });
        }
        head.setAttribute('aria-expanded', open?'false':'true');
        head.classList.toggle('collapsed', open);
        const body=head.nextElementSibling; if(body) body.style.display=open?'none':'';
      });
    });
  })();
</script>

<?php
$bot = __DIR__.'/studentlayout_bottom.php';
$botAlt = __DIR__.'/layout_bottom.php';
require is_file($bot) ? $bot : $botAlt;
