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

// Check admin access
if (!isAuthenticated() || !$_SESSION['is_admin']) {
    redirect(APP_URL . '/login.php');
}

$db = getDB();
$message = '';
$error = '';

// Handle user actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $userId = intval($_POST['user_id'] ?? 0);
    
    if (!$userId) {
        $error = 'Invalid user ID';
    } else {
        switch ($action) {
            case 'approve':
                $stmt = $db->prepare("UPDATE users SET status = 'approved' WHERE id = ? AND is_admin = 0");
                $stmt->execute([$userId]);
                $message = 'User approved successfully';
                
                // Log activity
                $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, 'user_approve', 'Approved user $userId', ?)");
                $stmt->execute([$_SESSION['user_id'], $_SERVER['REMOTE_ADDR']]);
                break;
                
            case 'reject':
                // Optionally delete the user or mark as rejected
                $stmt = $db->prepare("DELETE FROM users WHERE id = ? AND is_admin = 0 AND status = 'pending'");
                $stmt->execute([$userId]);
                $message = 'User rejected and removed';
                break;
                
            case 'block':
                $stmt = $db->prepare("UPDATE users SET status = 'blocked' WHERE id = ? AND is_admin = 0");
                $stmt->execute([$userId]);
                
                // Invalidate all sessions
                $stmt = $db->prepare("UPDATE sessions SET is_valid = 0 WHERE user_id = ?");
                $stmt->execute([$userId]);
                
                $message = 'User blocked and logged out from all devices';
                
                // Log activity
                $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, 'user_block', 'Blocked user $userId', ?)");
                $stmt->execute([$_SESSION['user_id'], $_SERVER['REMOTE_ADDR']]);
                break;
                
            case 'unblock':
                $stmt = $db->prepare("UPDATE users SET status = 'approved' WHERE id = ? AND is_admin = 0");
                $stmt->execute([$userId]);
                
                // Clear any invalid sessions for this user
                $stmt = $db->prepare("UPDATE sessions SET is_valid = 1 WHERE user_id = ?");
                $stmt->execute([$userId]);
                
                // Update last activity to current time
                $stmt = $db->prepare("UPDATE users SET last_activity = NOW() WHERE id = ?");
                $stmt->execute([$userId]);
                
                // Get user details for logging
                $stmt = $db->prepare("SELECT name, unique_id FROM users WHERE id = ?");
                $stmt->execute([$userId]);
                $userInfo = $stmt->fetch();
                
                $message = 'User unblocked successfully';
                
                // Log activity
                $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address, created_at) VALUES (?, 'user_unblock', ?, ?, NOW())");
                $stmt->execute([$_SESSION['user_id'], json_encode([
                    'unblocked_user_id' => $userId,
                    'unblocked_user_name' => $userInfo['name'],
                    'unblocked_user_unique_id' => $userInfo['unique_id'],
                    'unblocked_by' => $_SESSION['user_name']
                ]), $_SERVER['REMOTE_ADDR']]);
                break;
                
            case 'delete':
                // Delete user and related data
                $stmt = $db->prepare("DELETE FROM users WHERE id = ? AND is_admin = 0");
                $stmt->execute([$userId]);
                $message = 'User deleted successfully';
                break;
                
            case 'force_logout':
                $stmt = $db->prepare("UPDATE sessions SET is_valid = 0 WHERE user_id = ?");
                $stmt->execute([$userId]);
                $message = 'User logged out from all devices';
                
                // Log activity
                $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, 'force_logout', 'Forced logout for user $userId', ?)");
                $stmt->execute([$_SESSION['user_id'], $_SERVER['REMOTE_ADDR']]);
                break;
        }
    }
}

// Redirect back to users page
header('Location: users.php' . ($error ? '?error=' . urlencode($error) : ($message ? '?message=' . urlencode($message) : '')));
exit;
?>
