<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once __DIR__ . '/../includes/helpers.php'; // esc(), app_url(), go(), table_exists()
require_once __DIR__ . '/../includes/auth.php';    // require_role(), etc.
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/scope.php';

require_role(['super_admin','branch_admin']); // protect the page

// Optional page vars some layouts use
$PAGE_TITLE  = 'Summary View';
$ACTIVE_MENU = 'home';

/* ------- Read filters ------- */
$selCourseId = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;
$selBatchId  = isset($_GET['batch_id'])  ? (int)$_GET['batch_id']  : 0;

/* ------- Branch / centre selector (optional) ------- */
[$branchMap, $branchTable, $branchRefCol] = elms_all_branches($mysqli);
if (isset($_GET['branch_id'])) $_SESSION['branch_id'] = (int)$_GET['branch_id'];
$selBranchId = (int)($_SESSION['branch_id'] ?? 0);

/* ------- Dropdown data ------- */
$courses = elms_all_courses($mysqli);
$batches = elms_all_batches($mysqli, $selCourseId, $selBranchId, $branchRefCol);

/* ------- Selected batch details ------- */
$batch = $selBatchId ? elms_get_batch($mysqli, $selBatchId) : null;

/* ------- Progress bar from dates ------- */
$progressPct = 0; $startText='—'; $endText='—';
if ($batch) {
  $startText = $batch['batch_start_date'] ? date('d/m/Y', strtotime($batch['batch_start_date'])) : '—';
  $endText   = $batch['batch_end_date']   ? date('d/m/Y', strtotime($batch['batch_end_date']))   : '—';

  if (!empty($batch['batch_start_date']) && !empty($batch['batch_end_date'])) {
    $start = strtotime($batch['batch_start_date']);
    $end   = strtotime($batch['batch_end_date']);
    if ($end > $start) {
      $total = max(1, ($end - $start) / 86400);
      $done  = max(0, min($total, (time() - $start) / 86400));
      $progressPct = (int)round($done / $total * 100);
    } else {
      $progressPct = (time() >= $start) ? 100 : 0;
    }
  }
}

/* ------- Batch header fields ------- */
$batchName  = $batch['batch_name'] ?? '—';
$branchName = '—';
if ($batch && !empty($batch['branch_id']) && isset($branchMap[(int)$batch['branch_id']])) {
  $branchName = $branchMap[(int)$batch['branch_id']];
}
$status     = $batch['status'] ?? 'In progress';

