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

requireLogin();
$user   = getConnectedUser($pdo);
$userId = (int)$user['id'];
$circleId = (int)($_SESSION['circle_id'] ?? 1);

$isAdminUser  = isAdmin($user);
$isOracleUser = isOracle($user, $circleId, $pdo);
if (!$isAdminUser && !$isOracleUser) { header("Location: index.php"); exit; }

$msg = ''; $error = '';

// Créer tables si absentes
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS mailing_lists (
        id          INT(11)     NOT NULL AUTO_INCREMENT PRIMARY KEY,
        circle_id   INT(11)     NOT NULL,
        name        VARCHAR(100) NOT NULL,
        description VARCHAR(255) DEFAULT NULL,
        created_by  INT(11)     NOT NULL,
        created_at  TIMESTAMP   DEFAULT CURRENT_TIMESTAMP
    )");
    $pdo->exec("CREATE TABLE IF NOT EXISTS mailing_list_members (
        id       INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        list_id  INT(11) NOT NULL,
        user_id  INT(11) NOT NULL,
        UNIQUE KEY unique_member (list_id, user_id)
    )");
    $pdo->exec("CREATE TABLE IF NOT EXISTS mailing_config (
        id           INT(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
        circle_id    INT(11)      NOT NULL UNIQUE,
        from_name    VARCHAR(100) DEFAULT 'JeTeGageQue',
        from_email   VARCHAR(150) DEFAULT 'noreply@jetegageque.com',
        smtp_host    VARCHAR(150) DEFAULT NULL,
        smtp_port    INT(5)       DEFAULT 587,
        smtp_user    VARCHAR(150) DEFAULT NULL,
        smtp_pass    VARCHAR(255) DEFAULT NULL,
        smtp_enabled TINYINT(1)   DEFAULT 0
    )");
} catch (Exception $e) {}

// Changer de cercle
if (isset($_GET['circle_id'])) {
    $circleId = (int)$_GET['circle_id'];
    $_SESSION['circle_id'] = $circleId;
}

// Créer une liste
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_list'])) {
    $name = trim(htmlspecialchars($_POST['list_name'] ?? ''));
    $desc = trim(htmlspecialchars($_POST['list_desc'] ?? ''));
    if (!empty($name)) {
        try {
            $pdo->prepare("INSERT INTO mailing_lists (circle_id,name,description,created_by) VALUES (?,?,?,?)")
                ->execute([$circleId, $name, $desc, $userId]);
            $msg = "Liste \"$name\" creee !";
        } catch (Exception $e) { $error = $e->getMessage(); }
    }
}

// Supprimer une liste
if (isset($_GET['del_list'])) {
    $lid = (int)$_GET['del_list'];
    $pdo->prepare("DELETE FROM mailing_list_members WHERE list_id=?")->execute([$lid]);
    $pdo->prepare("DELETE FROM mailing_lists WHERE id=? AND circle_id=?")->execute([$lid, $circleId]);
    header("Location: oracle_mailing.php"); exit;
}

// Ajouter membre à une liste
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_member'])) {
    $lid      = (int)$_POST['list_id'];
    $memberId = (int)$_POST['member_id'];
    if ($lid && $memberId) {
        try {
            $pdo->prepare("INSERT IGNORE INTO mailing_list_members (list_id,user_id) VALUES (?,?)")->execute([$lid, $memberId]);
            $msg = "Membre ajoute !";
        } catch (Exception $e) { $error = $e->getMessage(); }
    }
}

// Retirer membre
if (isset($_GET['rm_member'])) {
    $lid = (int)$_GET['list_id'];
    $uid = (int)$_GET['rm_member'];
    $pdo->prepare("DELETE FROM mailing_list_members WHERE list_id=? AND user_id=?")->execute([$lid, $uid]);
    header("Location: oracle_mailing.php?list_id={$lid}"); exit;
}

