<?php
$title='Mi perfil';
require_once __DIR__ . '/../inc/header.php';

$pdo = db();
$me = current_user();

// estilos DiceBear (selector simple)
$styles = [
  'notionists','notionists-neutral','avataaars','avataaars-neutral',
  'personas','micah','miniavs','lorelei','lorelei-neutral',
  'pixel-art','pixel-art-neutral','fun-emoji','bottts','bottts-neutral'
];

function dicebear_url(string $style, string $seed): string {
  return 'https://api.dicebear.com/7.x/' . rawurlencode($style) . '/svg?seed=' . rawurlencode($seed);
}

$current_url = (string)($me['avatar_url'] ?? '');
$default_style = 'notionists';
$default_seed  = $me['username'] ?? 'usuario';
if ($current_url) {
  $m=[];
  if (preg_match('#/7\.x/([^/]+)/svg\?seed=([^&]+)#', $current_url, $m)) {
    $default_style = urldecode($m[1]);
    $default_seed  = urldecode($m[2]);
  }
}

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

  if ($action === 'password') {
    $old = (string)($_POST['old_password'] ?? '');
    $new = (string)($_POST['new_password'] ?? '');
    if (strlen($new) < 6) {
      flash_set('danger','La nueva contraseña debe tener al menos 6 caracteres.');
      redirect('users/profile.php');
    }
    $st = $pdo->prepare("SELECT password_hash FROM users WHERE id=?");
    $st->execute([(int)$me['id']]);
    $row = $st->fetch();
    if (!$row || !password_verify($old, $row['password_hash'])) {
      flash_set('danger','Contraseña actual incorrecta.');
      redirect('users/profile.php');
    }
    $pdo->prepare("UPDATE users SET password_hash=? WHERE id=?")
        ->execute([password_hash($new, PASSWORD_DEFAULT), (int)$me['id']]);
    flash_set('success','Contraseña actualizada.');
    redirect('users/profile.php');
  }

  if ($action === 'avatar_dicebear') {
    $style = trim($_POST['style'] ?? $default_style);
    $seed  = trim($_POST['seed'] ?? '');
    if (!in_array($style, $styles, true)) $style = $default_style;
    if ($seed === '') $seed = bin2hex(random_bytes(4));
    $avatar_url = dicebear_url($style, $seed);

    // column avatar_url existe por ensure_schema()
    $pdo->prepare("UPDATE users SET avatar_url=? WHERE id=?")
        ->execute([$avatar_url, (int)$me['id']]);

    // actualizar sesión
    $_SESSION['user']['avatar_url'] = $avatar_url;

    flash_set('success','Avatar actualizado.');
    redirect('users/profile.php');
  }

  if ($action === 'avatar_upload') {
    if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
      flash_set('danger','Error al subir la imagen.');
      redirect('users/profile.php');
    }
    $file = $_FILES['avatar'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','webp'], true)) {
      flash_set('danger','Formato no permitido. Usa JPG/PNG/WEBP.');
      redirect('users/profile.php');
    }
    if ($file['size'] > 2*1024*1024) {
      flash_set('danger','Máximo 2MB.');
      redirect('users/profile.php');
    }
    $dir = __DIR__ . '/../uploads/avatars';
    if (!is_dir($dir)) @mkdir($dir, 0775, true);

    $name = 'u'.$me['id'].'_'.time().'.'.$ext;
    $dest = $dir . '/' . $name;
    if (!move_uploaded_file($file['tmp_name'], $dest)) {
      flash_set('danger','No se pudo guardar la imagen.');
      redirect('users/profile.php');
    }
    $url = '/uploads/avatars/' . $name;
    $pdo->prepare("UPDATE users SET avatar_url=? WHERE id=?")->execute([$url, (int)$me['id']]);
    $_SESSION['user']['avatar_url'] = $url;

    flash_set('success','Avatar subido.');
    redirect('users/profile.php');
  }
}

$me = current_user();
$current_avatar = avatar_url($me);
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h4 class="mb-0">Mi perfil</h4>
    <div class="text-muted">Cuenta, contraseña y avatar.</div>
  </div>
</div>

