<?php 
/* ===========================================================
   studentlayout_top.php — Drawer Overlay (mobile) + Rounded (desktop)
   - Mobile: slide-over drawer with dark overlay (no blur), z-index fixed
   - Desktop: simple rounded-right sidebar (20px), NO circular blobs
   - Theme toggle persists via cookie
   - Avatar resolver (session → DB → /edenrms/uploads probe)
   =========================================================== */

declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) {
  session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Lax']);
  session_start();
}
if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
}

/* Page vars (child pages may set these before include) */
$PAGE_TITLE  = $PAGE_TITLE  ?? 'Student Dashboard';
$ACTIVE_MENU = $ACTIVE_MENU ?? ''; // dashboard | courses/modules | assess | myresults | profile

/* Student identity */
$studentName = $_SESSION['student_name']
  ?? ($_SESSION['user']['full_name'] ?? ($_SESSION['user']['username'] ?? 'Student'));
$centerRegNo = $_SESSION['center_reg_no']
  ?? ($_SESSION['student_center_reg_no'] ?? ($_SESSION['user']['center_reg_no'] ?? ''));

$studentId = 0;
if (!empty($_SESSION['student_id']))        $studentId = (int)$_SESSION['student_id'];
elseif (!empty($_SESSION['sid']))           $studentId = (int)$_SESSION['sid'];
elseif (!empty($_SESSION['student']['id'])) $studentId = (int)$_SESSION['student']['id'];

/* Brand */
$brandLogoWide = '/elms/assets/brand/eden-student-wide.png';
$brandHref     = '/elms/student/index.php';

/* -------- Resolve student photo ---------- */
$studentPhotoWeb = trim((string)($_SESSION['student_photo'] ?? ''));

try {
  require_once __DIR__ . '/../includes/db.php';
  $db = isset($mysqli) && $mysqli instanceof mysqli ? $mysqli
      : (isset($conn) && $conn instanceof mysqli ? $conn : null);

  if ($studentId > 0 && $db instanceof mysqli) {
    $sql = "SELECT COALESCE(NULLIF(photograph,''), NULLIF(photo,''), NULLIF(avatar,''), NULLIF(profile_image,'')) AS img
              FROM studentss WHERE id=? LIMIT 1";
    if ($st = $db->prepare($sql)) {
      $st->bind_param('i',$studentId);
      $st->execute();
      if ($r = $st->get_result()) {
        if ($row = $r->fetch_assoc()) {
          if (!empty($row['img'])) $studentPhotoWeb = (string)$row['img'];
        }
        $r->free();
      }
      $st->close();
    }
  }
} catch (Throwable $e) { /* ignore */ }

/* Normalize to /edenrms/uploads/... if not absolute */
$abs = $studentPhotoWeb !== '' && preg_match('~^https?://~i', $studentPhotoWeb);
if ($studentPhotoWeb !== '' && !$abs && strpos($studentPhotoWeb, '/edenrms/uploads/') !== 0) {
  $studentPhotoWeb = '/edenrms/uploads/' . ltrim($studentPhotoWeb, '/');
}

/* Filesystem fallback */
$docRoot      = rtrim($_SERVER['DOCUMENT_ROOT'] ?? '', '/');
$uploadsLocal = $docRoot . '/edenrms/uploads';
$ensureExists = function(string $webPath) use ($docRoot){
  $p = parse_url($webPath, PHP_URL_PATH) ?: '';
  return is_file($docRoot . $p);
};

if ($studentId > 0) {
  $needFsProbe = true;
  if ($studentPhotoWeb !== '') {
    if (strpos($studentPhotoWeb, '/edenrms/uploads/') === 0) {
      $needFsProbe = !$ensureExists($studentPhotoWeb);
    } else {
      $needFsProbe = false; // absolute external URL
    }
  }
  if ($needFsProbe && is_dir($uploadsLocal)) {
    $pick = function(array $files){
      $ok = ['jpg','jpeg','png','webp','gif'];
      foreach ($files as $f) {
        $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
        if (in_array($ext, $ok, true)) return $f;
      }
      return null;
    };
    $file = $pick(glob($uploadsLocal . "/student_{$studentId}_*.*", GLOB_NOSORT) ?: [])
         ?: $pick(glob($uploadsLocal . "/{$studentId}_*.*", GLOB_NOSORT) ?: []);
    if ($file) $studentPhotoWeb = '/edenrms/uploads/' . basename($file);
  }
}

