<?php
declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../../includes/db.php';
if (is_file(__DIR__ . '/../../includes/auth.php')) {
  require_once __DIR__ . '/../../includes/auth.php';
  if (function_exists('require_role')) require_role(['super_admin','branch_admin']);
}

$course_id = (int)($_GET['course_id'] ?? 0);
$module_id = (int)($_GET['module_id'] ?? 0);
$url       = (string)($_GET['url'] ?? '');

if (!$course_id || !$module_id || !$url) {
  http_response_code(400);
  echo 'Missing params'; exit;
}

$mysqli = $mysqli ?? ($conn ?? new mysqli('localhost','root','','edencamp_edencampus'));
$mysqli->set_charset('utf8mb4');

/* ---- helpers ---- */
function t_exists(mysqli $db,string $t): bool {
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
  $st->bind_param('s',$t); $st->execute();
  $ok=(bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}
function first_existing(mysqli $db,string $t,array $cols): ?string{
  foreach($cols as $c){
    $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
    $st->bind_param('ss',$t,$c); $st->execute();
    $ok=(bool)$st->get_result()->fetch_row(); $st->close();
    if($ok) return $c;
  } return null;
}
function detect_content_table(mysqli $db): array{
  foreach (['lms_content','lms_contents','lms_module_contents','module_contents','lms_content_items'] as $T) {
    if (!t_exists($db,$T)) continue;
    $mid=first_existing($db,$T,['module_id','lms_module_id']);
    $url=first_existing($db,$T,['url','file_url','path','link']);
    if($mid && $url) return ['T'=>$T,'mid'=>$mid,'url'=>$url];
  } return ['T'=>null];
}

$CT = detect_content_table($mysqli);

/* ---- delete DB row ---- */
if ($CT['T']) {
  $sql="DELETE FROM `{$CT['T']}` WHERE `{$CT['mid']}`=? AND {$CT['url']}=? LIMIT 1";
  if ($st=$mysqli->prepare($sql)) { $st->bind_param('is',$module_id,$url); $st->execute(); $st->close(); }
}

/* ---- delete file (inside /elms/uploads/games only) ---- */
$root = realpath(dirname(__DIR__,2)); // /elms
$gamesDir = $root . '/uploads/games';
$path = parse_url($url, PHP_URL_PATH) ?: '';
$disk = $path ? $root . substr($path, strlen('/elms')) : '';
if (!is_file($disk) || strpos($disk,$gamesDir)!==0) {
  $disk = $gamesDir . '/' . basename($path);
}
if (is_file($disk) && strpos($disk,$gamesDir)===0) { @unlink($disk); }

header("Location: game_builder.php?course_id=$course_id&module_id=$module_id&deleted=1");
exit;
