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

$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    adm_csrf_verify();
    $act = $_POST['action'] ?? '';

    if ($act === 'save_flags') {
        $flags = [
            'starter_enabled'    => isset($_POST['starter_enabled'])    ? '1' : '0',
            'pro_enabled'        => isset($_POST['pro_enabled'])         ? '1' : '0',
            'agency_enabled'     => isset($_POST['agency_enabled'])      ? '1' : '0',
            'enterprise_enabled' => isset($_POST['enterprise_enabled'])  ? '1' : '0',
            'maintenance_mode'   => isset($_POST['maintenance_mode'])    ? '1' : '0',
            'new_signups'        => isset($_POST['new_signups'])         ? '1' : '0',
        ];
        foreach ($flags as $k => $v) {
            $pdo->prepare("INSERT INTO dm_settings (`key`,`value`,updated_at) VALUES (?,?,NOW()) ON DUPLICATE KEY UPDATE `value`=?, updated_at=NOW()")
                ->execute([$k, $v, $v]);
        }
        adm_audit('save_flags', 0, $flags);
        $msg = 'Feature flags guardados.';
    }

    if ($act === 'save_maintenance') {
        $m = $_POST['maintenance_message'] ?? '';
        $pdo->prepare("INSERT INTO dm_settings (`key`,`value`,updated_at) VALUES ('maintenance_message',?,NOW()) ON DUPLICATE KEY UPDATE `value`=?, updated_at=NOW()")
            ->execute([$m, $m]);
        $msg = 'Mensaje de mantenimiento actualizado.';
    }

    if ($act === 'create_coupon') {
        $code  = strtoupper(trim($_POST['code'] ?? ''));
        $dtype = $_POST['coupon_type'] ?? 'percent';
        $val   = (float)($_POST['coupon_value'] ?? 0);
        $limit = (int)($_POST['coupon_limit'] ?? 1);
        $exp   = $_POST['coupon_expires'] ?? null;
        if ($code) {
            $pdo->prepare("INSERT IGNORE INTO dm_coupons (code, discount_type, amount, max_uses, expires_at, active, created_at) VALUES (?,?,?,?,?,1,NOW())")
                ->execute([$code, $dtype, $val, $limit, $exp ?: null]);
            adm_audit('create_coupon', 0, ['code' => $code]);
            $msg = "Cupón $code creado.";
        }
    }

    if ($act === 'delete_coupon' && isset($_POST['coupon_id'])) {
        $pdo->prepare("DELETE FROM dm_coupons WHERE id=?")->execute([(int)$_POST['coupon_id']]);
        adm_audit('delete_coupon', (int)$_POST['coupon_id'], []);
        $msg = 'Cupón eliminado.';
    }

    if ($act === 'add_blacklist') {
        $entry  = strtolower(trim($_POST['blacklist_entry'] ?? ''));
        $reason = trim($_POST['blacklist_reason'] ?? '');
        $type   = (str_contains($entry, '@') && !str_starts_with($entry, '@')) ? 'email' : 'domain';
        if ($entry) {
            $pdo->prepare("INSERT IGNORE INTO dm_blacklist (`value`, type, reason, created_at) VALUES (?,?,?,NOW())")
                ->execute([$entry, $type, $reason]);
            adm_audit('add_blacklist', 0, ['entry' => $entry]);
            $msg = "Bloqueado: $entry";
        }
    }

    if ($act === 'remove_blacklist' && isset($_POST['bl_id'])) {
        $pdo->prepare("DELETE FROM dm_blacklist WHERE id=?")->execute([(int)$_POST['bl_id']]);
        $msg = 'Entrada removida.';
    }

    if ($act === 'save_limits') {
        $limits = ['trial_days'=>7,'starter_clients'=>1,'pro_clients'=>5,'agency_clients'=>7,'enterprise_clients'=>15];
        foreach ($limits as $k => $default) {
            $v = (int)($_POST[$k] ?? $default);
            $pdo->prepare("INSERT INTO dm_settings (`key`,`value`,updated_at) VALUES (?,?,NOW()) ON DUPLICATE KEY UPDATE `value`=?, updated_at=NOW()")
                ->execute([$k, $v, $v]);
        }
        adm_audit('save_limits', 0, []);
        $msg = 'Límites globales actualizados.';
    }

    header('Location: config_admin.php?msg='.urlencode($msg)); exit;
}

