<?php
// =============================================================
//  POST /api/v1/admin_students/toggle_status  { "id": 5, "status": "Inactive" }
//
//  Activates/deactivates a Clinical Student account — wraps app/manage_
//  clinical_students.php's toggle_status action: same permission, same
//  deactivation email notification via sendAccountEmail().
// =============================================================

require_once __DIR__ . '/../_bootstrap.php';
require_once __DIR__ . '/../../../include/account_helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Api::error(405, 'MethodNotAllowed', 'Use POST');
}

$account = api_authenticate();
api_require_permission('deactivate_user');

$body = json_decode(file_get_contents('php://input'), true) ?? [];
$userId = (int)($body['id'] ?? 0);
$newStatus = (string)($body['status'] ?? '');

if (!$userId) Api::error(422, 'ValidationError', 'id is required');
if (!in_array($newStatus, ['Active', 'Inactive'], true)) Api::error(422, 'ValidationError', 'status must be Active or Inactive');

$prevStmt = $conn->prepare('SELECT firstname, email, status FROM clinical_students WHERE id = ?');
$prevStmt->bind_param('i', $userId);
$prevStmt->execute();
$prev = $prevStmt->get_result()->fetch_assoc();
$prevStmt->close();
if (!$prev) {
    Api::error(404, 'NotFound', 'Clinical Student account not found');
}

$stmt = $conn->prepare('UPDATE clinical_students SET status = ? WHERE id = ?');
$stmt->bind_param('si', $newStatus, $userId);
if (!$stmt->execute()) {
    Api::error(500, 'ServerError', 'Could not update status. Please try again.');
}
$stmt->close();

if ($prev['status'] === 'Active' && $newStatus === 'Inactive' && !empty($prev['email'])) {
    sendAccountEmail($prev['email'], 'Your STH NRMS Account Has Been Deactivated', 'Account Deactivated', [
        "Hello <strong>{$prev['firstname']}</strong>,",
        'Your STH NRMS account has been deactivated by an administrator.',
        'If you believe this is a mistake, please contact your administrator.',
    ]);
}

$permManager = new PermissionManager($conn);
$permManager->logAudit($account->getId(), 'toggle_status', 'clinical_students', $userId, json_encode(['status' => $prev['status']]), json_encode(['status' => $newStatus]));

Api::success(['id' => $userId, 'status' => $newStatus]);
