<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

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

// Modifier le type de la colonne si nécessaire
try { $pdo->exec("ALTER TABLE admin_config MODIFY COLUMN config_value TEXT DEFAULT NULL"); } catch(Exception $e) {}

// ── Lire toutes les valeurs admin_config au début ─────────────
$vals = [];
try {
    $rows = $pdo->query("SELECT config_key,config_value FROM admin_config")->fetchAll();
    foreach ($rows as $r) $vals[$r['config_key']] = $r['config_value'];
} catch(Exception $e) {}

// ── Templates disponibles ─────────────────────────────────────
$templates = [
    'email_bet_subject' => [
        'label'   => 'Objet — Nouveau gage',
        'default' => '{{lanceur}} vous lance un gage sur JeTeGageQue !',
        'vars'    => ['{{lanceur}}','{{destinataire}}','{{description}}','{{montant}}','{{jetons}}','{{gage_id}}'],
    ],
    'email_bet_body' => [
        'label'   => 'Corps — Nouveau gage',
        'default' => "Bonjour {{destinataire}},\n\n{{lanceur}} vous lance un gage :\n\n\"{{description}}\"\n\nMontant : {{montant}} pts d'honneur\n{{jetons}} jetons en jeu\n\nAcceptez ou refusez sur le site.",
        'vars'    => ['{{lanceur}}','{{destinataire}}','{{description}}','{{montant}}','{{jetons}}','{{gage_id}}'],
    ],
    'email_accept_subject' => [
        'label'   => 'Objet — Gage accepté',
        'default' => '{{destinataire}} a accepté votre gage #{{gage_id}} !',
        'vars'    => ['{{lanceur}}','{{destinataire}}','{{gage_id}}'],
    ],
    'email_refuse_subject' => [
        'label'   => 'Objet — Gage refusé',
        'default' => '{{destinataire}} a refusé votre gage #{{gage_id}}.',
        'vars'    => ['{{lanceur}}','{{destinataire}}','{{gage_id}}'],
    ],
];

// ── Sauvegarder templates ─────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_templates'])) {
    foreach ($templates as $key => $info) {
        $val = trim($_POST[$key] ?? $info['default']);
        $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES (?,?) ON DUPLICATE KEY UPDATE config_value=?")
            ->execute([$key, $val, $val]);
    }
    $msg = "Templates sauvegardés !";
    // Recharger
    $rows = $pdo->query("SELECT config_key,config_value FROM admin_config")->fetchAll();
    foreach ($rows as $r) $vals[$r['config_key']] = $r['config_value'];
}

