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

$msg = ''; $msg_type = 'ok';

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

    if ($act === 'create' || $act === 'edit') {
        $id          = (int)($_POST['id'] ?? 0);
        $title       = trim($_POST['title'] ?? '');
        $message     = trim($_POST['message'] ?? '');
        $type        = in_array($_POST['type'] ?? '', ['info','success','warning','feature']) ? $_POST['type'] : 'info';
        $plan_target = trim($_POST['plan_target'] ?? '');
        $active      = isset($_POST['active']) ? 1 : 0;
        $starts_at   = ($_POST['starts_at'] ?? '') ?: null;
        $ends_at     = ($_POST['ends_at']   ?? '') ?: null;

        if (!$title || !$message) { $msg = 'Título y mensaje requeridos.'; $msg_type = 'err'; }
        elseif ($act === 'edit') {
            if (!$id) { $msg = 'ID de anuncio inválido.'; $msg_type = 'err'; }
            else {
                $pdo->prepare("UPDATE dm_announcements SET title=?,message=?,type=?,plan_target=?,active=?,starts_at=?,ends_at=? WHERE id=?")
                    ->execute([$title,$message,$type,$plan_target,$active,$starts_at,$ends_at,$id]);
                adm_audit('edit_announcement', 0, ['id'=>$id]);
                $msg = 'Anuncio actualizado.';
            }
        } else {
            $pdo->prepare("INSERT INTO dm_announcements (title,message,type,plan_target,active,starts_at,ends_at,created_at) VALUES (?,?,?,?,?,?,?,NOW())")
                ->execute([$title,$message,$type,$plan_target,$active,$starts_at,$ends_at]);
            adm_audit('create_announcement', 0, ['title'=>$title]);
            $msg = 'Anuncio creado.';
        }
    }

    if ($act === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE dm_announcements SET active = IF(active=1,0,1) WHERE id=?")->execute([$id]);
        adm_audit('toggle_announcement', 0, ['id'=>$id]);
        $msg = 'Visibilidad cambiada.';
    }

    if ($act === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM dm_announcements WHERE id=?")->execute([$id]);
        adm_audit('delete_announcement', 0, ['id'=>$id]);
        $msg = 'Anuncio eliminado.';
    }

    header("Location: announcements.php?msg=".urlencode($msg)."&mtype=$msg_type"); exit;
}

$msg      = $_GET['msg']   ?? $msg;
$msg_type = $_GET['mtype'] ?? $msg_type;

$edit_id = (int)($_GET['edit'] ?? 0);
$edit_ann = null;
if ($edit_id) {
    $s = $pdo->prepare("SELECT * FROM dm_announcements WHERE id=?");
    $s->execute([$edit_id]);
    $edit_ann = $s->fetch();
}

$all = $pdo->query("SELECT * FROM dm_announcements ORDER BY created_at DESC")->fetchAll();

adm_header('Anuncios', 'announcements');
?>
<h1 class="adm-h1">📢 Anuncios In-App</h1>

<?php if ($msg): ?>
<div class="card" style="background:<?=$msg_type==='ok'?'#052e16':'#1a0505'?>;border-color:<?=$msg_type==='ok'?'#4ade80':'#dc2626'?>;color:<?=$msg_type==='ok'?'#4ade80':'#f87171'?>;margin-bottom:16px">
  <?=htmlspecialchars($msg)?>
</div>
<?php endif; ?>

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