// Cargar settings actuales
$raw = $pdo->query("SELECT `key`,`value` FROM dm_settings WHERE `key` IN ('starter_enabled','pro_enabled','agency_enabled','enterprise_enabled','maintenance_mode','new_signups','maintenance_message','trial_days','starter_clients','pro_clients','agency_clients','enterprise_clients')")->fetchAll(PDO::FETCH_KEY_PAIR);
$f   = fn($k, $d=1) => (int)($raw[$k] ?? $d);

$coupons  = $pdo->query("SELECT * FROM dm_coupons ORDER BY created_at DESC")->fetchAll();
$blacklist = $pdo->query("SELECT * FROM dm_blacklist ORDER BY created_at DESC LIMIT 100")->fetchAll();
$msg      = $_GET['msg'] ?? $msg;

adm_header('Config Admin', 'config_admin');
?>
<h1 class="adm-h1">⚙️ Config & Feature Flags</h1>
<?php if ($msg): ?><div class="card" style="background:#052e16;border:1px solid #4ade80;color:#4ade80;margin-bottom:16px"><?=htmlspecialchars($msg)?></div><?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">

<div class="card">
  <h3 style="margin-top:0;color:#60a5fa">🚦 Feature Flags</h3>
  <form method="POST">
    <input type="hidden" name="action" value="save_flags">
    <?php foreach ([
      'starter_enabled'    => 'Plan Starter activo',
      'pro_enabled'        => 'Plan Pro activo',
      'agency_enabled'     => 'Plan Agency activo',
      'enterprise_enabled' => 'Plan Enterprise activo',
      'new_signups'        => 'Nuevos registros permitidos',
      'maintenance_mode'   => '⚠ Modo mantenimiento',
    ] as $k => $lbl): ?>
    <label style="display:flex;align-items:center;gap:10px;margin-bottom:12px;cursor:pointer">
      <input type="checkbox" name="<?=$k?>" <?=$f($k)?'checked':''?> style="width:16px;height:16px">
      <span style="color:#e2e8f0"><?=$lbl?></span>
    </label>
    <?php endforeach; ?>
    <button type="submit" class="btn btn-blue">Guardar flags</button>
  </form>
</div>

<div class="card">
  <h3 style="margin-top:0;color:#60a5fa">📊 Límites globales</h3>
  <form method="POST">
    <input type="hidden" name="action" value="save_limits">
    <?php foreach ([
      'trial_days'         => 'Días de trial',
      'starter_clients'    => 'Starter — max clientes',
      'pro_clients'        => 'Pro — max clientes',
      'agency_clients'     => 'Agency — max clientes',
      'enterprise_clients' => 'Enterprise — max clientes',
    ] as $k => $lbl): ?>
    <div style="margin-bottom:12px">
      <label style="display:block;color:#aaa;font-size:12px;margin-bottom:4px"><?=$lbl?></label>
      <input type="number" name="<?=$k?>" value="<?=htmlspecialchars($raw[$k]??'')?>" style="width:80px">
    </div>
    <?php endforeach; ?>
    <button type="submit" class="btn btn-blue">Guardar límites</button>
  </form>
</div>

<div class="card">
  <h3 style="margin-top:0;color:#fbbf24">🔧 Mensaje mantenimiento</h3>
  <form method="POST">
    <input type="hidden" name="action" value="save_maintenance">
    <textarea name="maintenance_message" style="width:100%;height:80px"><?=htmlspecialchars($raw['maintenance_message']??'Sistema en mantenimiento. Regresa pronto.')?></textarea>
    <button type="submit" class="btn btn-gray" style="margin-top:8px">Guardar mensaje</button>
  </form>
