<?php
// ─── API GROUP CHAT ───────────────────────────────────────────────────────────
// Routes :
//   POST /api/group_chat.php?action=send              → envoyer message/réaction
//   GET  /api/group_chat.php?action=poll&group_id=X&last_id=N → long polling

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

require 'db.php';
require 'jwt_helper.php';

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

// ─── POST send ────────────────────────────────────────────────────────────────
if ($action === 'send' && $method === 'POST') {
    $userId  = requireAuth();
    $groupId = (int)($body['group_id'] ?? 0);
    $type    = $body['type']    ?? 'text';    // 'text' | 'reaction'
    $content = trim($body['content'] ?? '');

    if (!$groupId || !$content) {
        http_response_code(400);
        echo json_encode(['message' => 'group_id et content requis']);
        exit;
    }

    if (!in_array($type, ['text', 'reaction'])) {
        http_response_code(400);
        echo json_encode(['message' => 'type invalide']);
        exit;
    }

    // Vérif membre
    $stmt = $pdo->prepare("SELECT 1 FROM group_members WHERE group_id = ? AND user_id = ?");
    $stmt->execute([$groupId, $userId]);
    if (!$stmt->fetch()) {
        http_response_code(403);
        echo json_encode(['message' => 'Accès refusé']);
        exit;
    }

    // Limite longueur
    if ($type === 'text' && mb_strlen($content) > 500) {
        $content = mb_substr($content, 0, 500);
    }
    if ($type === 'reaction' && mb_strlen($content) > 10) {
        http_response_code(400);
        echo json_encode(['message' => 'Réaction invalide']);
        exit;
    }

    $pdo->prepare("INSERT INTO group_messages (group_id, user_id, type, content) VALUES (?, ?, ?, ?)")
        ->execute([$groupId, $userId, $type, $content]);
    $msgId = (int)$pdo->lastInsertId();

    // Récupère le message avec le username
    $stmt = $pdo->prepare("SELECT gm.id, gm.type, gm.content, gm.created_at, u.username FROM group_messages gm JOIN users u ON u.id = gm.user_id WHERE gm.id = ?");
    $stmt->execute([$msgId]);
    $msg = $stmt->fetch();

    echo json_encode(['message' => $msg]);
    exit;
}

// ─── GET poll (long polling) ──────────────────────────────────────────────────
// `last_id` = id du dernier message connu par le client (0 = premiers messages)
// Attend jusqu'à 20s qu'un nouveau message arrive
if ($action === 'poll' && $method === 'GET') {
    $userId  = requireAuth();
    $groupId = (int)($_GET['group_id'] ?? 0);
    $lastId  = (int)($_GET['last_id']  ?? 0);

    if (!$groupId) {
        http_response_code(400);
        echo json_encode(['message' => 'group_id requis']);
        exit;
    }

    // Vérif membre
    $stmt = $pdo->prepare("SELECT 1 FROM group_members WHERE group_id = ? AND user_id = ?");
    $stmt->execute([$groupId, $userId]);
    if (!$stmt->fetch()) {
        http_response_code(403);
        echo json_encode(['message' => 'Accès refusé']);
        exit;
    }

    // Si last_id = 0 → charge les 50 derniers messages (historique initial)
    if ($lastId === 0) {
        $stmt = $pdo->prepare("SELECT gm.id, gm.type, gm.content, gm.created_at, u.username FROM group_messages gm JOIN users u ON u.id = gm.user_id WHERE gm.group_id = ? ORDER BY gm.created_at DESC LIMIT 50");
        $stmt->execute([$groupId]);
        $messages = array_reverse($stmt->fetchAll());
        echo json_encode(['messages' => $messages]);
        exit;
    }

    // Long polling : attend jusqu'à 20s qu'un nouveau message arrive
    $maxWait  = 20;
    $interval = 2;
    $waited   = 0;

    while ($waited < $maxWait) {
        $stmt = $pdo->prepare("SELECT gm.id, gm.type, gm.content, gm.created_at, u.username FROM group_messages gm JOIN users u ON u.id = gm.user_id WHERE gm.group_id = ? AND gm.id > ? ORDER BY gm.created_at ASC LIMIT 20");
        $stmt->execute([$groupId, $lastId]);
        $messages = $stmt->fetchAll();

        if (!empty($messages)) {
            echo json_encode(['messages' => $messages]);
            exit;
        }

        sleep($interval);
        $waited += $interval;
    }

    // Timeout — rien de nouveau
    echo json_encode(['messages' => []]);
    exit;
}

http_response_code(404);
echo json_encode(['message' => 'Action inconnue']);
