<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

if (!isset($_SESSION['user_id'])) { http_response_code(403); exit; }

$userId   = (int)$_SESSION['user_id'];
$action   = $_GET['action'] ?? $_POST['action'] ?? '';
$userTier = $user['tier'] ?? 'free';
$isAdmin  = isAdmin($user);
$targetId = (int)($_GET['id'] ?? $_POST['id'] ?? 0);

if (!$targetId || $targetId === $userId) { exit; }

// Récupérer username
$nStmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
$nStmt->execute([$userId]);
$myName = $nStmt->fetchColumn() ?: 'Quelqu\'un';

switch ($action) {

    case 'request':
        // Vérifier limite amis selon le grade
        $tierKeyF = match($userTier??'free') {'premium_plus'=>'premplus','premium'=>'premium','admin'=>'admin',default=>'free'};
        $maxFriends = (int)getWalletConfig($pdo, 'limit_friends_'.$tierKeyF, match($tierKeyF){'admin'=>999,'premplus'=>500,'premium'=>100,default=>20});
        $nbFriends = (int)$pdo->query("SELECT COUNT(*) FROM friends WHERE user_id={$userId} AND status='active'")->fetchColumn();
        if ($nbFriends >= $maxFriends && !$isAdmin) {
            echo json_encode(['error'=>"Limite de {$maxFriends} ami(s) atteinte pour votre forfait."]);
            exit;
        }
        // Envoyer une demande d'ami (status = pending)
        $chk = $pdo->prepare("SELECT id FROM friends WHERE user_id = ? AND friend_id = ?");
        $chk->execute([$userId, $targetId]);
        if (!$chk->fetch()) {
            try {
                $pdo->prepare("INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'pending')")->execute([$userId, $targetId]);
            } catch (Exception $e) {
                // Colonne status peut ne pas avoir 'pending' — ajouter directement
                $pdo->prepare("INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'active')")->execute([$userId, $targetId]);
                $pdo->prepare("INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'active')")->execute([$targetId, $userId]);
            }
            addNotification($pdo, $targetId, "{$myName} veut t'ajouter comme ami — acceptes-tu ?", "index.php?friend_request={$userId}");
        }
        echo "ok";
        break;

    case 'accept':
        // Accepter la demande
        $pdo->prepare("UPDATE friends SET status = 'active' WHERE user_id = ? AND friend_id = ?")->execute([$targetId, $userId]);
        // Ajouter l'autre sens
        $chk2 = $pdo->prepare("SELECT id FROM friends WHERE user_id = ? AND friend_id = ?");
        $chk2->execute([$userId, $targetId]);
        if (!$chk2->fetch()) {
            $pdo->prepare("INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'active')")->execute([$userId, $targetId]);
        } else {
            $pdo->prepare("UPDATE friends SET status = 'active' WHERE user_id = ? AND friend_id = ?")->execute([$userId, $targetId]);
        }
        addNotification($pdo, $targetId, "{$myName} a accepté ta demande d'ami !", "index.php");
        echo "ok";
        break;

    case 'decline':
        $pdo->prepare("DELETE FROM friends WHERE user_id = ? AND friend_id = ? AND status = 'pending'")->execute([$targetId, $userId]);
        echo "ok";
        break;

    case 'add':
        // Ajout direct (compatibilité)
        $chk = $pdo->prepare("SELECT id FROM friends WHERE user_id = ? AND friend_id = ?");
        $chk->execute([$userId, $targetId]);
        if (!$chk->fetch()) {
            $pdo->prepare("INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'active')")->execute([$userId, $targetId]);
            $pdo->prepare("INSERT INTO friends (user_id, friend_id, status) VALUES (?, ?, 'active')")->execute([$targetId, $userId]);
            addNotification($pdo, $targetId, "{$myName} t'a ajouté comme ami !", "index.php");
        }
        echo "ok";
        break;

    case 'favorite':
        $fav = (int)($_GET['fav'] ?? 1);
        $pdo->prepare("UPDATE friends SET is_favorite = ? WHERE user_id = ? AND friend_id = ?")->execute([$fav, $userId, $targetId]);
        echo "ok";
        break;

    case 'remove':
        $pdo->prepare("DELETE FROM friends WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)")
            ->execute([$userId, $targetId, $targetId, $userId]);
        echo "ok";
        break;

    default:
        http_response_code(400);
        echo "action inconnue";
}
?>
