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

if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0) {
    http_response_code(403); exit("Non autorisé");
}

$userId   = (int)$_SESSION['user_id'];
// Accepter l'ID depuis GET (plein écran depuis modal) ou session
if (!empty($_GET['id']) && (int)$_GET['id'] > 0) {
    $circleId = (int)$_GET['id'];
    $_SESSION['circle_id'] = $circleId; // Synchroniser la session
} else {
    $circleId = (int)($_SESSION['circle_id'] ?? 0);
}
if (!$circleId) { http_response_code(403); exit("Cercle invalide"); }

$uStmt = $pdo->prepare("SELECT username, tier, interaction_points FROM users WHERE id = ?");
$uStmt->execute([$userId]);
$user = $uStmt->fetch();
if (!$user) { http_response_code(403); exit; }

$tier          = $user['tier'] ?? 'free';
$interPts      = (int)($user['interaction_points'] ?? 0);
$isPremiumPlus = in_array($tier, ['premium_plus','admin']);

// ============================================================
// SIGNALER UN MESSAGE
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['report_msg'])) {
    header('Content-Type: application/json');
    $msgId = (int)($_POST['message_id'] ?? 0);
    if (!$msgId) { echo json_encode(['error'=>'ID invalide']); exit; }

    try {
        $pdo->prepare("INSERT INTO chat_reports (message_id, reporter_id) VALUES (?,?)")->execute([$msgId,$userId]);
    } catch (Exception $e) {
        echo json_encode(['error'=>'Déjà signalé']); exit;
    }

    $pdo->prepare("UPDATE messages SET flag_count = flag_count + 1 WHERE id = ?")->execute([$msgId]);
    $fcStmt = $pdo->prepare("SELECT flag_count FROM messages WHERE id = ?");
    $fcStmt->execute([$msgId]);
    $flagCount = (int)$fcStmt->fetchColumn();

    if ($flagCount >= 2) {
        $pdo->prepare("UPDATE messages SET is_flagged = 1 WHERE id = ?")->execute([$msgId]);
        $autoMsg = $pdo->query("SELECT message FROM chat_auto_messages WHERE is_active=1 ORDER BY RAND() LIMIT 1")->fetchColumn();
        if ($autoMsg) {
            try {
                $pdo->prepare("INSERT INTO messages (circle_id,user_id,username,content,icon_emoji,text_color) VALUES (?,0,' L\'Oracle',?,?,?)")
                    ->execute([$circleId,$autoMsg,'⚠️','#ff6600']);
            } catch (Exception $e) {
                $pdo->prepare("INSERT INTO messages (circle_id,user_id,username,content) VALUES (?,0,' L\'Oracle',?)")
                    ->execute([$circleId,$autoMsg]);
            }
        }
        echo json_encode(['flagged'=>true,'count'=>$flagCount]); exit;
    }
    echo json_encode(['flagged'=>false,'count'=>$flagCount]);
    exit;
}

// ============================================================
// ENVOYER UN MESSAGE
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content   = trim($_POST['content'] ?? '');
    $iconEmoji = !empty($_POST['icon']) ? trim($_POST['icon']) : null;
    $textColor = null;
    $photoPath = null;

    // Vérifier si les médias sont bloqués
    $blockMedia = false;
    try {
        $bm = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='block_media'");
        $bm->execute();
        $blockMedia = (int)($bm->fetchColumn() ?? 0) === 1;
    } catch (Exception $e) {}

    if (empty($content) && empty($_FILES['chat_photo']['name'])) { exit; }
    if (strlen($content) > 500) $content = substr($content, 0, 500);

    // Valider l'icône
    if ($iconEmoji) {
        try {
            $iconStmt = $pdo->prepare("SELECT required_tier, required_points FROM chat_icons WHERE emoji=? AND is_active=1");
            $iconStmt->execute([$iconEmoji]);
            $iconData = $iconStmt->fetch();
            if ($iconData) {
                $tierOrder = ['free'=>0,'premium'=>1,'premium_plus'=>2,'admin'=>3];
                if (($tierOrder[$tier]??0) < ($tierOrder[$iconData['required_tier']]??0) || $interPts < (int)$iconData['required_points']) {
                    $iconEmoji = null;
                }
            } else { $iconEmoji = null; }
        } catch (Exception $e) { $iconEmoji = null; }
    }

    // Couleur texte (premium+)
    if ($isPremiumPlus && !empty($_POST['text_color'])) {
        $col = trim($_POST['text_color']);
        if (preg_match('/^#[0-9a-fA-F]{6}$/', $col)) $textColor = $col;
    }

    // Photo chat (premium+)
    if ($isPremiumPlus && !$blockMedia && isset($_FILES['chat_photo']) && $_FILES['chat_photo']['size'] > 0) {
        $f = $_FILES['chat_photo'];
        $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
        if (in_array($ext,['jpg','jpeg','png','gif','webp']) && $f['size'] <= 3*1024*1024) {
            $dir = __DIR__.'/uploads/chat/';
            if (!is_dir($dir)) mkdir($dir,0755,true);
            $fname = 'chat_'.time().'_'.rand(100,999).'.'.$ext;
            if (move_uploaded_file($f['tmp_name'],$dir.$fname)) $photoPath = 'uploads/chat/'.$fname;
        }
    }

    try {
        $pdo->prepare("INSERT INTO messages (circle_id,user_id,username,content,icon_emoji,text_color,photo_path) VALUES (?,?,?,?,?,?,?)")
            ->execute([$circleId,$userId,$user['username'],$content,$iconEmoji,$textColor,$photoPath]);
    } catch (Exception $e) {
        $pdo->prepare("INSERT INTO messages (circle_id,user_id,username,content) VALUES (?,?,?,?)")
            ->execute([$circleId,$userId,$user['username'],$content]);
    }

    require_once 'functions.php';
    addInteractionPoints($pdo, $userId, 'chat');
    echo "ok";
}
?>
