<?php
require_once __DIR__ . '/_auth.php';
adm_require_login();

// Resend manual email
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    adm_csrf_verify();
    $act = $_POST['action'] ?? '';
    if ($act === 'resend' && isset($_POST['user_id'], $_POST['template_key'])) {
        require_once __DIR__ . '/../helpers/brevo.php';
        $uid  = (int)$_POST['user_id'];
        $tkey = $_POST['template_key'];
        $ok   = brevo_send($uid, $tkey, []);
        adm_audit('brevo_resend', $uid, ['template' => $tkey, 'ok' => $ok]);
    }
    header('Location: comms.php'); exit;
}

// Log emails
$logs = $pdo->query("
    SELECT be.*, u.name, u.email
    FROM dm_billing_events be
    JOIN dm_users u ON u.id = be.user_id
    WHERE be.event_type LIKE 'email_%'
    ORDER BY be.created_at DESC
    LIMIT 200
")->fetchAll();

// Sequences activas (trials con emails pendientes)
$sequences = $pdo->query("
    SELECT s.user_id, u.name, u.email, s.trial_ends_at,
           DATEDIFF(s.trial_ends_at, NOW()) AS days_left,
           s.engagement_score
    FROM dm_subscriptions s
    JOIN dm_users u ON u.id = s.user_id
    WHERE s.status IN ('trial','active') AND s.trial_ends_at IS NOT NULL
    ORDER BY s.trial_ends_at ASC
    LIMIT 100
")->fetchAll();

$templates = [
    'welcome'                  => 'Bienvenida',
    'trial_day3'               => 'Trial día 3 (sin BYOK)',
    'trial_day5'               => 'Trial día 5 (recordatorio)',
    'trial_day7'               => 'Trial día 7 (último aviso)',
    'trial_expired'            => 'Trial expirado',
    'payment_failed'           => 'Pago fallido',
    'payment_success'          => 'Pago exitoso',
    'subscription_created'     => 'Suscripción activada',
    'implementation_confirmed' => 'Implementación confirmada',
    'implementation_delivered' => 'Implementación entregada',
    'renewal_reminder'         => 'Recordatorio renovación',
];

adm_header('Comunicaciones', 'comms');
?>
<h1 class="adm-h1">📨 Comunicaciones — Brevo</h1>

<?php if (!defined('BREVO_API_KEY') || !BREVO_API_KEY): ?>
<div class="card" style="background:#1a1a2e;border:1px solid #fbbf24;margin-bottom:20px">
  <h3 style="color:#fbbf24;margin-top:0">⚠ Brevo no configurado</h3>
  <p style="color:#aaa">Los emails se envían solo cuando <code>BREVO_API_KEY</code> esté en config.php. El log muestra intentos aunque falle el envío real.</p>
</div>
<?php endif; ?>

<h2 style="color:#e2e8f0;font-size:16px;margin-bottom:10px">Sequences activas (trials)</h2>
<div class="card" style="margin-bottom:24px">
  <table>
    <tr><th>Usuario</th><th>Días restantes</th><th>Score</th><th>Reenviar email</th></tr>
    <?php foreach ($sequences as $s): ?>
    <tr>
      <td><div style="font-weight:600"><?=htmlspecialchars($s['name'])?></div><div style="color:#666;font-size:11px"><?=htmlspecialchars($s['email'])?></div></td>
      <td style="color:<?=(int)$s['days_left']<=2?'#f87171':'#4ade80'?>;font-weight:600"><?=(int)$s['days_left']?> días</td>
      <td><?=(int)$s['engagement_score']?>/100</td>
      <td>
        <form method="POST" style="display:flex;gap:6px;align-items:center">
          <input type="hidden" name="action" value="resend">
          <input type="hidden" name="user_id" value="<?=$s['user_id']?>">
          <select name="template_key" style="width:auto">
            <?php foreach ($templates as $k=>$l): ?>
            <option value="<?=$k?>"><?=$l?></option>
            <?php endforeach; ?>
          </select>
          <button type="submit" class="btn btn-blue" style="padding:4px 10px">Enviar</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
  </table>
</div>

<h2 style="color:#e2e8f0;font-size:16px;margin-bottom:10px">Log de emails enviados</h2>
<div class="card">
  <table>
    <tr><th>Fecha</th><th>Usuario</th><th>Template</th><th>Status</th></tr>
    <?php foreach ($logs as $l): $t=substr($l['event_type'],6); ?>
    <tr>
      <td style="font-size:12px;color:#888"><?=substr($l['created_at'],0,16)?></td>
      <td><?=htmlspecialchars($l['name'])?> <span style="color:#555;font-size:11px"><?=htmlspecialchars($l['email']??'')?></span></td>
      <td><?=$templates[$t]??$t?></td>
      <td><span style="color:#4ade80">✓ enviado</span></td>
    </tr>
    <?php endforeach; ?>
    <?php if (!$logs): ?><tr><td colspan="4" style="color:#555;text-align:center">Sin emails registrados aún</td></tr><?php endif; ?>
  </table>
</div>
<?php adm_footer(); ?>
