<?php
session_start(); if(empty($_SESSION['admin'])){ header('Location: /admin/login.php'); exit; }
require __DIR__.'/../db.php'; $pdo=pdo();
$id=(int)($_GET['id']??0);
$nota=['id'=>0,'titulo'=>'','slug'=>'','resumen'=>'','portada'=>'','estado'=>'borrador','publicado_en'=>null];
$bloques=[];
if($id){
  $st=$pdo->prepare("SELECT * FROM notas WHERE id=?"); $st->execute([$id]); $nota=$st->fetch()?:$nota;
  $st=$pdo->prepare("SELECT * FROM nota_bloques WHERE nota_id=? ORDER BY orden ASC"); $st->execute([$id]); $bloques=$st->fetchAll();
}
$csrf=bin2hex(random_bytes(16)); $_SESSION['csrf']=$csrf;
?><!doctype html><html lang="es"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $id?'Editar':'Nueva' ?> nota — Admin</title>
<style>
body{font-family:system-ui,Segoe UI,Roboto,Arial,sans-serif;margin:0;background:#f7f9fc}
.header{display:flex;justify-content:space-between;align-items:center;padding:16px 20px;border-bottom:1px solid #e5e9f2;background:#fff}
.container{max-width:1100px;margin:16px auto;padding:0 16px}
.card{background:#fff;border:1px solid #e5e9f2;border-radius:12px;padding:16px;margin-bottom:14px}
input[type=text],textarea,select{width:100%;padding:12px;border:1px solid #dfe6ee;border-radius:10px;font:inherit}
textarea{min-height:120px}
.row{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.btn{background:#1f72b6;color:#fff;border:0;border-radius:10px;padding:10px 14px;font-weight:700;cursor:pointer}
.btn.ghost{background:#eef4fb;color:#1f72b6}
.small{font-size:12px;color:#667085}
.block{border:1px dashed #cbd5e1;border-radius:12px;padding:12px;margin:10px 0;background:#fff}
.block-head{display:flex;align-items:center;gap:8px;justify-content:space-between}
.block-actions button{margin-left:6px}
.type{background:#eff6ff;color:#1f72b6;border-radius:8px;padding:4px 8px;font-weight:700}
</style></head><body>
<div class="header"><h1 style="margin:0"><?= $id?'Editar':'Nueva' ?> nota</h1><a href="/admin/index.php">← Volver</a></div>

<form class="container" action="save_nota.php" method="post" enctype="multipart/form-data" id="formNota">
  <input type="hidden" name="csrf" value="<?=$csrf?>"><input type="hidden" name="id" value="<?=$id?>">
  <div class="card">
    <label>Título</label><input type="text" name="titulo" required value="<?=htmlspecialchars($nota['titulo'])?>">
    <div class="row">
      <div><label>Slug (URL “mi-nota”)</label><input type="text" name="slug" required value="<?=htmlspecialchars($nota['slug'])?>"></div>
      <div><label>Estado</label><select name="estado"><option value="borrador" <?=$nota['estado']==='borrador'?'selected':''?>>Borrador</option><option value="publicado" <?=$nota['estado']==='publicado'?'selected':''?>>Publicado</option></select></div>
    </div>
    <label>Resumen (tarjeta/listado)</label><textarea name="resumen"><?=htmlspecialchars($nota['resumen'])?></textarea>
    <div class="row">
      <div><label>Portada (listado)</label><input type="file" name="portada"><?php if($nota['portada']):?><div class="small">Actual: <?=htmlspecialchars($nota['portada'])?></div><?php endif;?></div>
      <div><label>Fecha publicación</label><input type="text" name="publicado_en" placeholder="YYYY-MM-DD HH:MM:SS" value="<?=htmlspecialchars($nota['publicado_en']??'')?>"></div>
    </div>
  </div>

  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center"><strong>Contenido</strong>
      <button type="button" class="btn ghost" onclick="addBlock()">+ Agregar bloque al final</button></div>
    <div id="blocks">
      <?php $i=0; foreach($bloques as $b): $i++; $data=json_decode($b['data'],true)?:[]; ?>
      <div class="block" data-i="<?=$i?>">
        <div class="block-head">
          <span class="type">Bloque <?=$i?> — <?=$b['tipo']?></span>
          <div class="block-actions">
            <button type="button" class="btn ghost" onclick="move(this,-1)">↑</button>
            <button type="button" class="btn ghost" onclick="move(this,1)">↓</button>
            <button type="button" class="btn ghost" onclick="addHere(this)">+ arriba</button>
            <button type="button" class="btn ghost" onclick="addHere(this,true)">+ abajo</button>
            <button type="button" class="btn" onclick="delBlock(this)">Eliminar</button>
          </div>
        </div>
        <div class="block-body">
          <input type="hidden" name="blocks[<?=$i?>][tipo]" value="<?=$b['tipo']?>"><input type="hidden" name="blocks[<?=$i?>][orden]" value="<?=$b['orden']?>">
          <?php if($b['tipo']==='texto'): ?>
            <label>Texto (HTML o simple)</label><textarea name="blocks[<?=$i?>][html]"><?=htmlspecialchars($data['html']??'')?></textarea>
          <?php elseif($b['tipo']==='imagen'): ?>
            <div class="row"><div><label>Imagen (subir para reemplazar)</label><input type="file" name="blocks_file_<?=$i?>"></div>
            <div><label>Alt</label><input type="text" name="blocks[<?=$i?>][alt]" value="<?=htmlspecialchars($data['alt']??'')?>"></div></div>
            <label>Caption</label><input type="text" name="blocks[<?=$i?>][caption]" value="<?=htmlspecialchars($data['caption']??'')?>">
            <label>Link</label><input type="text" name="blocks[<?=$i?>][link]" value="<?=htmlspecialchars($data['link']??'')?>"><?php if(!empty($data['src'])):?><div class="small">Actual: <?=htmlspecialchars($data['src'])?></div><?php endif;?>
          <?php elseif($b['tipo']==='video'): ?>
            <label>URL (YouTube/Vimeo o MP4)</label><input type="text" name="blocks[<?=$i?>][url]" value="<?=htmlspecialchars($data['url']??'')?>"><label>Caption</label><input type="text" name="blocks[<?=$i?>][caption]" value="<?=htmlspecialchars($data['caption']??'')?>">
          <?php elseif($b['tipo']==='audio'): ?>
            <label>Archivo de audio</label><input type="file" name="blocks_file_<?=$i?>"><label>Caption</label><input type="text" name="blocks[<?=$i?>][caption]" value="<?=htmlspecialchars($data['caption']??'')?>"><?php if(!empty($data['src'])):?><div class="small">Actual: <?=htmlspecialchars($data['src'])?></div><?php endif;?>
          <?php elseif($b['tipo']==='link'): ?>
            <label>URL destino</label><input type="text" name="blocks[<?=$i?>][href]" value="<?=htmlspecialchars($data['href']??'')?>"><label>Texto del link</label><input type="text" name="blocks[<?=$i?>][label]" value="<?=htmlspecialchars($data['label']??'')?>"><label>Imagen (opcional)</label><input type="file" name="blocks_file_<?=$i?>"><?php if(!empty($data['img'])):?><div class="small">Actual: <?=htmlspecialchars($data['img'])?></div><?php endif;?>
          <?php endif; ?>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <div style="margin-top:12px"><button class="btn">Guardar nota</button></div>
  </div>
</form>

<template id="tpl-block">
  <div class="block" data-i="__i__">
    <div class="block-head">
      <span class="type">Bloque __i__ — <span class="tipo-label">texto</span></span>
      <div class="block-actions">
        <button type="button" class="btn ghost" onclick="move(this,-1)">↑</button>
        <button type="button" class="btn ghost" onclick="move(this,1)">↓</button>
        <button type="button" class="btn ghost" onclick="addHere(this)">+ arriba</button>
        <button type="button" class="btn ghost" onclick="addHere(this,true)">+ abajo</button>
        <button type="button" class="btn" onclick="delBlock(this)">Eliminar</button>
      </div>
    </div>
    <div class="block-body">
      <label>Tipo</label>
      <select name="blocks[__i__][tipo]" class="sel-tipo" onchange="renderFields(this)">
        <option value="texto">Texto</option><option value="imagen">Imagen</option><option value="video">Video</option><option value="audio">Audio</option><option value="link">Link</option>
      </select>
      <input type="hidden" name="blocks[__i__][orden]" value="0">
      <div class="fields"></div>
    </div>
  </div>
</template>

<script>
let idx=document.querySelectorAll('#blocks .block').length;
function addBlock(){idx++;const t=document.getElementById('tpl-block').innerHTML.replaceAll('__i__',idx);document.getElementById('blocks').insertAdjacentHTML('beforeend',t);}
function addHere(btn,abajo=false){idx++;const t=document.getElementById('tpl-block').innerHTML.replaceAll('__i__',idx);const b=btn.closest('.block');b.insertAdjacentHTML(abajo?'afterend':'beforebegin',t);}
function delBlock(btn){btn.closest('.block').remove();}
function move(btn,dir){const el=btn.closest('.block');if(dir<0&&el.previousElementSibling)el.parentNode.insertBefore(el,el.previousElementSibling);if(dir>0&&el.nextElementSibling)el.parentNode.insertBefore(el.nextElementSibling,el);}
function renderFields(sel){const b=sel.closest('.block'),f=b.querySelector('.fields'),i=b.dataset.i||sel.name.match(/\[(\d+)\]/)[1];b.querySelector('.tipo-label').textContent=sel.value;
 if(sel.value==='texto'){f.innerHTML=`<label>Texto (HTML o simple)</label><textarea name="blocks[${i}][html]" rows="8"></textarea>`}
 else if(sel.value==='imagen'){f.innerHTML=`<label>Imagen</label><input type="file" name="blocks_file_${i}"><label>Alt</label><input type="text" name="blocks[${i}][alt]"><label>Caption</label><input type="text" name="blocks[${i}][caption]"><label>Link</label><input type="text" name="blocks[${i}][link]">`}
 else if(sel.value==='video'){f.innerHTML=`<label>URL (YouTube/Vimeo o MP4)</label><input type="text" name="blocks[${i}][url]"><label>Caption</label><input type="text" name="blocks[${i}][caption]">`}
 else if(sel.value==='audio'){f.innerHTML=`<label>Archivo de audio</label><input type="file" name="blocks_file_${i}"><label>Caption</label><input type="text" name="blocks[${i}][caption]">`}
 else if(sel.value==='link'){f.innerHTML=`<label>URL destino</label><input type="text" name="blocks[${i}][href]"><label>Texto del link</label><input type="text" name="blocks[${i}][label]"><label>Imagen (opcional)</label><input type="file" name="blocks_file_${i}">`}
}
document.getElementById('formNota').addEventListener('submit',()=>{document.querySelectorAll('#blocks .block').forEach((b,i)=>{const inp=b.querySelector('input[name$="[orden]"]'); if(inp) inp.value=(i+1)*10;});});
</script>
</body></html>
