<?php
/**
 * ============================================================================
 * friends/ajax/send-request.php - Send Friend Request Handler
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../../config/config.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Please login first']);
    exit;
}

$userId = getUserId();
$friendId = filter_input(INPUT_POST, 'friend_id', FILTER_VALIDATE_INT);

if (!$friendId) {
    echo json_encode(['success' => false, 'message' => 'Invalid friend ID']);
    exit;
}

// Cannot friend yourself
if ($userId === $friendId) {
    echo json_encode(['success' => false, 'message' => 'You cannot send a friend request to yourself']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    $friendshipClass = new \App\Friendship($db);
    
    $result = $friendshipClass->sendRequest($userId, $friendId);
    echo json_encode($result);
    
} catch (Exception $e) {
    error_log("Send friend request error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'An error occurred']);
}
?>
