<?php
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/helpers.php';

session_start_safe();
if (($_SESSION['tipo'] ?? '') !== 'operador') { header('Location:/arapiraca/admin_login.php'); exit; }

$id = (int)($_GET['id'] ?? 0);
$u = [
  'id' => 0,
  'nome' => '',
  'email' => '',
  'tipo_usuario' => 'vereador',
  'partido' => '',
  'ativo' => 1,
  'foto' => null,
  'eh_presidente' => 0,
];

/* --------- Detecta coluna de biografia existente --------- */
function column_exists_local(PDO $pdo, string $table, string $col): bool {
  try{
    $st = $pdo->prepare("SELECT 1
                           FROM information_schema.columns
                          WHERE table_schema = DATABASE()
                            AND table_name = :t
                            AND column_name = :c");
    $st->execute([':t'=>$table, ':c'=>$col]);
    return (bool)$st->fetchColumn();
  }catch(Throwable $e){ return false; }
}
$bioCol = null;
foreach (['biografia','bio','descricao'] as $c) {
  if (column_exists_local($pdo,'usuarios',$c)) { $bioCol = $c; break; }
}
$bioFieldName = $bioCol ?: 'biografia'; // fallback
/* --------------------------------------------------------- */

if ($id) {
  $st = $pdo->prepare("SELECT * FROM usuarios WHERE id=:id");
  $st->execute([':id'=>$id]);
  $row = $st->fetch();
  if (!$row) { header('Location:/arapiraca/admin_usuarios.php?msg=Usuário+não+encontrado'); exit; }
  $u = array_merge($u, $row);
}

$msg = $_GET['msg'] ?? null;
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $id ? 'Editar' : 'Novo' ?> Usuário</title>
<link rel="stylesheet" href="/arapiraca/assets/style.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
  :root{
    /* Paleta unificada (um pouco mais escura) */
    --primary:#4f7be8; --primary-2:#3a6ddf;
    --ok:#22c55e; --danger:#ef4444; --amber:#f59e0b;

    --gray-50:#f3f6fb; --gray-100:#e9eef6; --gray-200:#d9dee7; --gray-300:#c9cfd9;
    --gray-400:#9aa3b2; --gray-500:#5b6472; --gray-700:#2e3643; --gray-800:#1b2230; --gray-900:#121827;

    --shadow-sm:0 2px 8px rgba(18,24,39,.08);
    --shadow-md:0 12px 22px rgba(18,24,39,.10);
    --shadow-lg:0 22px 48px rgba(18,24,39,.12);
  }

  html,body{height:100%}
  body{
    font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;
    background:
      radial-gradient(820px 420px at -10% -10%, #e2e8ff 0 60%, transparent 61%),
      radial-gradient(960px 480px at 110% 0%, #ffd6dd 0 55%, transparent 56%),
      linear-gradient(180deg,#edf2f7 0%, #e7ecf4 100%);
    min-height:100vh; color:var(--gray-900);
  }

  /* Header vítreo */
  .header{
    background:rgba(255,255,255,.92); border-bottom:1px solid var(--gray-200);
    backdrop-filter:blur(10px); position:sticky; top:0; z-index:10; box-shadow:var(--shadow-sm);
  }
  .header-inner{
    max-width:1200px; margin:0 auto; padding:12px 16px;
    display:flex; gap:12px; align-items:center; justify-content:space-between; flex-wrap:wrap;
  }
  .back{
    display:inline-flex;align-items:center;gap:8px;padding:.6rem .9rem;border-radius:12px;
    background:#f1f5ff;border:1px solid #d6e0ff;color:#203a95;text-decoration:none;font-weight:800;
    box-shadow:var(--shadow-sm); transition:.18s;
  }
  .back:hover{transform:translateY(-1px); background:#e8efff}
  .cluster{display:flex;gap:8px;flex-wrap:wrap}
  .btn{
    display:inline-flex;align-items:center;gap:8px;border:1px solid var(--gray-200);
    border-radius:12px;padding:.7rem 1rem;font-weight:800;cursor:pointer;text-decoration:none;
    background:#fff;color:#223047; box-shadow:var(--shadow-sm); transition:.18s;
  }
  .btn:hover{transform:translateY(-1px); background:#f4f7fb}
  .btn-primary{background:var(--primary);color:#fff;border-color:transparent}
  .btn-primary:hover{background:var(--primary-2); box-shadow:var(--shadow-md)}
  .btn-ghost{background:#fff;border:1px solid var(--gray-200);color:#223047}

  /* Container e card */
  .main{max-width:1100px;margin:28px auto;padding:0 16px}
  .card{
    background:#fff;border:1px solid var(--gray-200);border-radius:16px;overflow:hidden;
    box-shadow:var(--shadow-lg);
  }
  .card-head{
    background:linear-gradient(135deg, var(--primary), var(--primary-2));
    color:#fff;padding:18px; text-shadow:0 1px 0 rgba(0,0,0,.05);
  }
  .card-head h2{margin:0;font-size:1.15rem;display:flex;align-items:center;gap:10px}
  .card-body{padding:18px}

  /* Alertas */
  .alert{
    padding:10px 12px;border-radius:12px;margin-bottom:14px;display:flex;align-items:center;gap:8px;
    font-weight:700; box-shadow:var(--shadow-sm);
  }
  .alert-info{background:#e8fbff;border:1px solid #b8eef7;color:#0e7490}

  /* Form */
  .grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}
  @media(max-width:720px){.grid{grid-template-columns:1fr}}
  label.form{display:block;font-weight:900;margin:6px 0 6px;color:#1f2737}
  .input{
    width:100%;background:#fff;border:2px solid var(--gray-200);border-radius:12px;padding:.8rem 1rem;
    font-size:1rem;outline:none;transition:.15s; color:#0f172a;
  }
  .input:hover{border-color:var(--gray-300)}
  .input:focus{border-color:#7aa2f7;box-shadow:0 0 0 3px rgba(122,162,247,.35)}

  .muted{color:var(--gray-500)}
  .row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
  .actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:12px}

  /* Avatar */
  .avatar-wrap{display:flex;align-items:center;gap:12px}
  .avatar{
    width:84px;height:84px;border-radius:999px;object-fit:cover;background:#e5e7eb;border:3px solid #eef2ff;
    box-shadow:var(--shadow-sm);
  }

  /* Switch */
  .switch{position:relative;display:inline-block;width:56px;height:32px}
  .switch input{opacity:0;width:0;height:0}
  .slider{
    position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background:#e5e7eb;border-radius:999px;transition:.2s;
    border:1px solid var(--gray-300);
  }
  .slider:before{
    content:""; position:absolute;height:24px;width:24px;left:3px;top:3px;background:#fff;border-radius:999px;
    box-shadow:0 2px 6px rgba(0,0,0,.18); transition:.2s;
  }
  .switch input:checked + .slider{background:#ffd58a;border-color:#f7c35f}
  .switch input:checked + .slider:before{transform:translateX(24px)}

  /* Chips / Badges */
  .chip{display:inline-flex;align-items:center;gap:.4rem;padding:.3rem .6rem;border-radius:.6rem;font-weight:900;font-size:.85rem}
  .chip-pres{background:#fff1cc;border:1px solid #ffe08a;color:#8a5a00}

  /* Textarea maior para biografia */
  textarea.input{ min-height: 140px; line-height: 1.35; }
</style>
</head>
<body>

  <div class="header">
    <div class="header-inner">
      <a class="back" href="/arapiraca/admin_usuarios.php"><i class="fa-solid fa-arrow-left"></i> Voltar</a>
      <div class="cluster">
        <a class="btn btn-ghost" href="/arapiraca/admin.php"><i class="fa-solid fa-calendar-check"></i> Sessões</a>
        <a class="btn btn-ghost" href="/arapiraca/actions.php?op=logout"><i class="fa-solid fa-right-from-bracket"></i> Sair</a>
      </div>
    </div>
  </div>

  <div class="main">
    <div class="card">
      <div class="card-head">
        <h2><i class="fa-solid fa-user-<?= $id ? 'pen' : 'plus' ?>"></i> <?= $id ? 'Editar Usuário' : 'Novo Usuário' ?></h2>
      </div>

      <div class="card-body">
        <?php if($msg): ?>
          <div class="alert alert-info"><i class="fa-solid fa-circle-info"></i> <?= h($msg) ?></div>
        <?php endif; ?>

        <form method="post" action="/arapiraca/actions.php?op=usuario_salvar" enctype="multipart/form-data" autocomplete="off">
          <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">

          <label class="form">Nome</label>
          <input class="input" name="nome" required value="<?= h($u['nome']) ?>">

          <div class="grid">
            <div>
              <label class="form">E-mail</label>
              <input class="input" name="email" type="email" required value="<?= h($u['email']) ?>">
            </div>
            <div>
              <label class="form">Tipo do usuário</label>
              <select class="input" name="tipo_usuario">
                <option value="operador" <?= $u['tipo_usuario']==='operador'?'selected':'' ?>>operador</option>
                <option value="vereador" <?= $u['tipo_usuario']==='vereador'?'selected':'' ?>>vereador</option>
              </select>
            </div>
          </div>

          <div class="grid">
            <div>
              <label class="form">Partido (opcional)</label>
              <input class="input" name="partido" value="<?= h($u['partido']) ?>">
            </div>
            <div>
              <label class="form">Status</label>
              <select class="input" name="ativo">
                <option value="1" <?= (int)$u['ativo']===1?'selected':'' ?>>Ativo</option>
                <option value="0" <?= (int)$u['ativo']===0?'selected':'' ?>>Inativo</option>
              </select>
            </div>
          </div>

          <!-- Presidente -->
          <label class="form">Função</label>
          <div class="row">
            <label class="switch" title="Marcar como Presidente (não vota)">
              <input type="checkbox" name="eh_presidente" value="1" <?= (int)($u['eh_presidente'] ?? 0)===1 ? 'checked' : '' ?>>
              <span class="slider"></span>
            </label>
            <strong>Presidente (não vota)</strong>
            <?php if ((int)($u['eh_presidente'] ?? 0)===1): ?>
              <span class="chip chip-pres"><i class="fa-solid fa-gavel"></i> Presidente</span>
            <?php endif; ?>
          </div>
          <p class="muted" style="margin:.35rem 0 1rem">Somente um usuário pode ser presidente por vez. Ao marcar aqui, os demais serão desmarcados automaticamente.</p>

          <div class="grid">
            <div>
              <label class="form">Senha <?= $id ? '(deixe em branco para manter)' : '' ?></label>
              <input class="input" name="senha" type="text" placeholder="<?= $id ? 'manter' : 'ex.: 123456' ?>">
            </div>
            <div>
              <label class="form">Foto (JPG/PNG/WebP até 2MB)</label>
              <input class="input" id="fotoInput" name="foto" type="file" accept=".jpg,.jpeg,.png,.webp">
            </div>
          </div>

          <!-- BIografia -->
          <label class="form">Biografia (opcional)</label>
          <?php
            $bioValue = (string)($u[$bioFieldName] ?? '');
            $hasBioCol = (bool)$bioCol;
          ?>
          <textarea class="input" name="<?= h($bioFieldName) ?>" placeholder="Resumo do perfil, trajetória, principais ações..."><?= h($bioValue) ?></textarea>
          <?php if (!$hasBioCol): ?>
            <p class="muted" style="margin:.35rem 0 1rem">
              Obs.: Nenhuma coluna <code>biografia</code>, <code>bio</code> ou <code>descricao</code> foi encontrada na tabela <code>usuarios</code>.
              O campo será enviado como <strong>biografia</strong>. Crie uma dessas colunas para salvar o conteúdo.
            </p>
          <?php endif; ?>

          <label class="form">Foto atual</label>
          <div class="avatar-wrap">
            <?php $src = $u['foto'] ? '/arapiraca/'.ltrim($u['foto'],'/') : '/arapiraca/assets/avatar.png'; ?>
            <img id="avatarPreview" class="avatar" src="<?= $src ?>" alt="">
            <span class="muted">A pré-visualização será atualizada ao escolher um novo arquivo.</span>
          </div>

          <div class="actions">
            <button class="btn btn-primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> Salvar</button>
            <a class="btn btn-ghost" href="/arapiraca/admin_usuarios.php"><i class="fa-solid fa-rectangle-list"></i> Voltar</a>
          </div>
        </form>

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

  <script>
    // Animação de entrada leve
    document.addEventListener('DOMContentLoaded', () => {
      const card = document.querySelector('.card');
      card.style.opacity = '0';
      card.style.transform = 'translateY(14px)';
      setTimeout(() => {
        card.style.transition = 'all .45s ease';
        card.style.opacity = '1';
        card.style.transform = 'translateY(0)';
      }, 50);
    });

    // Preview de foto
    const input = document.getElementById('fotoInput');
    const preview = document.getElementById('avatarPreview');
    if (input) {
      input.addEventListener('change', e => {
        const f = e.target.files?.[0];
        if (!f || !/^image\//.test(f.type)) return;
        const reader = new FileReader();
        reader.onload = ev => { preview.src = ev.target.result; };
        reader.readAsDataURL(f);
      });
    }
  </script>
</body>
</html>