$initials = mb_strtoupper(mb_substr(trim($studentName), 0, 1));
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?= esc($PAGE_TITLE) ?> — EDEN LMS</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <style>
    :root{
      --ink:#0e1a2f; --muted:#6b7280;
      --primary:#2752f4; --bg:#f6f8ff; --card:#ffffff; --line:#e7eef7;
      --eden-1:#0D1E3E; --eden-2:#153B99;
      --eden-pill-1:#0B3C89; --eden-pill-2:#2563EB;
      --r-xl:22px; --r-lg:18px; --r-md:12px; --r-sm:10px; --r-xxs:6px;
      --elev:0 8px 22px rgba(2,8,23,.08);
      --logo-h:40px; --logo-maxw:110px;
      --drawer-w: 86vw;                 /* mobile drawer width */
      --sidebar-r: 20px;                /* desktop rounded edge you requested */
    }
    .eden-portal[data-theme="dark"]{
      --bg:#0b1226; --card:#0f1a34; --line:#223056; --ink:#e5ecf7; --muted:#9fb0c9;
      --eden-1:#0a1530; --eden-2:#0c2a76; --elev:0 8px 22px rgba(0,0,0,.35);
    }

    /* Transition smoothing for theming */
    .eden-portal, .sidebar, .topbar, .search input, .btn.ghost {
      transition: background-color .18s ease, color .18s ease, border-color .18s ease, box-shadow .18s ease;
    }

    .eden-portal{min-height:100vh; background:var(--bg); color:var(--ink);
      font:14px/1.45 system-ui,-apple-system,Segoe UI,Inter,Roboto,Arial,sans-serif;}
    .eden-shell{display:grid; grid-template-columns:280px 1fr; min-height:100vh; overflow-x:hidden;}

    /* ===== Sidebar base ===== */
    .sidebar{
      position:sticky; top:0; height:100vh; padding:16px 12px; color:#fff;
      background:
        radial-gradient(70% 90% at 0% 0%, rgba(62,94,255,.28) 0%, rgba(62,94,255,0) 55%),
        linear-gradient(180deg, var(--eden-1) 0%, var(--eden-2) 100%);
      box-shadow: inset 0 0 0 1px rgba(255,255,255,.06);
      overflow:visible;
      z-index: 10;
    }
    /* Kill the old circle blobs completely */
    .sidebar::before,
    .sidebar::after { content:none !important; display:none !important; }

    /* ===== Desktop: rounded right edge (20px), no blobs ===== */
    @media (min-width: 992px){
      .sidebar{
        border-radius: 0 var(--sidebar-r) var(--sidebar-r) 0 !important;
        overflow: hidden !important;                         /* crisp curve */
        box-shadow: 0 6px 24px rgba(2,8,23,.08);             /* subtle depth */
        isolation: isolate;
      }
    }

    .brand{display:flex; align-items:center; gap:12px; padding:8px 6px 12px; margin-bottom:10px; position:relative; z-index:2}
    .brand-logo{height:40px; display:flex; align-items:center; justify-content:center;
      background:#fff; border:1px solid #c8d2eb; border-radius:8px; padding:4px 6px;}
    .eden-portal[data-theme="dark"] .brand-logo{ background:#0f1a34; border-color:#223056; }
    .brand-logo img{height:var(--logo-h); max-width:var(--logo-maxw); width:auto; display:block; object-fit:contain}
    .brand-caption{line-height:1.1}
    .brand-title{font-weight:900; letter-spacing:.02em; font-size:14px; color:#fff}
    .brand-sub{font-size:12px; color:#d5e1ff; margin-top:2px}
    .brand-divider{height:1px; background:rgba(255,255,255,.28); margin:10px 6px; position:relative; z-index:2}

    .profile-card{
      display:flex; align-items:center; gap:12px; margin:8px 6px 14px; position:relative; z-index:2;
      border:1px solid rgba(255,255,255,.18); border-radius:16px; padding:10px;
      background:linear-gradient(180deg, rgba(255,255,255,.08), rgba(255,255,255,.04));
    }
    .profile-avatar{ width:76px; height:76px; border-radius:50%; overflow:hidden;
      background:linear-gradient(135deg,#6a9cff,#2b58ff); color:#fff; font-weight:900;
      display:grid; place-items:center; border:1px solid rgba(255,255,255,.35); }
    .profile-avatar img{width:100%; height:100%; object-fit:cover; display:block}
    .profile-meta .name{font-weight:800; font-size:15px; color:#fff}
    .profile-meta .sub{font-size:12px; color:#dbe6ff}
    .profile-meta a{display:inline-block; margin-top:6px; font-weight:700; font-size:12px; color:#fff; text-decoration:none; opacity:.9}
    .profile-meta a:hover{opacity:1; text-decoration:underline}

    .side-h{font-size:12px; letter-spacing:.12em; text-transform:uppercase; opacity:.85; padding:10px 12px; position:relative; z-index:2}
    .side-nav{list-style:none; margin:0; padding:0; position:relative; z-index:2}
    .side-link{
      position:relative; display:flex; align-items:center; gap:12px;
      padding:12px 14px; margin:8px 6px; border-radius:999px;
      color:#eaf0ff; text-decoration:none; border:1px solid transparent;
      transition:transform .12s ease, background .12s ease, box-shadow .12s ease, color .12s ease;
    }
    .side-link:hover{background:linear-gradient(90deg, rgba(255,255,255,.10), rgba(255,255,255,0)); transform:translateX(1px)}
    .side-link .side-icon{width:20px; height:20px; padding:4px; border-radius:10px; background:rgba(255,255,255,.06)}
    .eden-portal[data-theme="dark"] .side-link:hover{ background:linear-gradient(90deg, rgba(255,255,255,.06), rgba(255,255,255,0)); }
    .eden-portal[data-theme="dark"] .side-link .side-icon{ background: rgba(255,255,255,.08); }

    .side-link.active{
      background:linear-gradient(90deg, var(--eden-pill-1), var(--eden-pill-2));
      color:#fff; box-shadow:0 10px 22px rgba(37,99,235,.28);
    }
    .side-link.active .side-icon{ background:rgba(255,255,255,.18); }

    .main{display:grid; grid-template-rows:auto 1fr}
    .topbar{position:sticky; top:0; z-index:50; background:rgba(255,255,255,.72);
      backdrop-filter: blur(12px); border-bottom:1px solid rgba(2,8,23,.06)}
    .eden-portal[data-theme="dark"] .topbar{background:rgba(11,18,38,.72); border-color:#223056;}
    .topbar-inner{display:flex; align-items:center; gap:14px; padding:14px 18px; padding-left: max(18px, env(safe-area-inset-left))}
    .search{flex:1; position:relative}
    .search input{height:46px; width:100%; padding:0 14px 0 40px; border-radius:12px;
      border:1px solid var(--line); background:#fff; outline:0; box-shadow:var(--elev)}
    .eden-portal[data-theme="dark"] .search input{ background:#0f1a34; border-color:#223056; color:#e5ecf7; }
    .search svg{position:absolute; left:12px; top:50%; transform:translateY(-50%); width:18px; height:18px; opacity:.6}

    .btn{display:inline-flex; align-items:center; gap:10px; padding:10px 14px; border-radius:12px;
      font-weight:700; text-decoration:none; border:1px solid transparent; cursor:pointer}
    .btn.ghost{background:#fff; border:1px solid var(--line)}
    .eden-portal[data-theme="dark"] .btn.ghost{background:#0f1a34; border-color:#223056; color:#e5ecf7}

    .wrap{padding:24px; max-width:1400px; margin:0 auto}

    /* ===== Drawer Overlay (phones & small tablets) ===== */
    @media (max-width: 992px){
      .eden-shell{ grid-template-columns: 1fr } /* no reserved column */

      /* Drawer itself — ABOVE the backdrop */
      .sidebar{
        position:fixed; inset:0 auto 0 0; width:var(--drawer-w);
        height:100dvh;
        transform: translateX(-110%);
        transition: transform .22s ease;
        overflow:auto;
        -webkit-overflow-scrolling: touch;             /* momentum scroll on iOS */
        padding-top: calc(16px + env(safe-area-inset-top));
        padding-bottom: max(16px, env(safe-area-inset-bottom));
        box-shadow: 0 20px 60px rgba(2,8,23,.35);
        z-index: 1001;                                  /* <- key */
        border-radius: 0;                                /* keep mobile as-is */
      }

      .sidebar *{ max-width: 100% }

      .eden-portal.drawer-open .sidebar{ transform:none }

      /* Backdrop — BELOW the drawer, no blur (just dim) */
      .drawer-backdrop{
        display:none;
        position:fixed; inset:0;
        background:rgba(2,8,23,.45);
        z-index: 1000;                                  /* <- below drawer */
      }
      .eden-portal.drawer-open .drawer-backdrop{ display:block }

      .brand-logo{ height:40px; border-radius:8px }
      .profile-avatar{ width:64px; height:64px }
    }
  </style>
</head>
<body>
<div class="eden-portal" id="edenPortal" data-theme="<?= esc($_COOKIE['edenTheme'] ?? 'light') ?>">
  <!-- Drawer backdrop (mobile only) -->
  <div class="drawer-backdrop" id="drawerBackdrop" hidden aria-hidden="true"></div>

  <div class="eden-shell">

    <!-- ============== SIDEBAR / DRAWER ============== -->
    <aside class="sidebar" id="sidebar" aria-label="Primary">
      <a class="brand" href="<?= esc($brandHref) ?>" aria-label="Eden LMS Home">
        <span class="brand-logo">
          <img src="<?= esc($brandLogoWide) ?>" alt="Eden Campus — Student Portal" loading="lazy" decoding="async">
        </span>
        <span class="brand-caption">
          <span class="brand-title">EDEN CAMPUS</span><br>
          <span class="brand-sub">Student Portal</span>
        </span>
      </a>
      <div class="brand-divider"></div>

      <div class="profile-card">
        <div class="profile-avatar" id="sideAvatarBox">
          <?php if ($studentPhotoWeb !== ''): ?>
            <img id="sideAvatarImg" src="<?= esc($studentPhotoWeb) ?>" alt="Profile photo">
          <?php else: ?>
            <?= esc($initials) ?>
          <?php endif; ?>
        </div>
        <div class="profile-meta">
          <div class="name"><?= esc($studentName) ?></div>
          <?php if ($centerRegNo !== ''): ?><div class="sub">Center Reg: <?= esc($centerRegNo) ?></div><?php endif; ?>
          <a href="/elms/student/profile.php">View profile →</a>
        </div>
      </div>

      <div class="side-h">Main</div>
      <ul class="side-nav" role="navigation" aria-label="Student menu">
        <li><a class="side-link <?= $ACTIVE_MENU==='dashboard'?'active':'' ?>" href="/elms/student/index.php" <?= $ACTIVE_MENU==='dashboard'?'aria-current="page"':'' ?>>
          <svg class="side-icon" viewBox="0 0 24 24" fill="none"><path d="M3 10.5 12 3l9 7.5V21a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1v-10.5Z" stroke="currentColor" stroke-width="1.7"/></svg>
          <span>Dashboard</span></a></li>

        <li><a class="side-link <?= in_array($ACTIVE_MENU,['courses','modules'],true)?'active':'' ?>" href="/elms/student/modules.php" <?= in_array($ACTIVE_MENU,['courses','modules'],true)?'aria-current="page"':'' ?>>
          <svg class="side-icon" viewBox="0 0 24 24" fill="none"><path d="M4 6l8-3 8 3v12l-8 3-8-3V6Zm0 0 8 3 8-3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
          <span>Learn</span></a></li>

        <li><a class="side-link <?= $ACTIVE_MENU==='assess'?'active':'' ?>" href="/elms/student/assessments/index.php" <?= $ACTIVE_MENU==='assess'?'aria-current="page"':'' ?>>
          <svg class="side-icon" viewBox="0 0 24 24" fill="none"><path d="M7 4h10a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Z" stroke="currentColor" stroke-width="1.7"/><path d="M9 8h6M9 12h6M9 16h4" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>
          <span>Assessments</span></a></li>

        <li><a class="side-link <?= $ACTIVE_MENU==='myresults'?'active':'' ?>" href="/elms/student/results.php" <?= $ACTIVE_MENU==='myresults'?'aria-current="page"':'' ?>>
          <svg class="side-icon" viewBox="0 0 24 24" fill="none"><path d="M4 19V5a1 1 0 0 1 1-1h3l2 3h9a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1Z" stroke="currentColor" stroke-width="1.7"/><path d="M8 14l2.5 2.5L16 11" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/></svg>
          <span>My Results</span></a></li>

        <li><a class="side-link <?= $ACTIVE_MENU==='profile'?'active':'' ?>" href="/elms/student/profile.php" <?= $ACTIVE_MENU==='profile'?'aria-current="page"':'' ?>>
          <svg class="side-icon" viewBox="0 0 24 24" fill="none"><path d="M12 6a6 6 0 0 0-6 6v3a3 3 0 0 0 3 3h1v-7H8a4 4 0 0 1 8 0v7h1a3 3 0 0 0 3-3v-3a6 6 0 0 0-6-6Z" stroke="currentColor" stroke-width="1.7"/></svg>
          <span>Profile</span></a></li>

        <li><a class="side-link" href="/elms/student/logout.php">
          <svg class="side-icon" viewBox="0 0 24 24" fill="none"><path d="M15 17l5-5-5-5M20 12H9" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/><path d="M13 21H6a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7" stroke="currentColor" stroke-width="1.7"/></svg>
          <span>Logout</span></a></li>
      </ul>
    </aside>
    <!-- ============== /SIDEBAR ============== -->

    <!-- ============== MAIN ============== -->
    <section class="main">
      <div class="topbar">
        <div class="topbar-inner">
          <button class="btn ghost" id="sidebarToggle" type="button" aria-controls="sidebar" aria-expanded="false">Sidebar</button>
          <div class="search">
            <svg viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="1.7"/><path d="M20 20l-3-3" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>
            <input type="search" placeholder="Search courses, modules, assessments…" aria-label="Search">
          </div>
          <button class="btn ghost" id="themeToggle" type="button" title="Toggle theme">Theme</button>
        </div>
      </div>

      <!-- child pages content start -->
      <div class="wrap">
