<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }
$page_title = 'Vale Admin — Emails';
ob_start();
?>
<div class="dashboard-container">
    <?php $adminNav = 'emails'; require __DIR__ . '/sidebar.php'; ?>

    <main class="main-content">
        <header class="header-bar">
            <h2>Emails</h2>
            <span style="font-size:.8rem;color:var(--color-text-muted);">Envíos · Logs · Pruebas</span>
        </header>

        <div style="flex:1;overflow-y:auto;padding:1.5rem 2rem;">

            <?php if (!empty($emailNotice)): ?>
            <div class="alert" style="background:rgba(30,122,77,.1);color:var(--color-verde);border:1px solid rgba(30,122,77,.2);margin-bottom:1rem;"><?= htmlspecialchars($emailNotice) ?></div>
            <?php endif; ?>
            <?php if (!empty($emailError)): ?>
            <div class="alert alert-error" style="margin-bottom:1rem;"><?= htmlspecialchars($emailError) ?></div>
            <?php endif; ?>

            <!-- KPIs -->
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(155px,1fr));gap:1rem;margin-bottom:2rem;">
                <?php
                $ekpis = [
                    ['label'=>'Enviados (mes)',       'value'=>$stats['sent_mes'],                 'color'=>'#1E7A4D'],
                    ['label'=>'Fallidos (mes)',        'value'=>$stats['failed_mes'],               'color'=>'#C0392B'],
                    ['label'=>'Total histórico',       'value'=>$stats['total'],                    'color'=>'#3A332E'],
                    ['label'=>'Bienvenida dueño',      'value'=>$stats['welcome_owner'],            'color'=>'#A8331A'],
                    ['label'=>'Bienvenida vendedor',   'value'=>$stats['welcome_seller'],           'color'=>'#2C6A30'],
                    ['label'=>'Bienvenida cliente',    'value'=>$stats['client_welcome'],           'color'=>'#1E7A4D'],
                    ['label'=>'Confirmación cita',     'value'=>$stats['appointment_confirmation'], 'color'=>'#A8331A'],
                    ['label'=>'Alertas nuevos clientes','value'=>$stats['new_client_alert'],        'color'=>'#2E6BA8'],
                ];
                foreach ($ekpis as $k): ?>
                <div style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:.9rem 1.1rem;box-shadow:var(--shadow-soft);">
                    <p style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.8px;color:var(--color-text-muted);margin-bottom:.25rem;"><?= $k['label'] ?></p>
                    <p style="font-size:1.55rem;font-weight:700;color:<?= $k['color'] ?>;font-family:'Fraunces',serif;"><?= number_format($k['value']) ?></p>
                </div>
                <?php endforeach; ?>
            </div>

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;margin-bottom:2rem;">

                <!-- Test de envío -->
                <div style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.5rem;box-shadow:var(--shadow-soft);">
                    <h3 style="font-size:.95rem;margin-bottom:.35rem;">Enviar email de prueba</h3>
                    <p style="font-size:.8rem;color:var(--color-text-muted);margin-bottom:1rem;">Verifica que <code>RESEND_API_KEY</code> está funcionando sin crear un usuario real.</p>

                    <?php if (isset($testResult)): ?>
                    <div style="margin-bottom:1rem;padding:.7rem .9rem;border-radius:8px;font-size:.83rem;font-weight:600;
                         background:<?= $testResult['ok'] ? 'rgba(30,122,77,.1)' : 'rgba(192,57,43,.08)' ?>;
                         color:<?= $testResult['ok'] ? '#1E7A4D' : '#A8331A' ?>;
                         border:1px solid <?= $testResult['ok'] ? 'rgba(30,122,77,.2)' : 'rgba(192,57,43,.2)' ?>;">
                        <?php if ($testResult['ok']): ?>
                            Enviado. Resend ID: <code><?= htmlspecialchars($testResult['id'] ?? '—') ?></code>
                        <?php else: ?>
                            Falló: <?= htmlspecialchars($testResult['error'] ?? 'Error desconocido') ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <form method="POST" action="/admin/emails">
                        <input type="hidden" name="action" value="test_send">
                        <div class="form-group">
                            <label class="form-label">Destinatario</label>
                            <input type="email" name="test_to" class="form-control"
                                   value="<?= htmlspecialchars($_SESSION['admin_email'] ?? '') ?>"
                                   placeholder="tu@email.com" required>
                        </div>
                        <button type="submit" class="btn btn-primary" style="width:100%;">Enviar prueba →</button>
                    </form>

                    <div style="margin-top:1.25rem;padding:.9rem 1rem;background:#FAF6F0;border-radius:9px;border:1px solid var(--color-border);">
                        <p style="font-size:.75rem;font-weight:700;color:var(--color-text-muted);margin-bottom:.5rem;">Estado de Resend</p>
                        <div style="font-size:.82rem;line-height:1.9;">
                            <div>
                                <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:<?= getenv('RESEND_API_KEY') ? '#1E7A4D' : '#C0392B' ?>;margin-right:6px;"></span>
                                API Key: <?= getenv('RESEND_API_KEY') ? '<strong style="color:#1E7A4D;">Configurada</strong>' : '<strong style="color:#C0392B;">No configurada (RESEND_API_KEY falta en .env)</strong>' ?>
                            </div>
                            <div>
                                <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#1E7A4D;margin-right:6px;"></span>
                                From: <code><?= htmlspecialchars(getenv('RESEND_FROM_EMAIL') ?: 'Vale &lt;hola@valeai.app&gt;') ?></code>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Templates disponibles -->
                <div style="background:#fff;border:1px solid var(--color-border);border-radius:12px;padding:1.5rem;box-shadow:var(--shadow-soft);">
                    <h3 style="font-size:.95rem;margin-bottom:.35rem;">Templates activos</h3>
                    <p style="font-size:.8rem;color:var(--color-text-muted);margin-bottom:1rem;">Todos los correos usan la misma base branded de Vale.</p>

                    <?php
                    $templates = [
                        ['type'=>'welcome_owner',              'label'=>'Bienvenida dueño',          'desc'=>'Se envía al registrarse con Google OAuth. Incluye accesos, portales y próximos pasos.',               'trigger'=>'Automático en registro'],
                        ['type'=>'welcome_seller',             'label'=>'Bienvenida vendedor',       'desc'=>'Se envía al crear un vendedor desde el admin. Incluye credenciales y portales de venta.',             'trigger'=>'Automático al crear vendedor'],
                        ['type'=>'client_welcome',             'label'=>'Bienvenida cliente',        'desc'=>'Se envía al cliente final la primera vez que Vale captura su email en una conversación.',             'trigger'=>'Automático — primer email capturado'],
                        ['type'=>'appointment_confirmation',   'label'=>'Confirmación de cita',      'desc'=>'Confirma la cita al cliente con negocio, servicio, fecha y hora. Solo si tiene email registrado.',    'trigger'=>'Automático al agendar cita'],
                        ['type'=>'new_client_alert',           'label'=>'Alerta nuevo cliente',      'desc'=>'Notificación interna a Vale (VALE_ADMIN_EMAIL) cada vez que un cliente nuevo da su email.',           'trigger'=>'Automático — primer email capturado'],
                        ['type'=>'test',                       'label'=>'Email de prueba',           'desc'=>'Verifica que Resend está operativo. No se envía a usuarios reales.',                                  'trigger'=>'Manual desde este panel'],
                    ];
                    foreach ($templates as $t): ?>
                    <div style="border-bottom:1px solid #FAF6F0;padding:.75rem 0;<?= $t === end($templates) ? 'border-bottom:none' : '' ?>">
                        <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:.5rem;">
                            <div style="flex:1;">
                                <p style="font-weight:700;font-size:.85rem;color:var(--color-tierra);margin-bottom:.2rem;"><?= htmlspecialchars($t['label']) ?></p>
                                <p style="font-size:.75rem;color:var(--color-text-muted);line-height:1.4;margin-bottom:.25rem;"><?= htmlspecialchars($t['desc']) ?></p>
                                <span style="font-size:.68rem;font-weight:700;background:#F0EAE2;color:var(--color-text-muted);border-radius:99px;padding:2px 7px;"><?= htmlspecialchars($t['trigger']) ?></span>
                            </div>
                            <code style="font-size:.7rem;color:var(--color-text-muted);white-space:nowrap;padding-top:2px;"><?= $t['type'] ?></code>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

            </div>

            <!-- Log de emails -->
            <div style="background:#fff;border:1px solid var(--color-border);border-radius:12px;box-shadow:var(--shadow-soft);overflow:hidden;">
                <div style="padding:1.1rem 1.5rem;border-bottom:1px solid var(--color-border);display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.75rem;">
                    <h3 style="font-size:.95rem;">Log de envíos</h3>
                    <form method="GET" action="/admin/emails" style="display:flex;gap:.5rem;flex-wrap:wrap;align-items:center;">
                        <select name="filter_type" class="form-control" style="padding:.35rem .6rem;font-size:.82rem;">
                            <option value="">Todos los tipos</option>
                            <?php foreach (['welcome_owner','welcome_seller','client_welcome','appointment_confirmation','new_client_alert','test'] as $ft): ?>
                            <option value="<?= $ft ?>" <?= ($filterType ?? '') === $ft ? 'selected' : '' ?>><?= $ft ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name="filter_status" class="form-control" style="padding:.35rem .6rem;font-size:.82rem;">
                            <option value="">Todos</option>
                            <option value="sent"   <?= ($filterStatus ?? '') === 'sent'   ? 'selected' : '' ?>>Enviados</option>
                            <option value="failed" <?= ($filterStatus ?? '') === 'failed' ? 'selected' : '' ?>>Fallidos</option>
                        </select>
                        <button type="submit" class="btn btn-primary" style="font-size:.82rem;padding:.35rem .8rem;">Filtrar</button>
                        <a href="/admin/emails" class="btn" style="font-size:.82rem;padding:.35rem .8rem;">Limpiar</a>
                    </form>
                </div>
                <div style="overflow-x:auto;">
                <table style="width:100%;font-size:.82rem;border-collapse:collapse;">
                    <thead>
                        <tr style="background:#FAFAF8;border-bottom:1px solid var(--color-border);">
                            <th style="text-align:left;padding:.65rem 1rem;font-weight:700;color:var(--color-text-muted);">Fecha</th>
                            <th style="text-align:left;padding:.65rem .75rem;font-weight:700;color:var(--color-text-muted);">Tipo</th>
                            <th style="text-align:left;padding:.65rem .75rem;font-weight:700;color:var(--color-text-muted);">Destinatario</th>
                            <th style="text-align:left;padding:.65rem .75rem;font-weight:700;color:var(--color-text-muted);">Asunto</th>
                            <th style="text-align:center;padding:.65rem .75rem;font-weight:700;color:var(--color-text-muted);">Estado</th>
                            <th style="text-align:left;padding:.65rem .75rem;font-weight:700;color:var(--color-text-muted);">Resend ID / Error</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($emailLogs as $log): ?>
                    <tr style="border-bottom:1px solid #FAF6F1;">
                        <td style="padding:.6rem 1rem;color:var(--color-text-muted);white-space:nowrap;"><?= date('d/m/Y H:i', strtotime($log['created_at'])) ?></td>
                        <td style="padding:.6rem .75rem;">
                            <code style="font-size:.72rem;background:#F0EAE2;padding:2px 6px;border-radius:5px;"><?= htmlspecialchars($log['type']) ?></code>
                        </td>
                        <td style="padding:.6rem .75rem;"><?= htmlspecialchars($log['to_email']) ?></td>
                        <td style="padding:.6rem .75rem;color:var(--color-text-muted);max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"><?= htmlspecialchars($log['subject']) ?></td>
                        <td style="padding:.6rem .75rem;text-align:center;">
                            <?php if ($log['status'] === 'sent'): ?>
                                <span style="background:rgba(30,122,77,.12);color:#1E7A4D;border-radius:99px;padding:2px 9px;font-size:.72rem;font-weight:700;">enviado</span>
                            <?php else: ?>
                                <span style="background:rgba(192,57,43,.1);color:#C0392B;border-radius:99px;padding:2px 9px;font-size:.72rem;font-weight:700;">fallido</span>
                            <?php endif; ?>
                        </td>
                        <td style="padding:.6rem .75rem;font-size:.75rem;color:var(--color-text-muted);max-width:200px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                            <?= $log['status'] === 'sent'
                                ? htmlspecialchars($log['resend_id'] ?? '—')
                                : '<span style="color:#C0392B;">' . htmlspecialchars($log['error'] ?? '—') . '</span>'
                            ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($emailLogs)): ?>
                    <tr><td colspan="6" style="padding:2rem 1rem;text-align:center;color:var(--color-text-muted);">Sin registros con los filtros aplicados.</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
                </div>
            </div>

        </div>
    </main>
</div>
<?php
$content = ob_get_clean();
require dirname(__DIR__) . '/layout.php';
