<?php
// /elms/admin/courses/_probe_course.php
declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
$course_id = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }

$APP_ROOT = dirname(__DIR__, 2); // .../elms
@include_once $APP_ROOT.'/includes/db.php';
if (!isset($mysqli) || !($mysqli instanceof mysqli) || $mysqli->connect_errno) {
  @include_once $APP_ROOT.'/includes/config.php';
  $mysqli = @new mysqli(DB_HOST ?? 'localhost', DB_USER ?? 'root', DB_PASS ?? '', DB_NAME ?? 'edencamp_edencampus', DB_PORT ?? 3306);
  if ($mysqli && !$mysqli->connect_errno) $mysqli->set_charset('utf8mb4');
}
function t_exists($t){ global $mysqli; $t=$mysqli->real_escape_string($t);
  $r=@$mysqli->query("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='$t' LIMIT 1");
  return $r? (bool)$r->num_rows:false;
}
function c_exists($t,$c){ global $mysqli; $t=str_replace('`','``',$t); $c=$mysqli->real_escape_string($c);
  $r=@$mysqli->query("SHOW COLUMNS FROM `$t` LIKE '$c'"); return $r? (bool)$r->num_rows:false;
}

header('Content-Type: text/html; charset=utf-8');
echo "<h3>Course Content Probe</h3>";
if (!$mysqli || $mysqli->connect_errno) { echo "<div>DB connect failed.</div>"; exit; }

echo "<div>PHP ".PHP_VERSION." · DB OK</div>";

$hasCourses = t_exists('courses');
echo "<div>Table <code>courses</code>: ".($hasCourses?'exists':'missing')."</div>";

if ($hasCourses && $course_id) {
  $rs = $mysqli->query("SELECT id, name, title FROM courses WHERE id=".$course_id." LIMIT 1");
  $row = $rs->fetch_assoc();
  echo $row ? "<div>Course #$course_id found: <b>".esc($row['title'] ?? $row['name'])."</b></div>"
            : "<div>Course #$course_id NOT FOUND</div>";
}

$candidates = ['course_contents','lms_course_contents','contents','course_modules','lms_contents'];
$found = false;
foreach ($candidates as $t) {
  if (t_exists($t) && c_exists($t,'course_id')) {
    $rs = $mysqli->query("SELECT COUNT(*) FROM `$t` WHERE course_id=".$course_id);
    $cnt = (int)$rs->fetch_row()[0];
    echo "<div>Table <code>$t</code> exists, course_id rows: <b>$cnt</b></div>";
    $found = true;
  }
}
if (!$found) {
  echo "<div>No obvious *contents* table (tried: ".esc(implode(', ',$candidates)).").</div>";
}

echo "<hr><div>If the page still 500s, open <code>content.php?course_id=$course_id&debug=1</code> and copy the message here.</div>";
