<?php
require_once __DIR__ . '/../config.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] ?? '') !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$user_id = intval($data['user_id'] ?? 0);

if ($user_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid user ID']);
    exit;
}

try {
    $stmt = $mysqli->prepare('SELECT id, full_name, email, role, status FROM users WHERE id = ? LIMIT 1');
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $stmt->bind_param('i', $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();

    if (!$user) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'User not found']);
        exit;
    }

    $new_status = ($user['status'] === 'active') ? 'inactive' : 'active';

    $update_stmt = $mysqli->prepare('UPDATE users SET status = ? WHERE id = ?');
    if (!$update_stmt) {
        throw new Exception('Prepare failed: ' . $mysqli->error);
    }
    $update_stmt->bind_param('si', $new_status, $user_id);
    if (!$update_stmt->execute()) {
        throw new Exception('Execute failed: ' . $update_stmt->error);
    }
    $update_stmt->close();

    $user['status'] = $new_status;

    echo json_encode([
        'success' => true,
        'message' => $new_status === 'active' ? 'User activated successfully' : 'User suspended successfully',
        'user' => $user
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error changing user status: ' . $e->getMessage()]);
}

$mysqli->close();
?>