</div>

<div class="card">
  <h3 style="margin-top:0;color:#60a5fa">🎟 Crear cupón</h3>
  <form method="POST">
    <input type="hidden" name="action" value="create_coupon">
    <div style="display:grid;gap:10px">
      <input type="text" name="code" placeholder="Código (ej. EARLY20)" required style="text-transform:uppercase">
      <div style="display:flex;gap:8px">
        <select name="coupon_type">
          <option value="percent">% descuento</option>
          <option value="fixed">$ descuento fijo</option>
        </select>
        <input type="number" name="coupon_value" placeholder="Valor" style="width:90px">
      </div>
      <div style="display:flex;gap:8px;align-items:center">
        <input type="number" name="coupon_limit" placeholder="Usos máx" value="1" style="width:90px">
        <input type="date" name="coupon_expires" style="flex:1">
      </div>
      <button type="submit" class="btn btn-blue">Crear cupón</button>
    </div>
  </form>
</div>

</div>

<div class="card" style="margin-top:20px">
  <h3 style="margin-top:0;color:#60a5fa">🎟 Cupones activos</h3>
  <table>
    <tr><th>Código</th><th>Tipo</th><th>Valor</th><th>Usos</th><th>Expira</th><th>Acción</th></tr>
    <?php foreach ($coupons as $c): ?>
    <tr>
      <td style="font-family:monospace;font-weight:600"><?=htmlspecialchars($c['code'])?></td>
      <td><?=htmlspecialchars($c['discount_type'])?></td>
      <td><?=htmlspecialchars($c['amount'])?></td>
      <td><?=(int)$c['uses']?>/<?=$c['max_uses']??'∞'?></td>
      <td style="font-size:12px;color:#888"><?=$c['expires_at']?substr($c['expires_at'],0,10):'Sin límite'?></td>
      <td>
        <form method="POST" onsubmit="return confirm('¿Eliminar?')">
          <input type="hidden" name="action" value="delete_coupon">
          <input type="hidden" name="coupon_id" value="<?=(int)$c['id']?>">
          <button type="submit" class="btn btn-red" style="padding:3px 10px">Eliminar</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (!$coupons): ?><tr><td colspan="6" style="color:#555;text-align:center">Sin cupones</td></tr><?php endif; ?>
  </table>
</div>

<div class="card" style="margin-top:20px">
  <h3 style="margin-top:0;color:#f87171">🚫 Blacklist</h3>
  <form method="POST" style="display:flex;gap:8px;margin-bottom:16px">
    <input type="hidden" name="action" value="add_blacklist">
    <input type="text" name="blacklist_entry" placeholder="email o @dominio.com" style="flex:1">
    <input type="text" name="blacklist_reason" placeholder="Razón (ej. chargeback)" style="flex:1">
    <button type="submit" class="btn btn-red">Bloquear</button>
  </form>
  <table>
    <tr><th>Entrada</th><th>Tipo</th><th>Razón</th><th>Fecha</th><th>Acción</th></tr>
    <?php foreach ($blacklist as $b): ?>
    <tr>
      <td style="font-family:monospace"><?=htmlspecialchars($b['value'])?></td>
      <td style="color:#888"><?=htmlspecialchars($b['type']??'')?></td>
      <td style="color:#888"><?=htmlspecialchars($b['reason']??'')?></td>
      <td style="font-size:11px;color:#555"><?=substr($b['created_at'],0,10)?></td>
      <td>
        <form method="POST">
          <input type="hidden" name="action" value="remove_blacklist">
          <input type="hidden" name="bl_id" value="<?=(int)$b['id']?>">
          <button type="submit" class="btn btn-gray" style="padding:3px 8px">Quitar</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    <?php if (!$blacklist): ?><tr><td colspan="5" style="color:#555;text-align:center">Sin entradas</td></tr><?php endif; ?>
  </table>
</div>
<?php adm_footer(); ?>