// ── Test envoi ────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_email'])) {
    $dest     = trim($_POST['test_dest'] ?? '');
    $testType = $_POST['test_type'] ?? 'system';

    if (!filter_var($dest, FILTER_VALIDATE_EMAIL)) {
        $error = "Adresse courriel invalide.";
    } else {
        $fakeVars = [
            '{{lanceur}}'      => 'BrainTest',
            '{{destinataire}}' => 'TonAmi',
            '{{description}}'  => 'Je te gage que tu ne peux pas tenir 1 semaine sans cafe !',
            '{{montant}}'      => '50',
            '{{jetons}}'       => '100',
            '{{gage_id}}'      => '42',
            '{{url_site}}'     => 'https://jetegageque.com/jetegageque/',
        ];

        $borderColor = '#0dcaf0';
        $titleColor  = '#0dcaf0';
        $subj        = 'TEST SYSTEME — JeTeGageQue ' . date('H:i:s');
        $bodyContent = '';

        if ($testType === 'gage') {
            $borderColor = '#ffc107';
            $titleColor  = '#ffc107';
            $subjTpl     = $vals['email_bet_subject'] ?? $templates['email_bet_subject']['default'];
            $bodyTpl     = $vals['email_bet_body']    ?? $templates['email_bet_body']['default'];
            $subj        = str_replace(array_keys($fakeVars), array_values($fakeVars), $subjTpl);
            $bodyTxt     = str_replace(array_keys($fakeVars), array_values($fakeVars), $bodyTpl);
            $bodyContent = nl2br(htmlspecialchars($bodyTxt));
            $bodyContent .= '<div style="margin-top:16px;text-align:center;">'
                . '<a href="https://jetegageque.com/jetegageque/" style="background:#ffc107;color:#000;padding:10px 24px;border-radius:6px;text-decoration:none;font-weight:700;">Voir le gage</a>'
                . '</div>';

        } elseif ($testType === 'bienvenue') {
            $borderColor  = '#28a745';
            $titleColor   = '#28a745';
            $subj         = 'Bienvenue sur JeTeGageQue, BrainTest !';
            $bodyContent  = '<h2 style="color:#28a745;font-size:18px;margin:0 0 12px;">Bienvenue, BrainTest !</h2>';
            $bodyContent .= '<p style="color:#ddd;font-size:14px;line-height:1.7;margin:0 0 16px;">Ton compte a ete cree avec succes. Lance ton premier gage !</p>';
            $bodyContent .= '<div style="text-align:center;"><a href="https://jetegageque.com/jetegageque/" style="background:#28a745;color:#fff;padding:12px 28px;border-radius:6px;text-decoration:none;font-weight:700;">Commencer</a></div>';

        } elseif ($testType === 'reset') {
            $borderColor  = '#dc3545';
            $titleColor   = '#0dcaf0';
            $subj         = 'Reinitialisation de mot de passe — JeTeGageQue';
            $bodyContent  = '<p style="color:#ddd;font-size:14px;line-height:1.7;margin:0 0 12px;">Bonjour <strong>BrainTest</strong>,</p>';
            $bodyContent .= '<p style="color:#ddd;font-size:14px;line-height:1.7;margin:0 0 16px;">Cliquez pour choisir un nouveau mot de passe. Ce lien expire dans <strong>1 heure</strong>.</p>';
            $bodyContent .= '<div style="text-align:center;"><a href="https://jetegageque.com/jetegageque/reset_password.php?token=EXEMPLE" style="background:#0dcaf0;color:#000;padding:12px 28px;border-radius:6px;text-decoration:none;font-weight:700;">Reinitialiser</a></div>';

        } else {
            // Systeme
            $bodyContent  = '<h2 style="color:#28a745;font-size:16px;margin:0 0 12px;">Systeme de courriel fonctionnel</h2>';
            $bodyContent .= '<p style="color:#ddd;font-size:14px;margin:0 0 12px;">La fonction mail() PHP fonctionne sur ce serveur.</p>';
            $bodyContent .= '<table style="width:100%;border-collapse:collapse;font-size:12px;">';
            $bodyContent .= '<tr style="border-bottom:1px solid #1a1a2a;"><td style="color:#888;padding:5px 0;">Serveur</td><td style="color:#ddd;">' . htmlspecialchars($_SERVER['HTTP_HOST'] ?? 'inconnu') . '</td></tr>';
            $bodyContent .= '<tr style="border-bottom:1px solid #1a1a2a;"><td style="color:#888;padding:5px 0;">Date</td><td style="color:#ddd;">' . date('Y-m-d H:i:s') . '</td></tr>';
            $bodyContent .= '<tr><td style="color:#888;padding:5px 0;">Destinataire</td><td style="color:#ddd;">' . htmlspecialchars($dest) . '</td></tr>';
            $bodyContent .= '</table>';
        }

        // Assembler le HTML
        $html  = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>';
        $html .= '<body style="margin:0;background:#050510;font-family:Arial,sans-serif;">';
        $html .= '<div style="max-width:520px;margin:0 auto;background:#0d0d1a;border:1px solid #1a1a3a;border-radius:8px;overflow:hidden;">';
        $html .= '<div style="background:#050520;padding:14px 20px;border-bottom:2px solid ' . $borderColor . ';text-align:center;">';
        $html .= '<div style="font-size:20px;font-weight:900;color:#0dcaf0;letter-spacing:3px;">JETEGAGEQUE</div>';
        $html .= '<div style="font-size:9px;color:#555;letter-spacing:2px;margin-top:2px;">TEST — ' . strtoupper($testType) . '</div></div>';
        $html .= '<div style="padding:20px;">' . $bodyContent . '</div>';
        $html .= '<div style="padding:10px 20px;background:#060610;font-size:9px;color:#444;text-align:center;">JeTeGageQue — ' . date('Y-m-d H:i:s') . '</div>';
        $html .= '</div></body></html>';

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
        $headers .= "From: JeTeGageQue <noreply@jetegageque.com>\r\n";
        $ok = @mail($dest, '=?UTF-8?B?' . base64_encode($subj) . '?=', $html, $headers);
        $msg = $ok
            ? "Courriel (" . htmlspecialchars($testType) . ") envoye a " . htmlspecialchars($dest)
            : "Echec — verifiez que mail() PHP est active sur le serveur.";
    }
}

