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

requireLogin();
$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];

// Créer la table si absente
try {
    $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)
    )");
} catch (Exception $e) {}

$msg = '';

// Modifier une note donnée
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_rating'])) {
    $ratedId = (int)$_POST['rated_id'];
    $stars   = max(1, min(5, (int)$_POST['stars']));
    $comment = trim(htmlspecialchars($_POST['comment'] ?? ''));
    try {
        $pdo->prepare("INSERT INTO user_ratings (rater_id, rated_id, stars, comment)
                       VALUES (?, ?, ?, ?)
                       ON DUPLICATE KEY UPDATE stars=?, comment=?, updated_at=NOW()")
            ->execute([$userId, $ratedId, $stars, $comment, $stars, $comment]);
        $msg = "Note mise a jour !";
    } catch (Exception $e) { $msg = "Erreur: " . $e->getMessage(); }
}

// Notes reçues
try {
    $received = $pdo->prepare("
        SELECT ur.*, u.username as rater_name
        FROM user_ratings ur
        JOIN users u ON u.id = ur.rater_id
        WHERE ur.rated_id = ?
        ORDER BY ur.updated_at DESC
    ");
    $received->execute([$userId]);
    $receivedRatings = $received->fetchAll();
    $avgReceived = count($receivedRatings) > 0
        ? round(array_sum(array_column($receivedRatings, 'stars')) / count($receivedRatings), 1)
        : 0;
} catch (Exception $e) { $receivedRatings = []; $avgReceived = 0; }

// Notes données
try {
    $given = $pdo->prepare("
        SELECT ur.*, u.username as rated_name
        FROM user_ratings ur
        JOIN users u ON u.id = ur.rated_id
        WHERE ur.rater_id = ?
        ORDER BY ur.updated_at DESC
    ");
    $given->execute([$userId]);
    $givenRatings = $given->fetchAll();
} catch (Exception $e) { $givenRatings = []; }

include 'header.php';

function stars($n, $max=5) {
    $html = '';
    for ($i = 1; $i <= $max; $i++) {
        $html .= $i <= $n ? '★' : '☆';
    }
    return $html;
}
?>

<div class="container mt-4 px-4">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Retour</a>
        <h5 class="text-warning fw-bold mb-0">Mon Score de Réputation</h5>
    </div>

    <?php if ($msg): ?><div class="alert alert-success small py-2"><?= $msg ?></div><?php endif; ?>

    <!-- RÉSUMÉ -->
    <div class="row g-3 mb-4">
        <div class="col-md-4">
            <div class="card bg-dark border-warning shadow text-center p-3">
                <div style="font-size:2.5rem;color:#ffc107;letter-spacing:2px;"><?= str_repeat('★', round($avgReceived)) . str_repeat('☆', 5-round($avgReceived)) ?></div>
                <div class="text-warning fw-bold" style="font-size:1.4rem;"><?= $avgReceived ?>/5</div>
                <div class="text-muted small"><?= count($receivedRatings) ?> évaluation<?= count($receivedRatings) > 1 ? 's' : '' ?> reçue<?= count($receivedRatings) > 1 ? 's' : '' ?></div>
            </div>
        </div>
        <div class="col-md-8">
            <?php
            // Répartition des étoiles
            for ($s = 5; $s >= 1; $s--) {
                $cnt = count(array_filter($receivedRatings, fn($r) => $r['stars'] == $s));
                $pct = count($receivedRatings) > 0 ? round($cnt / count($receivedRatings) * 100) : 0;
            ?>
            <div class="d-flex align-items-center gap-2 mb-1">
                <span style="color:#ffc107;font-size:0.75rem;min-width:30px;"><?= $s ?>★</span>
                <div class="progress flex-grow-1" style="height:10px;background:#1a1a1a;">
                    <div class="progress-bar bg-warning" style="width:<?= $pct ?>%;"></div>
                </div>
                <span class="text-muted small" style="min-width:30px;"><?= $cnt ?></span>
            </div>
            <?php } ?>
        </div>
    </div>

    <div class="row g-3">
        <!-- NOTES REÇUES -->
        <div class="col-md-6">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header text-info fw-bold small py-2">Évaluations reçues</div>
                <div class="card-body p-0">
                    <?php if (empty($receivedRatings)): ?>
                    <div class="text-muted text-center py-3 small">Aucune évaluation reçue.</div>
                    <?php else: ?>
                    <?php foreach ($receivedRatings as $r): ?>
                    <div class="p-2 border-bottom border-secondary">
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="text-info" style="font-size:0.75rem;"><?= htmlspecialchars($r['rater_name']) ?></span>
                            <span style="color:#ffc107;font-size:0.8rem;"><?= stars($r['stars']) ?></span>
                        </div>
                        <?php if (!empty($r['comment'])): ?>
                        <div class="text-muted" style="font-size:0.68rem;margin-top:2px;font-style:italic;">"<?= htmlspecialchars($r['comment']) ?>"</div>
                        <?php endif; ?>
                        <div class="text-muted" style="font-size:0.58rem;"><?= date('d M Y', strtotime($r['updated_at'])) ?></div>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- NOTES DONNÉES -->
        <div class="col-md-6">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header text-success fw-bold small py-2">Évaluations données</div>
                <div class="card-body p-0">
                    <?php if (empty($givenRatings)): ?>
                    <div class="text-muted text-center py-3 small">Aucune évaluation donnée.</div>
                    <?php else: ?>
                    <?php foreach ($givenRatings as $r): ?>
                    <div class="p-2 border-bottom border-secondary">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <span class="text-white" style="font-size:0.75rem;"><?= htmlspecialchars($r['rated_name']) ?></span>
                            <span style="color:#ffc107;font-size:0.8rem;"><?= stars($r['stars']) ?></span>
                        </div>
                        <!-- Formulaire de modification -->
                        <form method="POST" class="d-flex gap-1 align-items-center flex-wrap mt-1">
                            <input type="hidden" name="rated_id" value="<?= $r['rated_id'] ?>">
                            <select name="stars" class="form-select form-select-sm bg-dark text-white border-secondary" style="width:auto;">
                                <?php for ($s = 1; $s <= 5; $s++): ?>
                                <option value="<?= $s ?>" <?= $s == $r['stars'] ? 'selected' : '' ?>><?= $s ?> ★</option>
                                <?php endfor; ?>
                            </select>
                            <input type="text" name="comment" class="form-control form-control-sm bg-dark text-white border-secondary flex-grow-1"
                                   value="<?= htmlspecialchars($r['comment'] ?? '') ?>" placeholder="Commentaire..." style="min-width:0;">
                            <button type="submit" name="update_rating" class="btn btn-xs btn-outline-success py-0">Modifier</button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
