<?php
/**
 * Admin API — Update User Status (Active/Inactive)
 * Protected: Admin session required.
 */

session_start();
header('Content-Type: application/json');

// Guard: Only allow admins
if (empty($_SESSION['admin_logged_in'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

require_once '../../includes/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = $_POST['userId'] ?? null;
    $status = isset($_POST['status']) ? intval($_POST['status']) : null; // 1 for active, 0 for inactive

    if (!$userId || $status === null) {
        echo json_encode(['status' => 'error', 'message' => 'User ID and Status are required.']);
        exit;
    }

    // Security: Prevent admin from deactivating themselves
    if ($userId == $_SESSION['admin_id'] && $status === 0) {
        echo json_encode(['status' => 'error', 'message' => 'You cannot deactivate your own administrative account.']);
        exit;
    }

    try {
        $stmt = $pdo->prepare("UPDATE users SET is_active = ? WHERE id = ?");
        $stmt->execute([$status, $userId]);

        if ($stmt->rowCount() > 0) {
            $msg = $status === 1 ? 'User activated successfully.' : 'User deactivated successfully.';
            echo json_encode(['status' => 'success', 'message' => $msg]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'No changes made or user not found.']);
        }
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
