<?php
require_once 'db.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

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

// For simplicity, we assume user_id is passed in query or body (in production use session/token)
$userId = $_GET['user_id'] ?? $input['user_id'] ?? 0;

if (!$userId) {
    http_response_code(401);
    echo json_encode(['message' => 'User ID required']);
    exit;
}

if ($method === 'GET') {
    $type = $_GET['type'] ?? 'friends'; // 'friends' or 'requests'

    if ($type === 'requests') {
        // List pending friend requests received by user
        $stmt = $mysqli->prepare("
            SELECT u.id, u.name, u.email, u.role, f.status 
            FROM friends f 
            JOIN users u ON f.user_id = u.id
            WHERE f.friend_id = ? AND f.status = 'pending'
        ");
        $stmt->bind_param('i', $userId);
    } else {
        // List accepted friends
        $stmt = $mysqli->prepare("
            SELECT u.id, u.name, u.email, u.role, f.status 
            FROM friends f 
            JOIN users u ON (f.friend_id = u.id OR f.user_id = u.id)
            WHERE (f.user_id = ? OR f.friend_id = ?) AND u.id != ? AND f.status = 'accepted'
        ");
        $stmt->bind_param('iii', $userId, $userId, $userId);
    }

    $stmt->execute();
    $result = $stmt->get_result();
    $friends = [];
    while ($row = $result->fetch_assoc()) {
        $hash = md5($row['name']);
        $row['color'] = '#' . substr($hash, 0, 6);
        $friends[] = $row;
    }
    echo json_encode($friends);

} elseif ($method === 'POST') {
    $action = $input['action'] ?? 'add'; // 'add', 'accept', 'reject'

    if ($action === 'add') {
        // Send Friend Request
        $friendUsername = $input['username'] ?? '';
        if (!$friendUsername) {
            http_response_code(400);
            echo json_encode(['message' => 'Friend username required']);
            exit;
        }

        $find = $mysqli->prepare("SELECT id FROM users WHERE username = ?");
        $find->bind_param('s', $friendUsername);
        $find->execute();
        $res = $find->get_result();
        
        if ($row = $res->fetch_assoc()) {
            $friendId = $row['id'];
            if ($friendId == $userId) {
                http_response_code(400);
                echo json_encode(['message' => 'Cannot add yourself']);
                exit;
            }

            // Check existing relationship
            $check = $mysqli->prepare("SELECT status FROM friends WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)");
            $check->bind_param('iiii', $userId, $friendId, $friendId, $userId);
            $check->execute();
            if ($check->get_result()->num_rows > 0) {
                echo json_encode(['message' => 'Request already sent or already friends']);
                exit;
            }

            // Insert pending request
            $add = $mysqli->prepare("INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'pending')");
            $add->bind_param('ii', $userId, $friendId);
            
            if ($add->execute()) {
                echo json_encode(['message' => 'Friend request sent! Waiting for approval.']);
            } else {
                http_response_code(500);
                echo json_encode(['message' => 'Error sending request']);
            }
        } else {
            http_response_code(404);
            echo json_encode(['message' => 'User not found']);
        }

    } elseif ($action === 'accept' || $action === 'reject') {
        // Handle Request
        $requesterId = $input['requester_id'] ?? 0;
        if (!$requesterId) {
            http_response_code(400);
            echo json_encode(['message' => 'Requester ID required']);
            exit;
        }

        if ($action === 'accept') {
            $stmt = $mysqli->prepare("UPDATE friends SET status = 'accepted' WHERE user_id = ? AND friend_id = ?");
            $stmt->bind_param('ii', $requesterId, $userId);
            if ($stmt->execute()) {
                echo json_encode(['message' => 'Friend request accepted!']);
            }
        } else {
            $stmt = $mysqli->prepare("DELETE FROM friends WHERE user_id = ? AND friend_id = ?");
            $stmt->bind_param('ii', $requesterId, $userId);
            if ($stmt->execute()) {
                echo json_encode(['message' => 'Friend request rejected']);
            }
        }
    }
}
?>
