<?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/admin/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); }

/* --- DB connection --- */
$mysqli = null;

try {
  $db_file = __DIR__ . '/../../includes/db.php';

  if (!is_file($db_file)) {
    throw new Exception('DB file not found: ' . $db_file);
  }

  require_once $db_file;

  if (isset($conn) && $conn instanceof mysqli) {
    $mysqli = $conn;
  } elseif (isset($mysqli) && $mysqli instanceof mysqli) {
    // already assigned from db.php
  } else {
    throw new Exception('No mysqli connection variable found from includes/db.php');
  }

  if ($mysqli->connect_errno) {
    throw new Exception('DB connect error: ' . $mysqli->connect_error);
  }

  $mysqli->set_charset('utf8mb4');
  $db_ok = true;

} catch (Throwable $e) {
  logx('DB failed: ' . $e->getMessage());
  $mysqli = null;
  $db_ok = false;
}




/* --- Dashboard counts --- */
$counts = [
  'courses' => null,
  'modules' => null,
  'open_assessments' => null
];

function table_exists(mysqli $db, string $table): bool {
  $table = $db->real_escape_string($table);
  $res = $db->query("SHOW TABLES LIKE '{$table}'");
  $ok = ($res && $res->num_rows > 0);
  if ($res) $res->close();
  return $ok;
}

function column_exists(mysqli $db, string $table, string $column): bool {
  $table = $db->real_escape_string($table);
  $column = $db->real_escape_string($column);
  $res = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");
  $ok = ($res && $res->num_rows > 0);
  if ($res) $res->close();
  return $ok;
}

function count_table(mysqli $db, string $table, string $where = ''): int {
  $sql = "SELECT COUNT(*) AS c FROM `{$table}`";
  if ($where !== '') {
    $sql .= " WHERE {$where}";
  }

  $res = $db->query($sql);
  if (!$res) return 0;

  $row = $res->fetch_assoc();
  $res->close();

  return (int)($row['c'] ?? 0);
}

if ($db_ok && $mysqli instanceof mysqli) {
  try {
    if (table_exists($mysqli, 'courses')) {
      $counts['courses'] = count_table($mysqli, 'courses');
    }

    if (table_exists($mysqli, 'course_modules')) {
      $counts['modules'] = count_table($mysqli, 'course_modules');
    } elseif (table_exists($mysqli, 'lms_modules')) {
      $counts['modules'] = count_table($mysqli, 'lms_modules');
    }

    if (table_exists($mysqli, 'lms_assessments')) {
      if (
        column_exists($mysqli, 'lms_assessments', 'open_at') &&
        column_exists($mysqli, 'lms_assessments', 'close_at')
      ) {
        $counts['open_assessments'] = count_table(
          $mysqli,
          'lms_assessments',
          "NOW() BETWEEN open_at AND close_at"
        );
      } elseif (column_exists($mysqli, 'lms_assessments', 'status')) {
        $counts['open_assessments'] = count_table(
          $mysqli,
          'lms_assessments',
          "LOWER(status) IN ('open','active','published')"
        );
      } else {
        $counts['open_assessments'] = count_table($mysqli, 'lms_assessments');
      }
    }

  } catch (Throwable $e) {
    logx('count 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/admin/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/admin/coordinator/index.php">Refresh</a>
    </div>
  </div>
</body>
</html>