<!-- ── Formulario ─────────────────────────────────────────── -->
<div class="card">
  <h3 style="color:#a78bfa;margin-bottom:14px;font-size:14px"><?=$edit_ann?'✏️ Editar anuncio':'+ Nuevo anuncio'?></h3>
  <form method="POST">
    <input type="hidden" name="action" value="<?=$edit_ann?'edit':'create'?>">
    <?php if ($edit_ann): ?><input type="hidden" name="id" value="<?=$edit_ann['id']?>"><?php endif; ?>

    <div style="margin-bottom:10px">
      <label style="font-size:11px;color:#64748b;display:block;margin-bottom:4px">Título (visible en interfaz)</label>
      <input type="text" name="title" required value="<?=htmlspecialchars($edit_ann['title']??'')?>">
    </div>

    <div style="margin-bottom:10px">
      <label style="font-size:11px;color:#64748b;display:block;margin-bottom:4px">Mensaje</label>
      <textarea name="message" required style="height:80px"><?=htmlspecialchars($edit_ann['message']??'')?></textarea>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px">
      <div>
        <label style="font-size:11px;color:#64748b;display:block;margin-bottom:4px">Tipo</label>
        <select name="type">
          <?php foreach(['info','success','warning','feature'] as $t): ?>
          <option value="<?=$t?>"<?=($edit_ann['type']??'info')===$t?' selected':''?>><?=ucfirst($t)?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label style="font-size:11px;color:#64748b;display:block;margin-bottom:4px">Plan objetivo</label>
        <input type="text" name="plan_target" placeholder="all / starter / pro…" value="<?=htmlspecialchars($edit_ann['plan_target']??'')?>">
      </div>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:10px">
      <div>
        <label style="font-size:11px;color:#64748b;display:block;margin-bottom:4px">Inicio (opcional)</label>
        <input type="datetime-local" name="starts_at" value="<?=substr($edit_ann['starts_at']??'',0,16)?>">
      </div>
      <div>
        <label style="font-size:11px;color:#64748b;display:block;margin-bottom:4px">Fin (opcional)</label>
        <input type="datetime-local" name="ends_at" value="<?=substr($edit_ann['ends_at']??'',0,16)?>">
      </div>
    </div>

    <label style="display:flex;align-items:center;gap:8px;margin-bottom:14px;cursor:pointer">
      <input type="checkbox" name="active" value="1"<?=($edit_ann['active']??1)?'checked':''?>>
      <span style="font-size:13px">Visible ahora</span>
    </label>

    <div style="display:flex;gap:8px">
      <button type="submit" class="btn btn-blue" style="flex:1"><?=$edit_ann?'Guardar cambios':'Crear anuncio'?></button>
      <?php if ($edit_ann): ?><a href="announcements.php" class="btn btn-gray">Cancelar</a><?php endif; ?>
    </div>
  </form>
</div>

<!-- ── Lista ───────────────────────────────────────────────── -->
<div>
  <?php if (!$all): ?>
  <div class="card" style="color:#475569;text-align:center;padding:30px">Sin anuncios aún. Crea el primero.</div>
  <?php endif; ?>

  <?php foreach ($all as $ann):
    $now = time();
    $started  = !$ann['starts_at'] || strtotime($ann['starts_at']) <= $now;
    $not_ended = !$ann['ends_at']  || strtotime($ann['ends_at'])   > $now;
    $live = $ann['active'] && $started && $not_ended;
    $type_colors = ['info'=>'#1e3a5f','success'=>'#14532d','warning'=>'#713f12','feature'=>'#3b1d6d'];
    $border = $type_colors[$ann['type']??'info'] ?? '#1e3a5f';
  ?>
  <div class="card" style="border-color:<?=$border?>;margin-bottom:12px">
    <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:10px">
      <div style="flex:1">
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px">
          <span style="font-weight:600;color:#e2e8f0"><?=htmlspecialchars($ann['title'])?></span>
          <span style="font-size:11px;padding:2px 7px;border-radius:20px;background:<?=$border?>;color:#e2e8f0"><?=htmlspecialchars($ann['type']??'')?></span>
          <?php if ($live): ?><span style="font-size:11px;color:#4ade80;font-weight:600">● LIVE</span>
          <?php elseif ($ann['active']): ?><span style="font-size:11px;color:#fbbf24">⏰ programado</span>
          <?php else: ?><span style="font-size:11px;color:#475569">○ inactivo</span><?php endif; ?>
        </div>
        <div style="color:#94a3b8;font-size:13px;margin-bottom:6px"><?=htmlspecialchars($ann['message'])?></div>
        <div style="font-size:11px;color:#475569">
          <?php if ($ann['plan_target']): ?>Plan: <span style="color:#a78bfa"><?=htmlspecialchars($ann['plan_target'])?></span> · <?php endif; ?>
          <?php if ($ann['starts_at']): ?>Inicio: <?=substr($ann['starts_at'],0,16)?> · <?php endif; ?>
          <?php if ($ann['ends_at']): ?>Fin: <?=substr($ann['ends_at'],0,16)?> · <?php endif; ?>
          Creado: <?=substr($ann['created_at'],0,10)?>
        </div>
      </div>
      <div style="display:flex;gap:6px;flex-shrink:0">
        <a href="announcements.php?edit=<?=$ann['id']?>" class="btn btn-gray" style="padding:4px 12px;font-size:12px">✏️</a>
        <form method="POST" style="display:inline">
          <input type="hidden" name="action" value="toggle">
          <input type="hidden" name="id" value="<?=$ann['id']?>">
          <button type="submit" class="btn <?=$ann['active']?'btn-gray':'btn-green'?>" style="padding:4px 12px;font-size:12px">
            <?=$ann['active']?'Ocultar':'Activar'?>
          </button>
        </form>
        <form method="POST" style="display:inline" onsubmit="return confirm('¿Eliminar este anuncio?')">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" value="<?=$ann['id']?>">
          <button type="submit" class="btn btn-red" style="padding:4px 12px;font-size:12px">🗑</button>
        </form>
      </div>
    </div>
  </div>
  <?php endforeach; ?>
</div>
</div>

<?php adm_footer(); ?>
