<?php
require_once __DIR__ . '/header.php';

if (!$isLoggedIn) {
    header('Location: ../login.php');
    exit;
}

$theme = isset($_GET['theme']) ? trim((string)$_GET['theme']) : '';

// 🎀 Traitement ajout ami 🎀
$msgSuccess = '';
$msgError   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    try {
        $pdo = getPdo();

        // 🎀 Création table amis si elle n'existe pas 🎀
        $pdo->exec("CREATE TABLE IF NOT EXISTS amis (
            id         INT AUTO_INCREMENT PRIMARY KEY,
            user_id    INT NOT NULL,
            ami_id     INT NOT NULL,
            statut     ENUM('en_attente','accepte','refuse') DEFAULT 'en_attente',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            UNIQUE KEY unique_amis (user_id, ami_id),
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (ami_id)  REFERENCES users(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

        if ($_POST['action'] === 'ajouter') {
            $emailAmi = trim((string)($_POST['email'] ?? ''));
            if ($emailAmi === '') {
                $msgError = 'Entre un email.';
            } else {
                $stmtAmi = $pdo->prepare('SELECT id, name FROM users WHERE email = :email LIMIT 1');
                $stmtAmi->execute(['email' => $emailAmi]);
                $amiUser = $stmtAmi->fetch(PDO::FETCH_ASSOC);

                if (!$amiUser) {
                    $msgError = 'Aucun utilisateur trouvé avec cet email.';
                } elseif ((int)$amiUser['id'] === (int)$_SESSION['user_id']) {
                    $msgError = 'Tu ne peux pas t\'ajouter toi-même.';
                } else {
                    $stmtInsert = $pdo->prepare(
                        'INSERT IGNORE INTO amis (user_id, ami_id, statut) VALUES (:uid, :aid, "accepte")'
                    );
                    $stmtInsert->execute(['uid' => (int)$_SESSION['user_id'], 'aid' => (int)$amiUser['id']]);
                    $msgSuccess = htmlspecialchars($amiUser['name'], ENT_QUOTES, 'UTF-8') . ' ajouté comme ami !';
                }
            }
        }

        if ($_POST['action'] === 'supprimer' && isset($_POST['ami_id'])) {
            $stmtDel = $pdo->prepare('DELETE FROM amis WHERE (user_id = :uid AND ami_id = :aid) OR (ami_id = :uid2 AND user_id = :aid2)');
            $stmtDel->execute([
                'uid'  => (int)$_SESSION['user_id'],
                'aid'  => (int)$_POST['ami_id'],
                'uid2' => (int)$_SESSION['user_id'],
                'aid2' => (int)$_POST['ami_id'],
            ]);
            $msgSuccess = 'Ami supprimé.';
        }

    } catch (Throwable $e) {
        $msgError = 'Erreur serveur.';
    }
}

// 🎀 Charge la liste des amis 🎀
try {
    $pdo = getPdo();

    // Créer table si pas encore existante
    $pdo->exec("CREATE TABLE IF NOT EXISTS amis (
        id         INT AUTO_INCREMENT PRIMARY KEY,
        user_id    INT NOT NULL,
        ami_id     INT NOT NULL,
        statut     ENUM('en_attente','accepte','refuse') DEFAULT 'en_attente',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_amis (user_id, ami_id),
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
        FOREIGN KEY (ami_id)  REFERENCES users(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $stmtAmis = $pdo->prepare(
        "SELECT u.id, u.name, u.email
           FROM amis a
           JOIN users u ON (
               CASE WHEN a.user_id = :uid THEN u.id = a.ami_id
                    ELSE u.id = a.user_id END
           )
          WHERE (a.user_id = :uid2 OR a.ami_id = :uid3)
            AND a.statut = 'accepte'"
    );
    $stmtAmis->execute([
        'uid'  => (int)$_SESSION['user_id'],
        'uid2' => (int)$_SESSION['user_id'],
        'uid3' => (int)$_SESSION['user_id'],
    ]);
    $mesAmis = $stmtAmis->fetchAll(PDO::FETCH_ASSOC);

    // 🎀 Suggestions (utilisateurs pas encore amis) 🎀
    $stmtSugg = $pdo->prepare(
        "SELECT id, name FROM users
          WHERE id != :uid
            AND id NOT IN (
                SELECT ami_id  FROM amis WHERE user_id = :uid2
                UNION
                SELECT user_id FROM amis WHERE ami_id  = :uid3
            )
          LIMIT 4"
    );
    $stmtSugg->execute([
        'uid'  => (int)$_SESSION['user_id'],
        'uid2' => (int)$_SESSION['user_id'],
        'uid3' => (int)$_SESSION['user_id'],
    ]);
    $suggestions = $stmtSugg->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    $mesAmis     = [];
    $suggestions = [];
}
?>

<main class="amis-main">

    <!-- 🎀─── HEADER PAGE ─── 🎀 -->
    <div class="amis-header">
        <a href="souvenir-detail.php?id=<?= urlencode($theme) ?>" class="theme-back">
            <svg viewBox="0 0 24 24" fill="none"><path d="M15 18l-6-6 6-6" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
            Retour
        </a>
        <h1 class="amis-title">Mes amis</h1>
        <?php if ($theme !== ''): ?>
            <p class="amis-theme-label">Thème : <strong><?= htmlspecialchars($theme, ENT_QUOTES, 'UTF-8') ?></strong></p>
        <?php endif; ?>
    </div>

    <?php if ($msgSuccess !== ''): ?>
        <p class="add-memory-message add-memory-success"><?= htmlspecialchars($msgSuccess, ENT_QUOTES, 'UTF-8') ?></p>
    <?php endif; ?>
    <?php if ($msgError !== ''): ?>
        <p class="add-memory-message add-memory-error"><?= htmlspecialchars($msgError, ENT_QUOTES, 'UTF-8') ?></p>
    <?php endif; ?>

    <div class="amis-layout">

        <!-- ─── LISTE AMIS ─── -->
        <section class="amis-section">
            <h2 class="amis-section-title">Mes amis</h2>

            <!-- Formulaire ajout ami -->
            <form method="post" class="amis-add-form">
                <input type="hidden" name="action" value="ajouter">
                <input type="text" name="email" placeholder="Email de ton ami..." class="amis-input" required>
                <button type="submit" class="amis-btn-add">Ajouter</button>
            </form>

            <?php if (empty($mesAmis)): ?>
                <p class="theme-empty">Tu n'as pas encore d'amis. Ajoute-en avec leur email !</p>
            <?php else: ?>
                <ul class="amis-list">
                    <?php foreach ($mesAmis as $ami): ?>
                        <li class="amis-item">
                            <div class="amis-avatar">
                                <?= strtoupper(mb_substr($ami['name'], 0, 1)) ?>
                            </div>
                            <div class="amis-info">
                                <span class="amis-name"><?= htmlspecialchars($ami['name'], ENT_QUOTES, 'UTF-8') ?></span>
                                <span class="amis-email"><?= htmlspecialchars($ami['email'], ENT_QUOTES, 'UTF-8') ?></span>
                            </div>
                            <form method="post" style="margin-left:auto">
                                <input type="hidden" name="action"  value="supprimer">
                                <input type="hidden" name="ami_id" value="<?= (int)$ami['id'] ?>">
                                <button type="submit" class="amis-btn-remove">Supprimer</button>
                            </form>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </section>

        <!-- ─── SUGGESTIONS ─── -->
        <?php if (!empty($suggestions)): ?>
        <section class="amis-section">
            <h2 class="amis-section-title">Mes suggestions</h2>
            <div class="amis-suggestions">
                <?php foreach ($suggestions as $s): ?>
                    <div class="amis-suggestion-card">
                        <div class="amis-avatar amis-avatar-lg">
                            <?= strtoupper(mb_substr($s['name'], 0, 1)) ?>
                        </div>
                        <span class="amis-suggestion-name"><?= htmlspecialchars($s['name'], ENT_QUOTES, 'UTF-8') ?></span>
                        <form method="post">
                            <input type="hidden" name="action"  value="ajouter">
                            <input type="hidden" name="email"   value="<?= htmlspecialchars($s['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                            <button type="submit" class="amis-btn-sugg">Ajouter</button>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>
        <?php endif; ?>

    </div>
</main>

<?php require_once __DIR__ . '/footer.php'; ?>