<?php
/**
 * update_lms_status.php
 * AJAX endpoint: Change LMS login status
 *
 * POST params:
 *   student_id  - studentss.id (int, required)
 *   status      - 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['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 = 'lms_status'
     LIMIT 1"
);
$colCheck->execute();
$colCheck->store_result();
$hasCol = $colCheck->num_rows > 0;
$colCheck->close();

if (!$hasCol) {
    /* Auto-migration: add column on first use */
    $alter = $db->query(
        "ALTER TABLE studentss
         ADD COLUMN lms_status ENUM('Active','Inactive','Suspended') NOT NULL DEFAULT 'Active'"
    );
    if (!$alter) {
        http_response_code(500);
        echo json_encode(['ok' => false, 'message' => 'Could not create lms_status column: ' . $db->error]);
        exit;
    }
}

/* ── Update Status ── */
$stmt = $db->prepare("UPDATE studentss SET lms_status = ? WHERE id = ?");
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'Prepare failed: ' . $db->error]);
    exit;
}

$stmt->bind_param('si', $status, $student_id);
$ok = $stmt->execute();
$affected = $stmt->affected_rows;
$stmt->close();

if (!$ok) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'message' => 'Update failed: ' . $db->error]);
    exit;
}

echo json_encode([
    'ok' => true,
    'message' => "LMS status updated to $status",
    'status' => $status,
    'affected' => $affected,
]);