<?php
// /edenrms/ajax/request_delete_student.php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');

try {
  @session_start();

  // anyone logged-in can request
  if (
    empty($_SESSION['admin']) &&
    empty($_SESSION['branch_admin']) &&
    empty($_SESSION['super_admin']) &&
    empty($_SESSION['user'])
  ) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Unauthorized']);
    exit;
  }

  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

  // DB bootstrap
  $db = null;
  $inc = __DIR__ . '/../includes/db.php';
  if (is_file($inc)) {
    require_once $inc;
    if (isset($conn) && $conn instanceof mysqli) $db = $conn;
  }
  if (!$db instanceof mysqli) {
    $db = new mysqli('localhost', 'root', '', 'edencamp_edencampus');
  }
  $db->set_charset('utf8mb4');

  // helpers
  $tExists = function(string $t) use ($db): bool {
    $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
    $st->bind_param('s', $t);
    $st->execute();
    $st->store_result();
    $ok = $st->num_rows > 0;
    $st->free_result();
    $st->close();
    return $ok;
  };

  $cExists = function(string $t, string $c) use ($db, $tExists): bool {
    if (!$tExists($t)) return false;
    $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?");
    $st->bind_param('ss', $t, $c);
    $st->execute();
    $st->store_result();
    $ok = $st->num_rows > 0;
    $st->free_result();
    $st->close();
    return $ok;
  };

  // ensure approval_requests table
  $db->query("CREATE TABLE IF NOT EXISTS approval_requests (
    id INT AUTO_INCREMENT PRIMARY KEY,
    type VARCHAR(64) NOT NULL,
    status ENUM('pending','approved','rejected') NOT NULL DEFAULT 'pending',
    student_id INT NULL,
    course_id INT NULL,
    ref_id INT NULL,
    payload JSON NULL,
    reason TEXT NULL,
    requested_by INT NULL,
    requested_by_name VARCHAR(191) NULL,
    requested_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    decided_by INT NULL,
    decided_at TIMESTAMP NULL,
    KEY idx_status (status),
    KEY idx_type (type),
    KEY idx_student (student_id)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  // inputs
  $sid    = (int)($_POST['student_id'] ?? $_POST['id'] ?? 0);
  $reason = trim((string)($_POST['reason'] ?? ''));

  if ($sid <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Invalid student id']);
    exit;
  }

  // snapshot
  $snap   = ['student_id' => $sid, 'reason' => $reason];
  $stuTbl = $tExists('studentss') ? 'studentss' : ($tExists('students') ? 'students' : null);

  if ($stuTbl) {
    $cols = [];
    foreach (['center_reg_no', 'reference_no', 'full_name', 'email', 'mobile'] as $c) {
      if ($cExists($stuTbl, $c)) $cols[] = $c;
    }

    if ($cols) {
      $sql = "SELECT " . implode(',', array_map(fn($c) => "`$c`", $cols)) . " FROM `$stuTbl` WHERE id=? LIMIT 1";
      $st  = $db->prepare($sql);
      $st->bind_param('i', $sid);
      $st->execute();

      $res = $st->get_result();
      if ($res && ($row = $res->fetch_assoc())) {
        $snap += $row;
      }
      $st->close();
    }
  }

  $payload = json_encode($snap, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

  $uid = (int)($_SESSION['admin']['id']
      ?? $_SESSION['branch_admin']['id']
      ?? $_SESSION['super_admin']['id']
      ?? $_SESSION['user']['id']
      ?? 0);

  $uname = (string)($_SESSION['admin']['full_name']
      ?? $_SESSION['branch_admin']['full_name']
      ?? $_SESSION['super_admin']['full_name']
      ?? $_SESSION['user']['full_name']
      ?? $_SESSION['admin']['name']
      ?? $_SESSION['user']['name']
      ?? $_SESSION['admin']['username']
      ?? $_SESSION['user']['username']
      ?? '');

  // dynamic insert based on existing columns
  $cols   = ['type', 'status', 'student_id', 'payload'];
  $values = ['delete_student', 'pending', $sid, $payload];
  $types  = 'ssis';

  if ($cExists('approval_requests', 'reason')) {
    $cols[]   = 'reason';
    $values[] = $reason;
    $types   .= 's';
  }

  if ($cExists('approval_requests', 'requested_by')) {
    $cols[]   = 'requested_by';
    $values[] = $uid;
    $types   .= 'i';
  }

  if ($cExists('approval_requests', 'requested_by_name')) {
    $cols[]   = 'requested_by_name';
    $values[] = $uname;
    $types   .= 's';
  }

  $placeholders = implode(',', array_fill(0, count($cols), '?'));
  $sql = "INSERT INTO approval_requests (" . implode(',', $cols) . ") VALUES ($placeholders)";

  $st = $db->prepare($sql);
  $st->bind_param($types, ...$values);
  $st->execute();

  $reqId = $st->insert_id;
  $st->close();

  echo json_encode([
    'ok'         => true,
    'hard'       => false,
    'request_id' => $reqId,
    'message'    => 'Delete request sent for approval.'
  ]);
  exit;

} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode([
    'ok'    => false,
    'error' => $e->getMessage()
  ]);
  exit;
}