<?php
/**
 * Suspend User API
 * Allows admins to suspend/unsuspend users
 */

// Disable error display to prevent HTML in JSON response
ini_set('display_errors', 0);
error_reporting(E_ALL);

session_start();

// Debug session info
error_log("Suspend API - Session admin_logged_in: " . (isset($_SESSION['admin_logged_in']) ? 'true' : 'false'));
error_log("Suspend API - Session admin_user_id: " . (isset($_SESSION['admin_user_id']) ? $_SESSION['admin_user_id'] : 'not set'));

// Check if user is logged in as admin
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    error_log("Suspend API - Unauthorized access attempt");
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized - Please log in as admin']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['user_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

try {
    require_once '../config/database.php';
    $db = new Database();
    $conn = $db->getConnection();
    
    $userId = $input['user_id'];
    $action = $input['action'] ?? 'suspend'; // suspend or unsuspend
    $reason = $input['reason'] ?? '';
    
    error_log("Suspend API - Processing user_id: $userId, action: $action");
    
    // Get current user status
    $checkSql = "SELECT status FROM users WHERE id = :user_id";
    $checkStmt = $conn->prepare($checkSql);
    $checkStmt->execute([':user_id' => $userId]);
    $user = $checkStmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        error_log("Suspend API - User not found: $userId");
        echo json_encode(['success' => false, 'message' => 'User not found']);
        exit;
    }
    
    $newStatus = ($action === 'suspend') ? 'suspended' : 'pending';
    
    // Update user status
    $updateSql = "UPDATE users SET status = :status WHERE id = :user_id";
    $updateStmt = $conn->prepare($updateSql);
    $result = $updateStmt->execute([
        ':status' => $newStatus,
        ':user_id' => $userId
    ]);
    
    if ($result) {
        // Log the action (only if admin_user_id is available)
        if (isset($_SESSION['admin_user_id'])) {
            try {
                $logSql = "INSERT INTO admin_actions (admin_id, user_id, action, reason, created_at) VALUES (:admin_id, :user_id, :action, :reason, NOW())";
                $logStmt = $conn->prepare($logSql);
                $logStmt->execute([
                    ':admin_id' => $_SESSION['admin_user_id'],
                    ':user_id' => $userId,
                    ':action' => $action,
                    ':reason' => $reason
                ]);
                error_log("Suspend API - Admin action logged successfully");
            } catch (Exception $logError) {
                error_log("Suspend API - Failed to log admin action: " . $logError->getMessage());
                // Continue execution even if logging fails
            }
        } else {
            error_log("Suspend API - No admin_user_id in session, skipping admin action log");
        }
        
        // Create notification for user
        try {
            $notificationSql = "INSERT INTO user_notifications (user_id, title, message, type, created_at) VALUES (:user_id, :title, :message, :type, NOW())";
            $notificationStmt = $conn->prepare($notificationSql);
            
            if ($action === 'suspend') {
                $title = 'Account gesperrt';
                $message = 'Ihr Account wurde von einem Administrator gesperrt.' . ($reason ? ' Grund: ' . $reason : '');
                $type = 'warning';
            } else {
                $title = 'Account entsperrt';
                $message = 'Ihr Account wurde von einem Administrator entsperrt.' . ($reason ? ' Grund: ' . $reason : '');
                $type = 'success';
            }
            
            $notificationStmt->execute([
                ':user_id' => $userId,
                ':title' => $title,
                ':message' => $message,
                ':type' => $type
            ]);
            error_log("Suspend API - User notification created successfully");
        } catch (Exception $notificationError) {
            error_log("Suspend API - Failed to create user notification: " . $notificationError->getMessage());
            // Continue execution even if notification fails
        }
        
        echo json_encode([
            'success' => true, 
            'message' => 'User ' . $action . 'ed successfully',
            'new_status' => $newStatus
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to ' . $action . ' user']);
    }
    
} catch (Exception $e) {
    error_log("Suspend API - Error " . ($action ?? 'processing') . " user: " . $e->getMessage());
    error_log("Suspend API - Stack trace: " . $e->getTraceAsString());
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'message' => 'Internal server error: ' . $e->getMessage(),
        'debug' => [
            'action' => $action ?? 'unknown',
            'user_id' => $userId ?? 'unknown',
            'error' => $e->getMessage()
        ]
    ]);
}
?>