// Envoyer un courriel à une liste
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_email'])) {
    $lid     = (int)$_POST['list_id'];
    $subject = trim(htmlspecialchars($_POST['email_subject'] ?? ''));
    $body    = trim($_POST['email_body'] ?? '');

    if ($lid && $subject && $body) {
        // Récupérer config SMTP du cercle
        $smtpStmt = $pdo->prepare("SELECT * FROM mailing_config WHERE circle_id=?");
        $smtpStmt->execute([$circleId]);
        $smtpCfg = $smtpStmt->fetch();

        $fromName  = $smtpCfg['from_name']  ?? 'JeTeGageQue';
        $fromEmail = $smtpCfg['from_email'] ?? 'noreply@jetegageque.com';

        // Récupérer les membres avec email
        $membersStmt = $pdo->prepare("
            SELECT u.email, u.username FROM users u
            JOIN mailing_list_members mlm ON mlm.user_id = u.id
            WHERE mlm.list_id = ? AND u.email != '' AND u.email IS NOT NULL
        ");
        $membersStmt->execute([$lid]);
        $recipients = $membersStmt->fetchAll();

        $sent = 0; $failed = 0;
        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        $headers .= "From: {$fromName} <{$fromEmail}>\r\n";

        // Commanditaire actif
        $sponsorHtml = '';
        try {
            $sp = $pdo->query("SELECT nom,logo_url,site_url,slogan FROM commandites WHERE is_active=1 ORDER BY FIELD(niveau,'platine','or','argent','bronze') LIMIT 1")->fetch();
            if ($sp && $sp['logo_url']) {
                $spLink = $sp['site_url'] ? '<a href="'.htmlspecialchars($sp['site_url']).'" target="_blank">' : '';
                $spLinkEnd = $sp['site_url'] ? '</a>' : '';
                $spSlogan = $sp['slogan'] ? '<div style="font-size:10px;color:#888;font-style:italic;margin-top:3px;">'.htmlspecialchars($sp['slogan']).'</div>' : '';
                $sponsorHtml = '<div style="text-align:center;padding:10px 0;border-top:1px solid #222;margin-top:16px;">'
                    . '<div style="font-size:9px;color:#888;letter-spacing:1px;margin-bottom:5px;">COMMANDITAIRE</div>'
                    . $spLink . '<img src="'.htmlspecialchars($sp['logo_url']).'" style="max-height:36px;max-width:130px;object-fit:contain;" alt="'.htmlspecialchars($sp['nom']).'">' . $spLinkEnd
                    . $spSlogan . '</div>';
            }
        } catch (Exception $e) {}

        $oracleName = htmlspecialchars(strtoupper($user['username'] ?? ''));
        $htmlBody = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'
            . '<body style="margin:0;padding:0;background:#050510;font-family:Arial,sans-serif;">'
            . '<div style="max-width:560px;margin:0 auto;background:#0d0d1a;border:1px solid #1a1a3a;border-radius:10px;overflow:hidden;">'
            . '<div style="background:#050520;padding:18px 24px;border-bottom:2px solid #0dcaf0;text-align:center;">'
            . '<div style="font-size:22px;font-weight:900;color:#0dcaf0;letter-spacing:4px;">JETEGAGEQUE</div>'
            . '<div style="font-size:10px;color:#999;letter-spacing:2px;margin-top:2px;">PLATEFORME DE GAGES</div>'
            . '</div>'
            . '<div style="background:#080816;padding:10px 24px;border-bottom:1px solid #111;">'
            . '<div style="font-size:11px;font-weight:700;color:#fd7e14;letter-spacing:1px;">&#9878; ORACLE &mdash; ' . $oracleName . '</div>'
            . '</div>'
            . '<div style="padding:20px 24px;">'
            . '<h2 style="margin:0 0 14px;font-size:17px;font-weight:700;color:#0dcaf0;">' . htmlspecialchars($subject) . '</h2>'
            . '<div style="color:#ddd;line-height:1.7;font-size:14px;background:#080810;border-left:3px solid #0dcaf0;padding:12px 16px;border-radius:0 6px 6px 0;margin-bottom:16px;">'
            . nl2br(htmlspecialchars($body))
            . '</div>'
            . '</div>'
            . '<div style="padding:14px 24px;border-top:1px solid #1a1a2a;background:#060610;">'
            . '<div style="font-size:10px;color:#888;">Envoye par <strong style="color:#999;">JeTeGageQue</strong> &mdash; Oracle : <strong style="color:#999;">' . htmlspecialchars($user['username']) . '</strong></div>'
            . $sponsorHtml
            . '</div>'
            . '</div>'
            . '</body></html>';

        foreach ($recipients as $r) {
            if (mail($r['email'], $subject, $htmlBody, $headers)) {
                $sent++;
            } else { $failed++; }
        }

        $msg = "Courriel envoye a {$sent} membre(s)" . ($failed > 0 ? " ({$failed} echec(s))" : "") . ".";
    }
}

// Sauvegarder config SMTP
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_smtp'])) {
    try {
        $fromName  = trim(htmlspecialchars($_POST['from_name']  ?? 'JeTeGageQue'));
        $fromEmail = trim(htmlspecialchars($_POST['from_email'] ?? 'noreply@jetegageque.com'));
        $pdo->prepare("INSERT INTO mailing_config (circle_id,from_name,from_email) VALUES (?,?,?)
                       ON DUPLICATE KEY UPDATE from_name=?, from_email=?")
            ->execute([$circleId, $fromName, $fromEmail, $fromName, $fromEmail]);
        $msg = "Configuration courriel sauvegardee !";
    } catch (Exception $e) { $error = $e->getMessage(); }
}