// ── Envoi à tous ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_all'])) {
    $bulkType    = $_POST['bulk_type']    ?? 'message';
    $filterTier  = $_POST['bulk_tier']    ?? 'all';
    $confirm     = trim($_POST['bulk_confirm'] ?? '');
    $bulkMessage = trim($_POST['bulk_message']  ?? '');

    if ($confirm !== 'CONFIRMER') {
        $error = "Tapez CONFIRMER pour valider l'envoi a tous.";
    } else {
        try {
            if ($filterTier !== 'all' && in_array($filterTier, ['free','premium','premium_plus'])) {
                $stmtM = $pdo->prepare("SELECT id,username,email FROM users WHERE email IS NOT NULL AND email <> '' AND tier=? ORDER BY id ASC");
                $stmtM->execute([$filterTier]);
            } else {
                $stmtM = $pdo->query("SELECT id,username,email FROM users WHERE email IS NOT NULL AND email <> '' ORDER BY id ASC");
            }
            $members = $stmtM->fetchAll();
            $sent = 0; $failed = 0;

            foreach ($members as $m) {
                if (!filter_var($m['email'], FILTER_VALIDATE_EMAIL)) { $failed++; continue; }
                if ($bulkType === 'gage') {
                    $subj    = "Un gage vous attend sur JeTeGageQue !";
                    $bodyTxt = "Bonjour " . htmlspecialchars($m['username']) . ",\n\nUn gage vous attend. Connectez-vous pour le voir !";
                } elseif ($bulkType === 'bienvenue') {
                    $subj    = "Bienvenue sur JeTeGageQue, " . htmlspecialchars($m['username']) . " !";
                    $bodyTxt = "Bonjour " . htmlspecialchars($m['username']) . ",\n\nBienvenue sur JeTeGageQue ! Lance ton premier gage maintenant.";
                } else {
                    $subj    = "Message de JeTeGageQue";
                    $bodyTxt = $bulkMessage ?: "Message de l'administration.";
                }

                $html  = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>';
                $html .= '<body style="margin:0;background:#050510;font-family:Arial,sans-serif;">';
                $html .= '<div style="max-width:520px;margin:0 auto;background:#0d0d1a;border:1px solid #1a1a3a;border-radius:8px;overflow:hidden;">';
                $html .= '<div style="background:#050520;padding:14px 20px;border-bottom:2px solid #0dcaf0;text-align:center;">';
                $html .= '<div style="font-size:20px;font-weight:900;color:#0dcaf0;letter-spacing:3px;">JETEGAGEQUE</div></div>';
                $html .= '<div style="padding:20px;color:#ddd;font-size:14px;line-height:1.7;">' . nl2br(htmlspecialchars($bodyTxt)) . '</div>';
                $html .= '<div style="padding:12px 20px;text-align:center;"><a href="https://jetegageque.com/jetegageque/" style="background:#ffc107;color:#000;padding:10px 24px;border-radius:6px;text-decoration:none;font-weight:700;">Aller sur le site</a></div>';
                $html .= '<div style="padding:8px 20px;background:#060610;font-size:9px;color:#555;text-align:center;">JeTeGageQue — Ne pas repondre.</div>';
                $html .= '</div></body></html>';

                $headers  = "MIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n";
                $headers .= "From: JeTeGageQue <noreply@jetegageque.com>\r\n";
                $ok = @mail($m['email'], '=?UTF-8?B?' . base64_encode($subj) . '?=', $html, $headers);
                $ok ? $sent++ : $failed++;
                usleep(50000);
            }
            $msg = "Envoye: {$sent}. Echec: {$failed}.";
        } catch(Exception $e) {
            $error = "Erreur: " . $e->getMessage();
        }
    }
}

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<div class="container-fluid mt-3 mb-5" style="max-width:900px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-arrow-left fa-xs me-1"></i>Admin</a>
        <h4 class="oracle-text text-info mb-0" style="letter-spacing:2px;"><i class="fa-solid fa-envelope-open-text me-2"></i>TEMPLATES COURRIELS</h4>
    </div>

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

    <form method="POST">
        <!-- Templates -->
        <div class="card bg-dark border-info shadow mb-4">
            <div class="card-header py-2 fw-bold text-info small" style="background:#050520;letter-spacing:1px;">
                <i class="fa-solid fa-file-lines me-2"></i>MODELES DE COURRIELS
            </div>
            <div class="card-body">
                <?php foreach ($templates as $key => $info):
                    $val      = $vals[$key] ?? $info['default'];
                    $isTextarea = str_ends_with($key, '_body');
                ?>
                <div class="mb-4">
                    <label class="small text-muted mb-1 d-flex justify-content-between" style="font-size:0.65rem;">
                        <span><?= htmlspecialchars($info['label']) ?></span>
                        <span class="text-info"><?php foreach($info['vars'] as $v) echo "<code style='font-size:0.58rem;background:#0a0a14;padding:1px 4px;border-radius:3px;color:#0dcaf0;margin-left:2px;'>{$v}</code>"; ?></span>
                    </label>
                    <?php if ($isTextarea): ?>
                    <textarea name="<?= $key ?>" class="form-control form-control-sm bg-dark text-white border-secondary" rows="5"><?= htmlspecialchars($val) ?></textarea>
                    <?php else: ?>
                    <input type="text" name="<?= $key ?>" value="<?= htmlspecialchars($val) ?>" class="form-control form-control-sm bg-dark text-white border-secondary">
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Test envoi -->
        <div class="card bg-dark border-warning shadow mb-4">
            <div class="card-header py-2 fw-bold small" style="background:#1a1200;color:#ffc107;letter-spacing:1px;">
                <i class="fa-solid fa-flask me-2"></i>TEST D'ENVOI
            </div>
            <div class="card-body">
                <div class="d-flex gap-2 flex-wrap align-items-end">
                    <div>
                        <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">ADRESSE COURRIEL</label>
                        <input type="email" name="test_dest" class="form-control form-control-sm bg-dark text-white border-secondary" placeholder="courriel@test.com" style="min-width:220px;">
                    </div>
                    <div>
                        <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">TYPE</label>
                        <select name="test_type" class="form-select form-select-sm bg-dark text-white border-secondary" style="min-width:200px;">
                            <option value="system">Systeme (connexion)</option>
                            <option value="gage">Nouveau gage (template)</option>
                            <option value="bienvenue">Bienvenue membre</option>
                            <option value="reset">Reinitialisation mot de passe</option>
                        </select>
                    </div>
                    <button type="submit" name="test_email" class="btn btn-warning btn-sm fw-bold">
                        <i class="fa-solid fa-paper-plane fa-xs me-1"></i>Envoyer le test
                    </button>
                </div>
                <div class="mt-2" style="font-size:0.62rem;color:#888;">
                    Si vous ne recevez pas le courriel, la fonction mail() PHP n'est pas activee sur le serveur.
                </div>
            </div>
        </div>

        <div class="text-end mb-5">
            <button type="submit" name="save_templates" class="btn btn-info fw-bold">
                <i class="fa-solid fa-floppy-disk me-1"></i>Enregistrer les templates
            </button>
        </div>
    </form>

    <!-- Envoi a tous -->
    <div class="card bg-dark border-danger shadow">
        <div class="card-header py-2 fw-bold small" style="background:#1a0505;color:#dc3545;letter-spacing:1px;">
            <i class="fa-solid fa-users me-2"></i>ENVOI A TOUS LES MEMBRES
        </div>
        <div class="card-body">
            <?php
            $memberCount = 0;
            try { $memberCount = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE email IS NOT NULL AND email <> ''")->fetchColumn(); } catch(Exception $e){}
            ?>
            <div class="alert py-2 mb-3" style="background:rgba(220,53,69,0.08);border:1px solid rgba(220,53,69,0.3);font-size:0.72rem;color:#dc3545;">
                <i class="fa-solid fa-triangle-exclamation me-1"></i>
                Enverra un courriel a <strong><?= $memberCount ?> membres</strong>. Tapez <strong>CONFIRMER</strong> pour valider.
            </div>
            <form method="POST">
                <div class="row g-3 mb-3">
                    <div class="col-md-4">
                        <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">TYPE</label>
                        <select name="bulk_type" class="form-select form-select-sm bg-dark text-white border-secondary">
                            <option value="message">Message personnalise</option>
                            <option value="gage">Invitation a gager</option>
                            <option value="bienvenue">Message de bienvenue</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">GRADE</label>
                        <select name="bulk_tier" class="form-select form-select-sm bg-dark text-white border-secondary">
                            <option value="all">Tous les membres</option>
                            <option value="free">Free seulement</option>
                            <option value="premium">Premium seulement</option>
                            <option value="premium_plus">Premium+ seulement</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">CONFIRMATION</label>
                        <input type="text" name="bulk_confirm" class="form-control form-control-sm bg-dark text-white border-secondary" placeholder="Tapez CONFIRMER">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">MESSAGE (si type = personnalise)</label>
                    <textarea name="bulk_message" class="form-control form-control-sm bg-dark text-white border-secondary" rows="3" placeholder="Votre message ici..."></textarea>
                </div>
                <button type="submit" name="send_all" class="btn btn-danger fw-bold btn-sm">
                    <i class="fa-solid fa-bullhorn me-1"></i>Envoyer a tous
                </button>
            </form>
        </div>
    </div>
</div>

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