<?php
/**
* update_student_status.php
* AJAX endpoint: change a student's status (Active / Inactive / Suspended)
*
* POST params:
* id – studentss.id (int, required)
* status – one of: Active | Inactive | Suspended (string, required)
*
* Returns JSON: { ok: true|false, message: "...", status: "..." }
*/
declare(strict_types=1);
header('Content-Type: application/json; charset=UTF-8');
/* ── bootstrap ── */
require_once __DIR__ . '/../includes/auth.php';
ec_session_start();
ec_require_login();
if (!ec_can_any(['students.manage', 'admin', 'super_admin', 'branch_admin'])) {
http_response_code(403);
echo json_encode(['ok' => false, 'message' => 'Forbidden']);
exit;
}
/* ── DB ── */
$db = ec_db();
if (!$db instanceof mysqli) {
http_response_code(500);
echo json_encode(['ok' => false, 'message' => 'Database connection failed']);
exit;
}
$db->set_charset('utf8mb4');
/* ── input & validation ── */
$student_id = (int)($_POST['id'] ?? $_POST['student_id'] ?? 0);
$status = trim((string)($_POST['status'] ?? ''));
$allowed = ['Active', 'Inactive', 'Suspended'];
if ($student_id <= 0) {
http_response_code(400);
echo json_encode(['ok' => false, 'message' => 'Invalid student id']);
exit;
}
if (!in_array($status, $allowed, true)) {
http_response_code(400);
echo json_encode(['ok' => false, 'message' => 'Invalid status. Allowed: ' . implode(', ', $allowed)]);
exit;
}
/* ── ensure column exists ── */
$colCheck = $db->prepare(
"SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'studentss' AND COLUMN_NAME = 'status'
LIMIT 1"
);
$colCheck->execute();
$colCheck->store_result();
$hasCol = $colCheck->num_rows > 0;
$colCheck->close();
if (!$hasCol) {
/* Add the column on first use (graceful migration) */
$alter = $db->query(
"ALTER TABLE studentss
ADD COLUMN `status` ENUM('Active','Inactive','Suspended') NOT NULL DEFAULT 'Active'"
);
if (!$alter) {
http_response_code(500);
echo json_encode(['ok' => false, 'message' => 'Could not create status column: ' . $db->error]);
exit;
}
}
/* ── update ── */
$st = $db->prepare("UPDATE studentss SET `status` = ? WHERE id = ?");
if (!$st) {
http_response_code(500);
echo json_encode(['ok' => false, 'message' => 'Prepare failed: ' . $db->error]);
exit;
}
$st->bind_param('si', $status, $student_id);
$ok = $st->execute();
$affected = $st->affected_rows;
$st->close();
if (!$ok) {
http_response_code(500);
echo json_encode(['ok' => false, 'message' => 'Update failed: ' . $db->error]);
exit;
}
echo json_encode([
'ok' => true,
'message' => "Status updated to $status",
'status' => $status,
'affected' => $affected,
]);