<?php
// Student course helpers: remembers the selected course in session,
// supports bundles (courses.bundle_courses), and renders course chips.

if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/db.php';

/* -- escape -- */
if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }
}

/* -- current student id from session -- */
function current_student_id(): int {
  return (int)($_SESSION['student_id'] ?? $_SESSION['student']['id'] ?? $_SESSION['user']['id'] ?? 0);
}

/* -- tiny column_exists (private to this file) -- */
function _sc_col_exists(mysqli $db, string $t, string $c): bool {
  $st = $db->prepare(
    "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
     WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1"
  );
  $st->bind_param('ss',$t,$c);
  $st->execute(); $ok=(bool)$st->get_result()->fetch_row(); $st->close();
  return $ok;
}

/* -- list the student's courses as [{id,label}] -- */
function student_courses(?int $studentId=null): array {
  global $mysqli;
  $sid = $studentId ?? current_student_id();
  if ($sid<=0 || !($mysqli instanceof mysqli)) return [];

  if (_sc_col_exists($mysqli,'enrollments','course_id')) {
    // enrollments.course_id -> courses.id
    $sql="SELECT DISTINCT c.id, COALESCE(c.course_name,c.code,CONCAT('Course ',c.id)) AS label
          FROM enrollments e JOIN courses c ON c.id=e.course_id
          WHERE e.student_id=? ORDER BY label";
  } else {
    // enrollments.batch_id -> batches.course_id -> courses.id
    $sql="SELECT DISTINCT c.id, COALESCE(c.course_name,c.code,CONCAT('Course ',c.id)) AS label
          FROM enrollments e JOIN batches b ON b.id=e.batch_id
          JOIN courses c ON c.id=b.course_id
          WHERE e.student_id=? ORDER BY label";
  }
  $st=$mysqli->prepare($sql); $st->bind_param('i',$sid);
  $st->execute(); $rs=$st->get_result();
  $out=[]; while($r=$rs->fetch_assoc()) $out[]=['id'=>(int)$r['id'],'label'=>$r['label']];
  $st->close();
  return $out;
}

/* -- small label helper -- */
function sc_course_label(int $courseId): ?string {
  global $mysqli; if(!$courseId) return null;
  $sql="SELECT COALESCE(course_name,code,CONCAT('Course ',id)) FROM courses WHERE id=? LIMIT 1";
  $st=$mysqli->prepare($sql); $st->bind_param('i',$courseId);
  $st->execute(); $st->bind_result($label); $st->fetch(); $st->close();
  return $label ?: null;
}

/* -- ACTIVE COURSE:
      - reads ?cid=
      - saves to $_SESSION['student_active_course']
      - returns 'all' (string) if 'all' is selected
      - otherwise returns int course id or 0 if none   -- */
function active_course_id(?int $studentId=null) /* mixed */ {
  $sid  = $studentId ?? current_student_id();
  $list = student_courses($sid);
  $ids  = array_column($list,'id');

  // set from request
  if (isset($_GET['cid'])) {
    $req = $_GET['cid'];
    if ($req === 'all') {
      $_SESSION['student_active_course'] = 'all';
      return 'all';
    }
    $reqId = (int)$req;
    if (in_array($reqId, $ids, true)) {
      $_SESSION['student_active_course'] = $reqId;
      return $reqId;
    }
  }

  // session value
  if (isset($_SESSION['student_active_course'])) {
    $v = $_SESSION['student_active_course'];
    if ($v === 'all') return 'all';
    $v = (int)$v;
    if (in_array($v,$ids,true)) return $v;
  }

  // default: first course (or 0 if none)
  $def = $ids[0] ?? 0;
  $_SESSION['student_active_course'] = $def ?: 'all';
  return $def ?: 'all';
}

/* -- chips (adds an "All" chip) -- */
function render_course_chips(?int $studentId=null, ?string $baseUrl=null): void {
  $sid = $studentId ?? current_student_id();
  $courses = student_courses($sid);
  if (!$courses) return;

  $active = active_course_id($sid);
  $base = $baseUrl ?: basename($_SERVER['PHP_SELF']);

  echo '<div style="display:flex;gap:8px;flex-wrap:wrap;margin:10px 0 14px">';
  // ALL chip
  $isA = ($active === 'all');
  $style = $isA ? 'background:#4338ca;color:#fff;border:1px solid #4338ca'
                : 'background:#eef2ff;color:#3730a3;border:1px solid #c7d2fe';
  $href = $base.(strpos($base,'?')!==false?'&':'?').'cid=all';
  echo '<a href="'.esc($href).'" style="text-decoration:none;padding:6px 10px;border-radius:999px;'.$style.'">All</a>';

  // per-course chips
  foreach ($courses as $c) {
    $isActive = ($active !== 'all' && (int)$active === (int)$c['id']);
    $style = $isActive
      ? 'background:#4338ca;color:#fff;border:1px solid #4338ca'
      : 'background:#eef2ff;color:#3730a3;border:1px solid #c7d2fe';
    $href = $base.(strpos($base,'?')!==false?'&':'?').'cid='.$c['id'];
    echo '<a href="'.esc($href).'" style="text-decoration:none;padding:6px 10px;border-radius:999px;'.$style.'">'.esc($c['label']).'</a>';
  }
  echo '</div>';
}
