<?php
/* =========================================================================
   /elms/student/profile.php — Student Profile (mobile-polished)
   - Avatar fallback to initials if image fails
   - Table scroll wrapper for small screens
   - Tighter mobile spacing & typography
   ========================================================================= */

error_reporting(E_ALL);
ini_set('display_errors','0');

/* ---- HTTPS redirect ---- */
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
  $host = $_SERVER['HTTP_HOST'] ?? 'admin.edencampus.lk';
  $uri  = $_SERVER['REQUEST_URI'] ?? '/';
  header('Location: https://' . $host . $uri, true, 301);
  exit;
}

/* ---- Session ---- */
if (session_status() === PHP_SESSION_NONE) {
  @session_set_cookie_params(['path'=>'/','httponly'=>true,'samesite'=>'Lax','secure'=>true]);
  session_start();
}

/* ---- Helpers ---- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
function app_url(string $path=''): string {
  $host = $_SERVER['HTTP_HOST'] ?? 'admin.edencampus.lk';
  $p = ($path !== '' && $path[0] !== '/') ? '/'.$path : $path;
  return 'https://' . $host . '/elms' . $p;
}
function initials(string $name): string {
  $n = trim(preg_replace('/\s+/',' ', $name));
  if ($n === '') return 'ST';
  $parts = explode(' ', $n);
  return mb_strtoupper(mb_substr($parts[0],0,1) . mb_substr($parts[count($parts)-1],0,1));
}

/* ---- Auth guard ---- */
$sid  = (int)($_SESSION['student_id'] ?? 0);
$role = strtolower((string)($_SESSION['auth']['role'] ?? ($_SESSION['user']['role'] ?? ($_SESSION['role'] ?? ''))));
if ($sid <= 0 && !in_array($role, ['super_admin','branch_admin','admin','coordinator'], true)) {
  $next = $_SERVER['REQUEST_URI'] ?? '/';
  header('Location: ' . app_url('/student/login.php?next=' . rawurlencode($next)));
  exit;
}

/* ---- DB ---- */
require_once __DIR__ . '/../includes/db.php';
if (!$mysqli instanceof mysqli) { die('DB connection missing'); }

/* ---- DB helpers ---- */
function t_exists(mysqli $db,string $t):bool{
  $t=$db->real_escape_string($t);
  $q=$db->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' LIMIT 1");
  $ok=$q && $q->num_rows>0; if($q){$q->free();} return $ok;
}
function c_exists(mysqli $db,string $t,string $c):bool{
  $t=$db->real_escape_string($t); $c=$db->real_escape_string($c);
  $q=$db->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' AND COLUMN_NAME='$c' LIMIT 1");
  $ok=$q && $q->num_rows>0; if($q){$q->free();} return $ok;
}
function fetch_one_assoc(mysqli_stmt $st): ?array {
  $row=null;
  if (method_exists($st,'get_result')) {
    $res=$st->get_result(); if($res){ $row=$res->fetch_assoc(); $res->free(); }
  } else {
    $meta=$st->result_metadata();
    if($meta){ $fields=$meta->fetch_fields(); $data=[]; $bind=[];
      foreach($fields as $f){ $data[$f->name]=null; $bind[]=&$data[$f->name]; }
      call_user_func_array([$st,'bind_result'],$bind);
      if($st->fetch()) $row=$data;
    }
  }
  return $row;
}

/* ---- RMS photo helper (your cPanel path) ---- */
function try_photo_url(?string $file): ?string {
  $f = trim((string)$file);
  if ($f === '' || strtolower($f) === 'null') return null;
  if (preg_match('~^https?://~i', $f)) return $f;
  $f = basename($f);

  $host = $_SERVER['HTTP_HOST'] ?? 'admin.edencampus.lk';
  $doc  = rtrim($_SERVER['DOCUMENT_ROOT'] ?? '', '/');

  $rel  = "/edenrms/uploads/$f";
  if ($doc && is_file($doc . $rel)) return "https://$host$rel";
  foreach (["/edenrms/uploads/students/$f","/uploads/$f","/uploads/students/$f"] as $alt) {
    if ($doc && is_file($doc . $alt)) return "https://$host$alt";
  }
  return "https://$host$rel"; // best-effort
}