// Charger les listes du cercle
$lists = $pdo->prepare("SELECT ml.*, COUNT(mlm.user_id) as member_count
    FROM mailing_lists ml
    LEFT JOIN mailing_list_members mlm ON mlm.list_id = ml.id
    WHERE ml.circle_id = ?
    GROUP BY ml.id ORDER BY ml.name ASC");
$lists->execute([$circleId]);
$mailingLists = $lists->fetchAll();

// Liste sélectionnée
$selectedListId = (int)($_GET['list_id'] ?? ($mailingLists[0]['id'] ?? 0));
$selectedList   = null;
$listMembers    = [];

if ($selectedListId) {
    foreach ($mailingLists as $l) {
        if ($l['id'] == $selectedListId) { $selectedList = $l; break; }
    }
    $lmStmt = $pdo->prepare("SELECT u.id, u.username, u.email FROM users u
        JOIN mailing_list_members mlm ON mlm.user_id = u.id
        WHERE mlm.list_id = ?");
    $lmStmt->execute([$selectedListId]);
    $listMembers = $lmStmt->fetchAll();
}

// Membres du cercle pour ajout
$circleMembers = $pdo->prepare("SELECT u.id, u.username, u.email FROM users u
    JOIN circle_members cm ON cm.user_id = u.id
    WHERE cm.circle_id = ? ORDER BY u.username ASC");
$circleMembers->execute([$circleId]);
$circleUserList = $circleMembers->fetchAll();

// Config SMTP actuelle
$smtpStmt = $pdo->prepare("SELECT * FROM mailing_config WHERE circle_id=?");
$smtpStmt->execute([$circleId]);
$smtpCfg = $smtpStmt->fetch() ?: ['from_name'=>'JeTeGageQue','from_email'=>'noreply@jetegageque.com'];

// Mes cercles pour sélecteur
if ($isAdminUser) {
    $myCircles = $pdo->query("SELECT id, name FROM circles WHERE status='active' ORDER BY name")->fetchAll();
} else {
    $myCirclesStmt = $pdo->prepare("SELECT c.id, c.name FROM circles c
        JOIN circle_members cm ON cm.circle_id=c.id WHERE cm.user_id=? AND c.oracle_id=? ORDER BY c.name");
    $myCirclesStmt->execute([$userId, $userId]);
    $myCircles = $myCirclesStmt->fetchAll();
}

include 'header.php';
?>

<div class="container mt-4 px-4">
    <div class="d-flex align-items-center gap-3 mb-3 flex-wrap">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Retour</a>
        <h5 class="text-info fw-bold mb-0">Listes de distribution</h5>
        <?php if (count($myCircles) > 1): ?>
        <form method="GET" class="d-flex align-items-center gap-2">
            <select name="circle_id" class="form-select form-select-sm bg-dark text-white border-info" style="max-width:180px;" onchange="this.form.submit()">
                <?php foreach ($myCircles as $mc): ?>
                <option value="<?= $mc['id'] ?>" <?= $mc['id']==$circleId?'selected':'' ?>><?= htmlspecialchars($mc['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </form>
        <?php endif; ?>
    </div>

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

    <div class="row g-3">
        <!-- LISTES -->
        <div class="col-md-3">
            <div class="card bg-dark border-info shadow mb-2">
                <div class="card-header text-info fw-bold small py-2">Mes listes</div>
                <div class="list-group list-group-flush bg-dark">
                    <?php foreach ($mailingLists as $l): ?>
                    <a href="?list_id=<?= $l['id'] ?>"
                       class="list-group-item list-group-item-action bg-dark border-secondary <?= $l['id']==$selectedListId?'active':'' ?>"
                       style="font-size:0.75rem;">
                        <?= htmlspecialchars($l['name']) ?>
                        <span class="badge bg-secondary float-end"><?= $l['member_count'] ?></span>
                    </a>
                    <?php endforeach; ?>
                    <?php if (empty($mailingLists)): ?>
                    <div class="p-3 text-muted small">Aucune liste.</div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Créer liste -->
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header text-white fw-bold small py-2">Creer une liste</div>
                <div class="card-body py-2">
                    <form method="POST">
                        <input type="text" name="list_name" class="form-control form-control-sm bg-dark text-white border-secondary mb-2"
                               placeholder="Nom de la liste" required>
                        <input type="text" name="list_desc" class="form-control form-control-sm bg-dark text-white border-secondary mb-2"
                               placeholder="Description (opt.)">
                        <button type="submit" name="create_list" class="btn btn-info btn-sm fw-bold w-100">Creer</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- MEMBRES + ENVOI -->
        <div class="col-md-5">
            <?php if ($selectedList): ?>
            <div class="card bg-dark border-secondary shadow mb-3">
                <div class="card-header d-flex justify-content-between align-items-center py-2">
                    <span class="text-white fw-bold small"><?= htmlspecialchars($selectedList['name']) ?></span>
                    <a href="?del_list=<?= $selectedList['id'] ?>" class="btn btn-xs btn-outline-danger py-0"
                       onclick="return confirm('Supprimer cette liste ?')">Supprimer</a>
                </div>
                <div class="card-body py-2">
                    <!-- Membres actuels -->
                    <?php foreach ($listMembers as $lm): ?>
                    <div class="d-flex align-items-center justify-content-between py-1 border-bottom border-secondary">
                        <span class="text-info small"><?= htmlspecialchars($lm['username']) ?></span>
                        <span class="text-muted" style="font-size:0.65rem;"><?= htmlspecialchars($lm['email'] ?: 'Pas de courriel') ?></span>
                        <a href="?rm_member=<?= $lm['id'] ?>&list_id=<?= $selectedListId ?>" class="btn btn-xs btn-outline-danger py-0">-</a>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($listMembers)): ?>
                    <div class="text-muted small py-2">Aucun membre.</div>
                    <?php endif; ?>

                    <!-- Ajouter membre -->
                    <form method="POST" class="d-flex gap-2 mt-2">
                        <input type="hidden" name="list_id" value="<?= $selectedListId ?>">
                        <select name="member_id" class="form-select form-select-sm bg-dark text-white border-secondary">
                            <option value="">Ajouter un membre...</option>
                            <?php foreach ($circleUserList as $cu):
                                $alreadyIn = !empty(array_filter($listMembers, fn($m) => $m['id']==$cu['id']));
                                if (!$alreadyIn): ?>
                            <option value="<?= $cu['id'] ?>"><?= htmlspecialchars($cu['username']) ?></option>
                            <?php endif; endforeach; ?>
                        </select>
                        <button type="submit" name="add_member" class="btn btn-success btn-sm fw-bold">+</button>
                    </form>
                </div>
            </div>

            <!-- Envoyer courriel -->
            <div class="card bg-dark border-warning shadow">
                <div class="card-header text-warning fw-bold small py-2">Envoyer un courriel</div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="list_id" value="<?= $selectedListId ?>">
                        <input type="text" name="email_subject" class="form-control form-control-sm bg-dark text-white border-secondary mb-2"
                               placeholder="Sujet..." required>
                        <textarea name="email_body" class="form-control bg-dark text-white border-secondary mb-2" rows="4"
                                  placeholder="Message..." required></textarea>
                        <div class="d-flex align-items-center justify-content-between">
                            <small class="text-muted" style="font-size:0.65rem;"><?= count($listMembers) ?> destinataire(s)</small>
                            <button type="submit" name="send_email" class="btn btn-warning fw-bold btn-sm"
                                    onclick="return confirm('Envoyer a <?= count($listMembers) ?> membre(s) ?')">ENVOYER</button>
                        </div>
                    </form>
                </div>
            </div>
            <?php else: ?>
            <div class="alert alert-info small">Selectionne ou cree une liste.</div>
            <?php endif; ?>
        </div>

        <!-- CONFIG COURRIEL -->
        <div class="col-md-4">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header text-white fw-bold small py-2">Configuration courriel</div>
                <div class="card-body">
                    <form method="POST">
                        <div class="mb-2">
                            <label class="text-white small">Nom expediteur</label>
                            <input type="text" name="from_name" class="form-control form-control-sm bg-dark text-white border-secondary"
                                   value="<?= htmlspecialchars($smtpCfg['from_name']??'JeTeGageQue') ?>">
                        </div>
                        <div class="mb-3">
                            <label class="text-white small">Courriel expediteur</label>
                            <input type="email" name="from_email" class="form-control form-control-sm bg-dark text-white border-secondary"
                                   value="<?= htmlspecialchars($smtpCfg['from_email']??'noreply@jetegageque.com') ?>">
                        </div>
                        <button type="submit" name="save_smtp" class="btn btn-secondary btn-sm fw-bold w-100">Sauvegarder</button>
                    </form>
                    <hr class="border-secondary my-2">
                    <small class="text-muted" style="font-size:0.62rem;">
                        Les courriels sont envoyes via la fonction mail() du serveur.
                        Assure-toi que ton domaine est configure pour envoyer des courriels.
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

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