<?php
/**
 * ============================================================================
 * chat/ajax/block-user.php - Block User Endpoint
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

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

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

try {
    $userId = getUserId();
    $blockUserId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';
    
    if (!$blockUserId) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'User ID is required'
        ]);
        exit;
    }
    
    if ($blockUserId == $userId) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'You cannot block yourself'
        ]);
        exit;
    }
    
    $database = \App\Database::getInstance();
    $db = $database->getConnection();
    
    // Check if already blocked
    $checkQuery = "SELECT id FROM user_blocks WHERE blocker_id = ? AND blocked_id = ?";
    $stmt = $db->prepare($checkQuery);
    $stmt->execute([$userId, $blockUserId]);
    
    if ($stmt->fetch()) {
        echo json_encode([
            'success' => true,
            'message' => 'User is already blocked',
            'already_blocked' => true
        ]);
        exit;
    }
    
    // Block the user
    $insertQuery = "INSERT INTO user_blocks (blocker_id, blocked_id, reason, created_at) 
                    VALUES (?, ?, ?, NOW())";
    
    $stmt = $db->prepare($insertQuery);
    $success = $stmt->execute([$userId, $blockUserId, $reason]);
    
    if ($success) {
        // Remove from friends if they were friends
        $removeFriend = "UPDATE friendships SET status = 'blocked' 
                        WHERE (user_id = ? AND friend_id = ?) 
                        OR (user_id = ? AND friend_id = ?)";
        $stmt = $db->prepare($removeFriend);
        $stmt->execute([$userId, $blockUserId, $blockUserId, $userId]);
        
        // Log the action
        $logQuery = "INSERT INTO activity_log (user_id, action, description, created_at)
                     VALUES (?, 'block_user', ?, NOW())";
        $stmt = $db->prepare($logQuery);
        $stmt->execute([$userId, "Blocked user ID: $blockUserId"]);
        
        echo json_encode([
            'success' => true,
            'message' => 'User has been blocked successfully'
        ]);
    } else {
        throw new \Exception('Failed to block user');
    }
    
} catch (\Exception $e) {
    error_log('Block user error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to block user: ' . $e->getMessage()
    ]);
}