/* ------- Modules (fallback if table isn’t present) ------- */
$modules = [];
$hasCourseModules = $mysqli->query("
  SELECT 1 FROM INFORMATION_SCHEMA.TABLES
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='course_modules' LIMIT 1
")->num_rows > 0;

if ($selCourseId && $hasCourseModules) {
  $st = $mysqli->prepare("SELECT id, title FROM course_modules WHERE course_id=? ORDER BY sort_order, id");
  $st->bind_param('i',$selCourseId); $st->execute();
  $rs = $st->get_result();
  while ($r=$rs->fetch_assoc()) $modules[] = ['id'=>$r['id'],'name'=>$r['title']];
}
if (!$modules) $modules = [['id'=>1,'name'=>'Module A'],['id'=>2,'name'=>'Module B']];

/* ------- KPIs ------- */
$enrolled=0; $assessIds=[]; $submittedTotal=0; $markedTotal=0;

$hasEnroll = $mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='enrollments' LIMIT 1")->num_rows > 0;
$hasSess   = $mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lms_assessment_sessions' LIMIT 1")->num_rows > 0;
$hasSubs   = $mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lms_submissions' LIMIT 1")->num_rows > 0;
$hasGrades = $mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='lms_grades' LIMIT 1")->num_rows > 0;

if ($selBatchId) {
  if ($hasEnroll) {
    $st=$mysqli->prepare("SELECT COUNT(DISTINCT student_id) AS n FROM enrollments WHERE batch_id=?");
    $st->bind_param('i',$selBatchId); $st->execute();
    $enrolled=(int)$st->get_result()->fetch_assoc()['n'];
  }
  if ($hasSess) {
    $st=$mysqli->prepare("SELECT assessment_id FROM lms_assessment_sessions WHERE batch_id=?");
    $st->bind_param('i',$selBatchId); $st->execute();
    $rs=$st->get_result(); while($r=$rs->fetch_assoc()) $assessIds[]=(int)$r['assessment_id'];
  }
  if ($assessIds) {
    $in    = implode(',', array_fill(0, count($assessIds), '?'));
    $types = str_repeat('i', count($assessIds));

    if ($hasSubs) {
      $sql="SELECT COUNT(*) AS n FROM (SELECT assessment_id, student_id FROM lms_submissions WHERE assessment_id IN ($in) GROUP BY assessment_id, student_id) t";
      $st=$mysqli->prepare($sql); $st->bind_param($types, ...$assessIds); $st->execute();
      $submittedTotal=(int)$st->get_result()->fetch_assoc()['n'];
    }
    if ($hasGrades) {
      $sql="SELECT COUNT(*) AS n FROM (SELECT assessment_id, student_id FROM lms_grades WHERE assessment_id IN ($in) GROUP BY assessment_id, student_id) g";
      $st=$mysqli->prepare($sql); $st->bind_param($types, ...$assessIds); $st->execute();
      $markedTotal=(int)$st->get_result()->fetch_assoc()['n'];
    }
  }
}

$slots = max(1, $enrolled * max(1, count($assessIds)));
$submittedPct    = (int)round(($submittedTotal / $slots) * 100);
$notSubmittedPct = 100 - $submittedPct;
$markedPct       = (int)round(($markedTotal / $slots) * 100);
$notMarkedPct    = 100 - $markedPct;

/* ------- Per-module rows ------- */
$moduleRows = array_map(function($m) use($submittedPct,$notSubmittedPct,$markedPct,$notMarkedPct){
  return [
    'name'=>$m['name'],
    'delivery'=>($submittedPct>0||$markedPct>0)?'Started':'Not started',
    'submitted'=>$submittedPct,
    'notsub'=>$notSubmittedPct,
    'marked'=>$markedPct,
    'notmarked'=>$notMarkedPct,
    'done'=>($markedPct>=80),
  ];
}, $modules);

/* ------- Build <select> HTML ------- */
$branchOptions = '<option value="0">All Branches</option>';
foreach ($branchMap as $id=>$label) { $branchOptions .= '<option value="'.$id.'"'.($id===$selBranchId?' selected':'').'>'.esc($label).'</option>'; }

$courseOptions = '<option value="0">Select Course</option>';
foreach ($courses as $id=>$label) { $courseOptions .= '<option value="'.$id.'"'.($id===$selCourseId?' selected':'').'>'.esc($label).'</option>'; }

$batchOptions = '<option value="0">Select Batch</option>';
foreach ($batches as $id=>$label) { $batchOptions .= '<option value="'.$id.'"'.($id===$selBatchId?' selected':'').'>'.esc($label).'</option>'; }

/* ===================== OPEN LAYOUT (sidebar/topbar) ===================== */
$__layoutOpened = false;
foreach (['admin_layout_top.php','layout_top.php','admin_header.php','header_admin.php'] as $f) {
  $p = __DIR__ . '/../includes/' . $f;
  if (is_file($p)) { require_once $p; $__layoutOpened = true; break; }
}
if (!$__layoutOpened) { echo '<div class="container-fluid p-3">'; }
?>
<div class="d-flex align-items-center justify-content-between mb-3">
  <h1 class="h5 m-0">Summary View</h1>
  <form class="d-flex gap-2" method="get">
    <?php if ($branchTable): ?>
      <select name="branch_id" class="form-select form-select-sm" style="min-width:200px" onchange="this.form.submit()">
        <?= $branchOptions ?>
      </select>
    <?php endif; ?>
    <select name="course_id" class="form-select form-select-sm" style="min-width:260px" onchange="this.form.submit()">
      <?= $courseOptions ?>
    </select>
    <select name="batch_id" class="form-select form-select-sm" style="min-width:260px" onchange="this.form.submit()">
      <?= $batchOptions ?>
    </select>
  </form>
</div>

<div class="card mb-3">
  <div class="card-body">
    <div class="progress" style="height:16px;">
      <div class="progress-bar bg-danger" role="progressbar" style="width: <?= $progressPct ?>%"></div>
    </div>
    <div class="d-flex justify-content-between small text-muted mt-2">
      <div><div class="fw-semibold">Commence Date</div><div><?= esc($startText) ?></div></div>
      <div><div class="fw-semibold">Completion</div><div><?= esc($endText) ?></div></div>
      <div class="text-end"><div>Today</div><div><?= date('d/m/Y') ?></div></div>
    </div>
  </div>
</div>

<div class="card mb-3">
  <div class="card-body">
    <div class="row g-2 small mb-2">
      <div class="col-md-4">
        <div class="text-uppercase text-muted">Batch</div>
        <div class="fw-semibold fs-6"><?= esc($batchName) ?></div>
      </div>
      <div class="col-md-4">
        <div class="text-uppercase text-muted">Branch</div>
        <div class="fw-semibold"><?= esc($branchName) ?></div>
      </div>
      <div class="col-md-4">
        <div class="text-uppercase text-muted">Batch Status</div>
        <div class="fw-semibold text-warning"><?= esc($status) ?></div>
      </div>
    </div>

    <ul class="nav nav-tabs small mb-3">
      <li class="nav-item"><span class="nav-link active">Semester 2 (Current)</span></li>
      <li class="nav-item"><span class="nav-link">Semester 1</span></li>
      <li class="nav-item"><span class="nav-link">Semester 3</span></li>
    </ul>

    <div class="table-responsive">
      <table class="table align-middle">
        <thead class="small">
          <tr>
            <th style="width:38%">Module</th>
            <th>Delivery</th>
            <th>Submitted</th>
            <th>Not-Submitted</th>
            <th>Marked</th>
            <th>Not-Marked</th>
            <th class="text-center">Done</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($moduleRows as $m): ?>
          <tr>
            <td><?= esc($m['name']) ?></td>
            <td><?= esc($m['delivery']) ?></td>
            <td><span class="badge bg-primary"><?= $m['submitted'] ?>%</span></td>
            <td><span class="badge bg-danger"><?= $m['notsub'] ?>%</span></td>
            <td><span class="badge bg-success"><?= $m['marked'] ?>%</span></td>
            <td><span class="badge bg-warning text-dark"><?= $m['notmarked'] ?>%</span></td>
            <td class="text-center"><?= $m['done'] ? '✅' : '' ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php
/* ===================== CLOSE LAYOUT ===================== */
$__layoutClosed = false;
foreach (['admin_layout_bottom.php','layout_bottom.php','admin_footer.php','footer_admin.php'] as $f) {
  $p = __DIR__ . '/../includes/' . $f;
  if (is_file($p)) { require_once $p; $__layoutClosed = true; break; }
}
if (!$__layoutClosed) { echo '</div>'; }
