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

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

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

// Vérifier si un user a un email + retourner infos contact
if (isset($_GET['check_email']) && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $stmt = $pdo->prepare("SELECT email, phone, email_private, phone_private FROM users WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch();

    $hasEmail  = $row && !empty($row['email']) && filter_var($row['email'], FILTER_VALIDATE_EMAIL);
    $showEmail = $hasEmail && !($row['email_private'] ?? 1);
    $showPhone = !empty($row['phone']) && !($row['phone_private'] ?? 1);

    $result = ['has_email' => $hasEmail];
    if (isset($_GET['get_contact'])) {
        $result['email'] = $showEmail ? $row['email'] : '';
        $result['phone'] = $showPhone ? $row['phone'] : '';
    }
    echo json_encode($result);
    exit;
}

$q        = trim($_GET['q'] ?? '');
$circleId = (int)($_SESSION['circle_id'] ?? 1);
$userId   = (int)$_SESSION['user_id'];

if (strlen($q) < 2) { echo '[]'; exit; }

try {
    // Chercher dans le cercle et les amis en priorité
    $stmt = $pdo->prepare("
        SELECT DISTINCT u.id, u.username, u.nickname,
               CASE WHEN cm.user_id IS NOT NULL THEN 1 ELSE 0 END as in_circle,
               CASE WHEN fa.id IS NOT NULL AND fa.status='active'  THEN 1 ELSE 0 END as is_friend,
               CASE WHEN fa.id IS NOT NULL AND fa.status='pending' THEN 1 ELSE 0 END as req_sent,
               CASE WHEN fb.id IS NOT NULL AND fb.status='pending' THEN 1 ELSE 0 END as req_received
        FROM users u
        LEFT JOIN circle_members cm ON cm.user_id = u.id AND cm.circle_id = ?
        LEFT JOIN friends fa ON fa.user_id = ? AND fa.friend_id = u.id
        LEFT JOIN friends fb ON fb.user_id = u.id AND fb.friend_id = ?
        WHERE u.id != ?
          AND (u.username LIKE ? OR u.nickname LIKE ?)
        ORDER BY in_circle DESC, is_friend DESC, u.username ASC
        LIMIT 10
    ");
    $stmt->execute([$circleId, $userId, $userId, $userId, "%$q%", "%$q%"]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $out = [];
    foreach ($results as $r) {
        $label = $r['username'];
        if (!empty($r['nickname'])) $label .= ' (' . $r['nickname'] . ')';
        // Statut relation
        if     ((int)$r['is_friend']    === 1) $relation = 'ami';
        elseif ((int)$r['req_sent']     === 1) $relation = 'envoyee';
        elseif ((int)$r['req_received'] === 1) $relation = 'recue';
        else                                   $relation = 'aucun';

        $out[] = [
            'id'       => $r['id'],
            'label'    => $label,
            'username' => $r['username'],
            'relation' => $relation,
            'in_circle'=> (bool)$r['in_circle'],
        ];
    }
    echo json_encode($out);
} catch (Exception $e) { echo '[]'; }
?>