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

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

if (!isset($_SESSION['user_id']) || (int)$_SESSION['user_id'] === 0) {
    echo json_encode(['error' => 'Non connecte']); exit;
}

$raterId = (int)$_SESSION['user_id'];
$ratedId = (int)($_POST['rated_id'] ?? 0);
$stars   = max(1, min(5, (int)($_POST['stars'] ?? 3)));
$comment = trim(htmlspecialchars($_POST['comment'] ?? ''));

if (!$ratedId || $ratedId === $raterId) {
    echo json_encode(['error' => 'Invalide']); exit;
}

try {
    // Créer la table si elle n'existe pas
    $pdo->exec("CREATE TABLE IF NOT EXISTS user_ratings (
        id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        rater_id INT(11) NOT NULL,
        rated_id INT(11) NOT NULL,
        stars TINYINT(1) NOT NULL DEFAULT 3,
        comment VARCHAR(255) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_rating (rater_id, rated_id)
    )");

    // Insérer ou mettre à jour
    $pdo->prepare("INSERT INTO user_ratings (rater_id, rated_id, stars, comment)
                   VALUES (?, ?, ?, ?)
                   ON DUPLICATE KEY UPDATE stars=?, comment=?, updated_at=NOW()")
        ->execute([$raterId, $ratedId, $stars, $comment, $stars, $comment]);

    // Calculer la nouvelle moyenne
    $avgStmt = $pdo->prepare("SELECT AVG(stars) as avg, COUNT(*) as total FROM user_ratings WHERE rated_id = ?");
    $avgStmt->execute([$ratedId]);
    $avg = $avgStmt->fetch();

    echo json_encode([
        'success' => true,
        'avg'     => round((float)$avg['avg'], 1),
        'total'   => (int)$avg['total']
    ]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>