/* ---- Pick student ---- */
$student_id = $sid;
if ($student_id <= 0 && in_array($role, ['super_admin','branch_admin','admin','coordinator'], true)) {
  $student_id = filter_input(INPUT_GET,'student_id',FILTER_VALIDATE_INT) ?: 0;
}
if ($student_id <= 0) { http_response_code(403); die('Forbidden — please log in as a student.'); }

/* ========================= 1) Student + center/branch + photo ========================= */
$student=null; $branch_name=''; $photo_url=null;
$tbl_stu = t_exists($mysqli,'studentss') ? 'studentss' : (t_exists($mysqli,'students') ? 'students' : null);

if ($tbl_stu) {
  if ($tbl_stu==='studentss') {
    $sql="SELECT id, full_name, center_reg_no, photograph, course_id, branch_id, branch_name
            FROM studentss WHERE id=? LIMIT 1";
  } else {
    $sql="SELECT id, name AS full_name, course_reg_no AS center_reg_no, NULL AS photograph, NULL AS course_id, NULL AS branch_id, NULL AS branch_name
            FROM students WHERE id=? LIMIT 1";
  }
  $st=$mysqli->prepare($sql); $st->bind_param('i',$student_id); $st->execute(); $student=fetch_one_assoc($st); $st->close();

  $branch_name = (string)($student['branch_name'] ?? '');
  if ($branch_name==='' && !empty($student['branch_id']) && t_exists($mysqli,'branches')) {
    $bid=(int)$student['branch_id'];
    $st=$mysqli->prepare("SELECT name FROM branches WHERE id=? LIMIT 1");
    $st->bind_param('i',$bid); $st->execute(); $b=fetch_one_assoc($st); $st->close();
    $branch_name = (string)($b['name'] ?? '');
  }
  $photo_url = try_photo_url($student['photograph'] ?? null);
}

/* ========================= 2) Courses via enrollments → batches → courses ============== */
$courses=[]; $course_rows=[]; $latest_course_id=null; $latest_batch=null;