<div class="row g-3">
  <div class="col-lg-6">
    <div class="card shadow-sm">
      <div class="card-body">
        <h6 class="mb-3">Datos</h6>
        <div class="d-flex align-items-center gap-3">
          <img class="avatar-lg" src="<?= h($current_avatar) ?>" alt="avatar">
          <div>
            <div class="fw-semibold"><?= h($me['username']) ?></div>
            <div class="text-muted small"><?= is_admin()?'Admin':'Usuario' ?></div>
          </div>
        </div>

        <hr>

        <h6 class="mb-2">Cambiar contraseña</h6>
        <form method="post" class="row g-2">
          <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
          <input type="hidden" name="action" value="password">
          <div class="col-12">
            <label class="form-label">Contraseña actual</label>
            <input class="form-control" type="password" name="old_password" required>
          </div>
          <div class="col-12">
            <label class="form-label">Nueva contraseña</label>
            <input class="form-control" type="password" name="new_password" required>
            <div class="form-text">Mínimo 6 caracteres.</div>
          </div>
          <div class="col-12">
            <button class="btn btn-primary">Guardar contraseña</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="card shadow-sm">
      <div class="card-body">
        <h6 class="mb-3">Avatar</h6>

        <div class="mb-3">
          <div class="fw-semibold mb-1">Subir imagen</div>
          <form method="post" enctype="multipart/form-data" class="d-flex gap-2 align-items-end">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="avatar_upload">
            <div class="flex-grow-1">
              <input class="form-control" type="file" name="avatar" accept=".jpg,.jpeg,.png,.webp" required>
              <div class="form-text">Cuadrada recomendado. Máx 2MB.</div>
            </div>
            <button class="btn btn-outline-primary">Subir</button>
          </form>
        </div>

        <hr>

        <div class="fw-semibold mb-2">Elegir DiceBear</div>
        <form method="post" id="frmAvatar">
          <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
          <input type="hidden" name="action" value="avatar_dicebear">

          <div class="row g-2">
            <div class="col-md-6">
              <label class="form-label">Estilo</label>
              <select class="form-select" name="style" id="style">
                <?php foreach($styles as $s): ?>
                  <option value="<?= h($s) ?>" <?= $s===$default_style?'selected':'' ?>><?= h($s) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Seed</label>
              <div class="input-group">
                <input class="form-control" name="seed" id="seed" value="<?= h($default_seed) ?>">
                <button class="btn btn-outline-secondary" type="button" id="btnRnd">Aleatorio</button>
              </div>
            </div>
          </div>

          <div class="d-flex align-items-center gap-3 mt-3">
            <img id="preview" class="avatar-lg" src="<?= h(dicebear_url($default_style,$default_seed)) ?>" alt="preview">
            <div class="flex-grow-1">
              <button class="btn btn-primary w-100">Guardar avatar DiceBear</button>
              <div class="text-muted small mt-1">Pulsa “Barajar” para ver opciones rápidas.</div>
            </div>
          </div>
        </form>

        <div class="d-flex justify-content-between align-items-center mt-3 mb-2">
          <div class="text-muted small">Pulsa un avatar para usar ese seed.</div>
          <button class="btn btn-sm btn-outline-secondary" type="button" id="btnShuffle">Barajar</button>
        </div>
        <div id="grid" class="d-grid" style="grid-template-columns: repeat(6, 1fr); gap: 10px;"></div>

      </div>
    </div>
  </div>
</div>

<script>
const styleEl=document.getElementById('style');
const seedEl=document.getElementById('seed');
const preview=document.getElementById('preview');
const grid=document.getElementById('grid');

function url(style, seed){
  return `https://api.dicebear.com/7.x/${encodeURIComponent(style)}/svg?seed=${encodeURIComponent(seed)}`;
}
function randomSeed(){
  const chars='ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789';
  let s='';
  for(let i=0;i<8;i++) s+=chars[Math.floor(Math.random()*chars.length)];
  return s;
}
function updatePreview(){
  preview.src = url(styleEl.value, seedEl.value || 'usuario');
}
function buildGrid(){
  grid.innerHTML='';
  const style=styleEl.value;
  for(let i=0;i<24;i++){
    const seed=randomSeed();
    const img=document.createElement('img');
    img.src=url(style, seed);
    img.alt=seed;
    img.title=`Usar seed: ${seed}`;
    img.style.width='100%';
    img.style.aspectRatio='1 / 1';
    img.style.objectFit='cover';
    img.style.borderRadius='12px';
    img.style.border='1px solid #e5e7eb';
    img.style.cursor='pointer';
    img.addEventListener('click', ()=>{
      seedEl.value=seed;
      updatePreview();
      window.scrollTo({top:0, behavior:'smooth'});
    });
    grid.appendChild(img);
  }
}
document.getElementById('btnRnd').addEventListener('click', ()=>{
  seedEl.value=randomSeed();
  updatePreview();
});
document.getElementById('btnShuffle').addEventListener('click', buildGrid);
styleEl.addEventListener('change', ()=>{ updatePreview(); buildGrid(); });
seedEl.addEventListener('input', updatePreview);
updatePreview(); buildGrid();
</script>

<?php require_once __DIR__ . '/../inc/footer.php'; ?>
