<?php
/* ============================================================
   /elms/coordinator/index.php — safe coordinator home
   - No hard dependency on other includes (prevents 500 loops)
   - Reads session set by login.php
   - Uses DB if available (non-fatal if not)
   ============================================================ */

declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

/* --- make sure both role fields exist (some pages check either) --- */
if (!isset($_SESSION['role']) && isset($_SESSION['user']['role'])) {
  $_SESSION['role'] = $_SESSION['user']['role'];
}

/* --- minimal auth gate --- */
$allowed = ['course_coordinator','coordinator','branch_admin','super_admin'];
$role    = strtolower((string)($_SESSION['role'] ?? ($_SESSION['user']['role'] ?? '')));
if (!in_array($role, $allowed, true)) {
  header('Location: /elms/coordinator/login.php'); exit;
}

/* --- quiet but log errors --- */
ini_set('display_errors','0');
ini_set('log_errors','1');
error_reporting(E_ALL);
function logx($m){ error_log('[COORD-INDEX] '.$m); }

/* --- optional DB (never fatal) --- */
$mysqli = null;
if (is_file(__DIR__.'/../includes/db.php')) {
  try { @include __DIR__.'/../includes/db.php'; } catch (Throwable $e) { logx('includes/db.php threw: '.$e->getMessage()); }
}
if (isset($conn) && $conn instanceof mysqli && !$conn->connect_errno) {
  $mysqli = $conn;
} else {
  // fallback using common defaults; adjust if you use cPanel creds
  mysqli_report(MYSQLI_REPORT_OFF);
  $mysqli = @new mysqli('localhost','root','','edencamp_edencampus');
}
$db_ok = ($mysqli instanceof mysqli && !$mysqli->connect_errno);
if ($db_ok) { @$mysqli->set_charset('utf8mb4'); }

/* --- tiny probes (non-fatal) just to show live data --- */
$counts = ['courses'=>null,'modules'=>null,'open_assessments'=>null];
if ($db_ok) {
  try {
    if ($res = @$mysqli->query("SHOW TABLES LIKE 'courses'")) {
      if ($res->num_rows) { $counts['courses'] = (int)@$mysqli->query("SELECT COUNT(*) c FROM courses")->fetch_assoc()['c']; }
      $res->close();
    }
    if ($res = @$mysqli->query("SHOW TABLES LIKE 'course_modules'")) {
      if ($res->num_rows) { $counts['modules'] = (int)@$mysqli->query("SELECT COUNT(*) c FROM course_modules")->fetch_assoc()['c']; }
      $res->close();
    }
    if ($res = @$mysqli->query("SHOW TABLES LIKE 'lms_assessments'")) {
      if ($res->num_rows) { $counts['open_assessments'] = (int)@$mysqli->query("SELECT COUNT(*) c FROM lms_assessments WHERE NOW() BETWEEN open_at AND close_at")->fetch_assoc()['c']; }
      $res->close();
    }
  } catch (Throwable $e) { logx('probe failed: '.$e->getMessage()); }
}

/* --- session info --- */
$user = $_SESSION['user'] ?? [];
$name = $user['name'] ?? ($user['username'] ?? 'Coordinator');
$branch_csv = $user['branch_ids'] ?? '';
$branch_arr = $_SESSION['branch_ids'] ?? [];
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Coordinator — Dashboard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background:#0f172a; color:#e2e8f0; }
    .card { border:0; border-radius:16px; box-shadow:0 10px 30px rgba(0,0,0,.25); background:#111827; }
    .muted { color:#94a3b8; }
    .pill { display:inline-block; padding:.15rem .5rem; border-radius:999px; background:#1f2937; font-size:.8rem; }
  </style>
</head>
<body class="py-4">
  <div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h3 class="mb-0">Hello, <?= htmlspecialchars($name) ?></h3>
        <div class="muted">Role: <span class="pill"><?= htmlspecialchars($role) ?></span></div>
      </div>
      <div>
        <a href="/elms/coordinator/login.php" class="btn btn-outline-light btn-sm">Switch user</a>
      </div>
    </div>

    <?php if (!$db_ok): ?>
      <div class="alert alert-warning">
        Database not connected here. The page is still usable, but live counts are disabled.
      </div>
    <?php endif; ?>

    <div class="row g-3">
      <div class="col-md-4">
        <div class="card p-3">
          <div class="muted">Courses</div>
          <div class="h3 mb-0"><?= $counts['courses']===null ? '—' : (int)$counts['courses'] ?></div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3">
          <div class="muted">Modules</div>
          <div class="h3 mb-0"><?= $counts['modules']===null ? '—' : (int)$counts['modules'] ?></div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3">
          <div class="muted">Open Assessments</div>
          <div class="h3 mb-0"><?= $counts['open_assessments']===null ? '—' : (int)$counts['open_assessments'] ?></div>
        </div>
      </div>
    </div>

    <div class="card p-3 mt-4">
      <div class="muted mb-2">Branch scope</div>
      <div>
        <?php if ($branch_arr): ?>
          <?php foreach ($branch_arr as $b): ?>
            <span class="pill me-1"><?= (int)$b ?></span>
          <?php endforeach; ?>
        <?php elseif ($branch_csv): ?>
          <?php foreach (array_filter(array_map('trim', explode(',', $branch_csv))) as $b): ?>
            <span class="pill me-1"><?= htmlspecialchars($b) ?></span>
          <?php endforeach; ?>
        <?php else: ?>
          <span class="muted">No branch scope recorded.</span>
        <?php endif; ?>
      </div>
    </div>

    <div class="text-center mt-4">
      <a class="btn btn-success" href="/elms/coordinator/">Refresh</a>
    </div>
  </div>
</body>
</html>