if (t_exists($mysqli,'enrollments') && t_exists($mysqli,'batches')) {
  $st=$mysqli->prepare("
    SELECT e.*, b.batch_name, b.batch_start_date, b.batch_end_date, b.course_id
      FROM enrollments e
      JOIN batches b ON b.id=e.batch_id
     WHERE e.student_id=?
     ORDER BY e.enrollment_date DESC, e.id DESC
  ");
  $st->bind_param('i',$student_id); $st->execute();
  $rows=[]; if(method_exists($st,'get_result')){ $res=$st->get_result(); if($res){ while($r=$res->fetch_assoc()) $rows[]=$r; $res->free(); } }
  $st->close();

  foreach ($rows as $ix=>$r) { $course_rows[]=$r; if ($ix===0){ $latest_course_id=(int)$r['course_id']; $latest_batch=$r; } }

  if ($course_rows && t_exists($mysqli,'courses') && c_exists($mysqli,'courses','id')) {
    $ids = array_values(array_unique(array_map(fn($r)=>(int)$r['course_id'], $course_rows)));
    if ($ids) {
      $in = implode(',', array_map('intval',$ids));
      $q  = $mysqli->query("SELECT id, course_name, code, months FROM courses WHERE id IN ($in)");
      if ($q){ while($c=$q->fetch_assoc()) $courses[(int)$c['id']]=$c; $q->free(); }
    }
  }
}
$primary_course = $latest_course_id && isset($courses[$latest_course_id]) ? $courses[$latest_course_id] : (reset($courses) ?: null);

/* ========================= 3) Exams (simple counts) =================================== */
$exam=['total'=>null,'done'=>0,'pending'=>null];
if (t_exists($mysqli,'exams')) {
  $ids = array_keys($courses);
  $q = ($ids && c_exists($mysqli,'exams','course_id'))
      ? $mysqli->query("SELECT COUNT(*) AS n FROM exams WHERE course_id IN (".implode(',', array_map('intval',$ids)).")")
      : $mysqli->query("SELECT COUNT(*) AS n FROM exams");
  $total=0; if($q){ $total=(int)($q->fetch_assoc()['n'] ?? 0); $q->free(); }
  $exam=['total'=>$total,'done'=>0,'pending'=>$total];
}

/* ========================= 4) Assessments + submissions =============================== */
$asm=['total'=>0,'submitted'=>0,'pending'=>0,'list'=>[]];
if (t_exists($mysqli,'lms_assessments')) {
  $where=" (a.active=1) ";
  $ids=array_keys($courses);
  if ($ids && c_exists($mysqli,'lms_assessments','course_id')) $where .= " AND a.course_id IN (".implode(',', array_map('intval',$ids)).") ";
  $open  = c_exists($mysqli,'lms_assessments','available_from') ? " (a.available_from IS NULL OR a.available_from<=NOW()) " : " 1 ";
  $close = c_exists($mysqli,'lms_assessments','available_to')   ? " (a.available_to   IS NULL OR a.available_to  >=NOW()) " : " 1 ";

  $sql="SELECT a.id, a.title, ".(c_exists($mysqli,'lms_assessments','course_id')?'a.course_id':'NULL AS course_id')."
          FROM lms_assessments a
         WHERE $where AND $open AND $close";
  $st=$mysqli->prepare($sql); $st->execute();
  $ass=[]; if(method_exists($st,'get_result')){ $res=$st->get_result(); if($res){ while($r=$res->fetch_assoc()) $ass[]=$r; $res->free(); } }
  $st->close();

  $asm['total']=count($ass);
  $submitted=[];
  if ($ass && t_exists($mysqli,'lms_submissions') && c_exists($mysqli,'lms_submissions','assessment_id') && c_exists($mysqli,'lms_submissions','student_id')) {
    $aids = implode(',', array_map('intval', array_column($ass,'id')));
    $q=$mysqli->query("SELECT DISTINCT assessment_id FROM lms_submissions WHERE student_id=".(int)$student_id." AND assessment_id IN ($aids)");
    if($q){ while($r=$q->fetch_assoc()) $submitted[]=(int)$r['assessment_id']; $q->free(); }
  }
  foreach($ass as $r){ if(!in_array((int)$r['id'],$submitted,true)) $asm['list'][]=$r; }
  $asm['submitted']=count($submitted);
  $asm['pending']=max(0,$asm['total']-$asm['submitted']);
}

/* ========================= 5) Payments + next due (payment_schedule) ================== */
$pay=['paid_total'=>0.0,'last'=>[],'next_due'=>null,'next_due_amt'=>null,'cert_paid'=>false];

if (t_exists($mysqli,'payments')) {
  $q=$mysqli->query("
    SELECT id, plan_id, amount, fee_type, items_json, payment_method, date_paid
      FROM payments
     WHERE student_id=".(int)$student_id."
     ORDER BY date_paid DESC, id DESC LIMIT 7
  ");
  if($q){
    while($r=$q->fetch_assoc()){
      $pay['paid_total'] += (float)($r['amount'] ?? 0);
      $pay['last'][] = $r;
      if (!empty($r['fee_type']) && stripos($r['fee_type'],'cert')!==false) $pay['cert_paid']=true;
      if (!empty($r['items_json']) && stripos($r['items_json'],'certificate')!==false) $pay['cert_paid']=true;
    }
    $q->free();
  }
}
if (t_exists($mysqli,'payment_schedule') && c_exists($mysqli,'payment_schedule','student_id')) {
  $today = date('Y-m-d');
  $st=$mysqli->prepare("
    SELECT due_date, course_fee_lkr, registration_fee_lkr, certificate_fee_usd
      FROM payment_schedule
     WHERE student_id=? AND (due_date IS NOT NULL AND due_date>=?)
     ORDER BY due_date ASC, id ASC LIMIT 1
  ");
  $st->bind_param('is',$student_id,$today); $st->execute(); $row=fetch_one_assoc($st); $st->close();
  if ($row) {
    $pay['next_due'] = $row['due_date'];
    $lkr = (float)($row['course_fee_lkr'] ?? 0) + (float)($row['registration_fee_lkr'] ?? 0);
    $usd = (float)($row['certificate_fee_usd'] ?? 0);
    $pay['next_due_amt'] = $usd>0 ? number_format($lkr,2)." LKR + ".number_format($usd,2)." USD"
                                  : ($lkr>0 ? number_format($lkr,2)." LKR" : null);
  }
}

/* ---- Layout includes ---- */
$top1=__DIR__.'/studentlayout_top.php';
$bot1=__DIR__.'/studentlayout_bottom.php';
$top2=__DIR__.'/layout_top.php';
$bot2=__DIR__.'/layout_bottom.php';
$top = is_file($top1)?$top1:(is_file($top2)?$top2:null);
$bot = is_file($bot1)?$bot1:(is_file($bot2)?$bot2:null);

$PAGE_TITLE='Profile';
$ACTIVE_MENU='profile';

if ($top) require $top; else {
  echo "<!doctype html><meta charset='utf-8'><meta name=viewport content='width=device-width,initial-scale=1'><title>Profile</title>";
  echo "<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css'><div class='container py-3'>";
}
?>

<style>
:root{
  --ink:#0f172a; --muted:#667085; --line:#e9eef5; --card:#ffffff; --bg:#f6f8fb;
  --grad1:#0b4ea2; --grad2:#1c7ed6; --accent:#2563eb; --ok:#16a34a; --warn:#f59e0b;
}

/* ===== layout ===== */
.profile-wrap{max-width: min(1600px, 96vw); margin: 14px auto; padding: 0 6px}
.hero{
  background:linear-gradient(90deg,var(--grad1),var(--grad2));
  color:#fff; border-radius:18px; padding:22px;
  display:flex; align-items:center; gap:18px;
  box-shadow:0 10px 28px rgba(10,60,120,.18)
}
.hero .avatar{width:96px;height:96px;border-radius:16px;border:2px solid rgba(255,255,255,.95);object-fit:cover;background:#e8eef6}
.hero .avatar-fallback{width:96px;height:96px;border-radius:16px;display:none;align-items:center;justify-content:center;background:rgba(255,255,255,.12);border:2px solid rgba(255,255,255,.95);font-weight:900;font-size:28px}
.hero h1{margin:0;font-weight:900;font-size:24px}
.hero .sub{opacity:.97}

.grid{display:grid;grid-template-columns:1.25fr 1.25fr 1fr;gap:16px;margin-top:14px}
.cardx{background:var(--card);border:1px solid var(--line);border-radius:18px;box-shadow:0 12px 26px rgba(2,8,20,.05);overflow:hidden}
.card-head{padding:12px 16px;background:linear-gradient(135deg,var(--grad1),var(--grad2));color:#fff;font-weight:800}
.card-body{padding:18px}

.label{font-size:12px;color:var(--muted)}
.value{font-weight:700}
.kv{display:grid;grid-template-columns:120px 1fr;gap:6px 12px}

.badges{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}
.badgechip{border:1px solid #e7eef7;background:#fff;border-radius:999px;padding:6px 10px;font-size:12px}

.list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}
.list-item{border:1px dashed #e8eef6;border-radius:10px;padding:10px;background:#fbfdff}
.list-item a{text-decoration:none;color:inherit}

.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:10px}
.stat{background:#f9fbff;border:1px solid #ecf2fa;border-radius:12px;padding:12px;text-align:center}
.stat h3{margin:0;font-weight:900}

.table-min{width:100%;border-collapse:collapse;min-width:560px}
.table-min th,.table-min td{padding:8px;border-top:1px solid #eef2f7}
.emph-ok{color:var(--ok);font-weight:800}
.emph-warn{color:var(--warn);font-weight:800}

/* NEW: mobile table wrapper */
.table-wrap{overflow:auto; -webkit-overflow-scrolling:touch; border:1px solid var(--line); border-radius:12px; background:#fff}

/* Mobile polish */
@media (max-width:1200px){ .grid{grid-template-columns:1fr 1fr} }
@media (max-width:800px){ .grid{grid-template-columns:1fr} .stats{grid-template-columns:1fr 1fr} }
@media (max-width:600px){
  .hero{padding:16px}
  .hero .avatar{width:84px;height:84px;border-radius:14px}
  .hero .avatar-fallback{width:84px;height:84px;border-radius:14px; font-size:24px}
  .hero h1{font-size:20px}
  .kv{grid-template-columns:1fr;gap:4px 8px}
  .card-body{padding:14px}
}
</style>

<div class="profile-wrap">
  <!-- HERO -->
  <div class="hero">
    <!-- Image + fallback both present; JS will show fallback on error -->
    <img class="avatar" id="profileAvatarImg" src="<?= esc($photo_url ?? '') ?>" alt="Profile photo" loading="lazy" decoding="async">
    <div class="avatar-fallback" id="profileAvatarFallback" aria-hidden="true"><?= esc(initials((string)($student['full_name'] ?? 'Student'))) ?></div>

    <div>
      <h1><?= esc($student['full_name'] ?? 'Student') ?></h1>
      <div class="sub">
        Center Reg: <strong><?= esc($student['center_reg_no'] ?? '—') ?></strong>
        <?php if ($branch_name): ?> · Center: <strong><?= esc($branch_name) ?></strong><?php endif; ?>
      </div>
      <?php if ($primary_course): ?>
        <div class="sub">Primary course: <strong><?= esc($primary_course['course_name']) ?></strong><?= !empty($primary_course['code']) ? ' ('.esc($primary_course['code']).')':'' ?></div>
      <?php endif; ?>
    </div>
  </div>

  <div class="grid">

    <!-- Profile & Courses -->
    <div class="cardx">
      <div class="card-head">Profile & Courses</div>
      <div class="card-body">
        <?php if ($latest_batch): ?>
          <div class="kv" style="margin-bottom:8px">
            <div class="label">Batch</div><div class="value"><?= esc($latest_batch['batch_name'] ?? '—') ?></div>
            <div class="label">Start</div><div class="value"><?= esc($latest_batch['batch_start_date'] ?? '—') ?></div>
            <div class="label">End</div><div class="value"><?= esc($latest_batch['batch_end_date'] ?? '—') ?></div>
          </div>
        <?php endif; ?>

        <div class="label" style="margin-top:2px">Enrolled courses</div>
        <?php if ($courses): ?>
          <ul class="list" style="margin-top:6px">
            <?php foreach ($courses as $c): ?>
              <li class="list-item">
                <div class="value"><?= esc($c['course_name']) ?><?= !empty($c['code']) ? ' · '.esc($c['code']) : '' ?></div>
                <?php if (!empty($c['months'])): ?><div class="label"><?= (int)$c['months'] ?> months</div><?php endif; ?>
              </li>
            <?php endforeach; ?>
          </ul>
        <?php else: ?>
          <div class="label">No course enrollments found.</div>
        <?php endif; ?>

        <div class="badges">
          <span class="badgechip"><?= count($courses) ?> course(s)</span>
          <?php if ($exam['total'] !== null): ?><span class="badgechip"><?= (int)$exam['total'] ?> exams</span><?php endif; ?>
          <span class="badgechip"><?= (int)$asm['total'] ?> assessments</span>
        </div>
      </div>
    </div>

    <!-- Exams & Assessments -->
    <div class="cardx">
      <div class="card-head">Exams</div>
      <div class="card-body">
        <div class="stats">
          <div class="stat"><div class="label">Total</div><h3><?= $exam['total']===null ? 'N/A' : (int)$exam['total'] ?></h3></div>
          <div class="stat"><div class="label">Done</div><h3><?= (int)$exam['done'] ?></h3></div>
          <div class="stat"><div class="label">Pending</div><h3 class="<?= ($exam['pending']??0)>0 ? 'emph-warn':'' ?>"><?= $exam['pending']===null ? 'N/A' : (int)$exam['pending'] ?></h3></div>
          <div class="stat"><div class="label">Courses</div><h3><?= count($courses) ?></h3></div>
        </div>
      </div>

      <div class="card-head">Pending Assessments</div>
      <div class="card-body">
        <?php if (!empty($asm['list'])): ?>
          <ul class="list">
            <?php foreach (array_slice($asm['list'],0,8) as $a):
              $cid  = (int)($a['course_id'] ?? ($primary_course['id'] ?? 0));
              $href = app_url('/student/assessments/submit.php?assessment_id='.(int)$a['id'].($cid ? '&course_id='.$cid : ''));
            ?>
              <li class="list-item"><a href="<?= esc($href) ?>"><?= esc($a['title'] ?? 'Assessment') ?></a></li>
            <?php endforeach; ?>
          </ul>
          <?php if (count($asm['list'])>8): ?>
            <div class="label" style="margin-top:6px">…and <?= count($asm['list'])-8 ?> more</div>
          <?php endif; ?>
        <?php else: ?>
          <div class="label">No pending assessments 🎉</div>
        <?php endif; ?>

        <div class="stats" style="margin-top:10px">
          <div class="stat"><div class="label">Open</div><h3><?= (int)$asm['total'] ?></h3></div>
          <div class="stat"><div class="label">Submitted</div><h3 class="emph-ok"><?= (int)$asm['submitted'] ?></h3></div>
          <div class="stat"><div class="label">Pending</div><h3 class="<?= $asm['pending']>0 ? 'emph-warn':'' ?>"><?= (int)$asm['pending'] ?></h3></div>
          <div class="stat"><div class="label">Status</div><h3><?= $asm['pending']>0 ? 'In progress' : 'All done' ?></h3></div>
        </div>
      </div>
    </div>

    <!-- Fees & Payments -->
    <div class="cardx">
      <div class="card-head">Course Fees & Payments</div>
      <div class="card-body">
        <div class="d-flex justify-content-between" style="gap:14px; flex-wrap:wrap">
          <div>
            <div class="label">Total paid</div>
            <div class="value" style="font-size:20px">LKR <?= number_format((float)$pay['paid_total'],2) ?></div>
          </div>
          <div>
            <div class="label">Next due (date)</div>
            <div class="value"><?= esc($pay['next_due'] ?? '—') ?></div>
            <?php if ($pay['next_due_amt']): ?>
              <div class="label">Next due (amount): <?= esc($pay['next_due_amt']) ?></div>
            <?php endif; ?>
          </div>
        </div>

        <div class="mt-2">
          <span class="label">Certificate fee:</span>
          <span class="<?= $pay['cert_paid'] ? 'emph-ok' : 'emph-warn' ?>" style="margin-left:8px">
            <?= $pay['cert_paid'] ? 'PAID' : 'NOT PAID' ?>
          </span>
        </div>

        <div class="label" style="margin-top:12px">Recent payments</div>
        <?php if (!empty($pay['last'])): ?>
          <div class="table-wrap">
            <table class="table-min">
              <thead>
                <tr><th class="label">Date</th><th class="label">Amount (LKR)</th><th class="label">Method</th><th class="label">Type</th></tr>
              </thead>
              <tbody>
              <?php foreach ($pay['last'] as $r): ?>
                <tr>
                  <td><?= esc($r['date_paid']) ?></td>
                  <td><?= number_format((float)$r['amount'],2) ?></td>
                  <td><?= esc($r['payment_method'] ?? '-') ?></td>
                  <td><?= esc($r['fee_type'] ?? '-') ?></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php else: ?>
          <div class="label">No receipts found.</div>
        <?php endif; ?>

        <div class="label" style="margin-top:6px">For full history, contact your center or open the payments section.</div>
      </div>
    </div>

  </div>
</div>

<!-- Avatar fallback (if image fails) -->
<script>
(function(){
  const img = document.getElementById('profileAvatarImg');
  const fb  = document.getElementById('profileAvatarFallback');
  if (!img || !fb) return;
  const showFB = ()=>{ fb.style.display='flex'; img.style.display='none'; };
  // no src or network error
  if (!img.getAttribute('src')) { showFB(); return; }
  img.addEventListener('error', showFB, {once:true});
})();
</script>

<?php if ($bot) require $bot; else echo '</div>'; ?>
