<?php
require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'POST') {
    if (!isset($input['user_id']) || !isset($input['friend_id'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    
    $stmt = $pdo->prepare("SELECT * FROM friendships WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)");
    $stmt->execute([$input['user_id'], $input['friend_id'], $input['friend_id'], $input['user_id']]);
    
    if ($stmt->fetch()) {
        jsonResponse(['error' => 'Friendship already exists'], 409);
    }
    
    $stmt = $pdo->prepare("INSERT INTO friendships (user_id, friend_id, status) VALUES (?, ?, 'pending')");
    $stmt->execute([$input['user_id'], $input['friend_id']]);
    
    jsonResponse(['success' => true, 'message' => 'Friend request sent'], 201);
}

if ($method === 'PUT') {
    if (!isset($input['friendship_id']) || !isset($input['status'])) {
        jsonResponse(['error' => 'Missing required fields'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("UPDATE friendships SET status = ? WHERE id = ?");
    $stmt->execute([$input['status'], $input['friendship_id']]);
    
    jsonResponse(['success' => true, 'message' => 'Friendship updated']);
}

if ($method === 'GET') {
    if (!isset($_GET['user_id'])) {
        jsonResponse(['error' => 'User ID required'], 400);
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT u.*, f.status FROM users u INNER JOIN friendships f ON (f.friend_id = u.id AND f.user_id = ?) OR (f.user_id = u.id AND f.friend_id = ?) WHERE f.status = 'accepted'");
    $stmt->execute([$_GET['user_id'], $_GET['user_id']]);
    $friends = $stmt->fetchAll();
    
    jsonResponse(['success' => true, 'friends' => $friends]);
}
?>