<?php
require_once '../includes/init.php';

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    jsonResponse(false, 'Admin access required');
}

$db = getDB();
$userId = intval($_POST['user_id'] ?? 0);

if (!$userId) {
    jsonResponse(false, 'User ID required');
}

// Check if user exists and is blocked
$stmt = $db->prepare("SELECT id, name, unique_id, status FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    jsonResponse(false, 'User not found');
}

if ($user['status'] !== 'blocked') {
    jsonResponse(false, 'User is not blocked');
}

// Unblock user
$stmt = $db->prepare("UPDATE users SET status = 'approved' WHERE id = ?");
$result = $stmt->execute([$userId]);

if ($result) {
    // Log the action
    $stmt = $db->prepare("
        INSERT INTO activity_logs (user_id, action, details, created_at) 
        VALUES (?, 'unblock_user', ?, NOW())
    ");
    $stmt->execute([$_SESSION['user_id'], json_encode([
        'unblocked_user_id' => $userId,
        'unblocked_user_name' => $user['name'],
        'unblocked_user_unique_id' => $user['unique_id']
    ])]);
    
    jsonResponse(true, 'User unblocked successfully', [
        'user_id' => $userId,
        'user_name' => $user['name'],
        'user_unique_id' => $user['unique_id'],
        'new_status' => 'approved'
    ]);
} else {
    jsonResponse(false, 'Failed to unblock user');
}
?>
