<?php
if (session_status() === PHP_SESSION_NONE) session_start();
$old = $_SESSION['old'] ?? [];
require_once dirname(__DIR__, 1) . '/partials/header.php';
?>

<div class="container my-5">
  <div class="card shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
      <h5 class="mb-0">Adicionar Novo Colaborador</h5>
      <a href="<?= rtrim(BASE_URL, '/') ?>/employees" class="btn btn-sm btn-outline-secondary">Voltar</a>
    </div>

    <div class="card-body">
      <?php if (!empty($_SESSION['errors'])) : ?>
        <div class="alert alert-danger">
          <ul class="mb-0">
            <?php foreach ($_SESSION['errors'] as $error) : ?>
              <li><?= htmlspecialchars($error) ?></li>
            <?php endforeach; ?>
          </ul>
        </div>
        <?php unset($_SESSION['errors']); ?>
      <?php endif; ?>

      <form method="POST" action="<?= rtrim(BASE_URL, '/') ?>/employees/store" enctype="multipart/form-data" novalidate>
        <div class="row">
          <div class="col-lg-8">
            <div class="mb-3">
              <label for="full_name" class="form-label">Nome completo *</label>
              <input type="text" id="full_name" name="full_name" required class="form-control" value="<?= htmlspecialchars($old['full_name'] ?? '') ?>">
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="cpf" class="form-label">CPF *</label>
                <input type="text" id="cpf" name="cpf" required class="form-control" placeholder="000.000.000-00" value="<?= htmlspecialchars($old['cpf'] ?? '') ?>">
              </div>
              <div class="col-md-6 mb-3">
                <label for="phone_number" class="form-label">Telefone</label>
                <input type="text" id="phone_number" name="phone_number" class="form-control" placeholder="(00) 00000-0000" value="<?= htmlspecialchars($old['phone_number'] ?? '') ?>">
              </div>
            </div>

            <div class="mb-3">
              <label for="address" class="form-label">Endereço</label>
              <input type="text" id="address" name="address" class="form-control" value="<?= htmlspecialchars($old['address'] ?? '') ?>">
            </div>

            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="job_title" class="form-label">Cargo *</label>
                <input type="text" id="job_title" name="job_title" required class="form-control" value="<?= htmlspecialchars($old['job_title'] ?? '') ?>">
              </div>
              <div class="col-md-6 mb-3">
                <label for="salary" class="form-label">Salário (R$)</label>
                <input type="text" id="salary" name="salary" class="form-control" placeholder="1.412,00" value="<?= htmlspecialchars($old['salary'] ?? '') ?>">
              </div>
            </div>

            <div class="d-flex justify-content-end gap-2 mt-4">
              <a href="<?= rtrim(BASE_URL, '/') ?>/employees" class="btn btn-light">Cancelar</a>
              <button type="submit" class="btn btn-primary">Salvar Colaborador</button>
            </div>
          </div>

          <div class="col-lg-4">
            <div class="card border-0">
              <div class="card-body text-center">
                <img id="photoPreviewV2" src="<?= rtrim(BASE_URL, '/') ?>/assets/img/placeholder-user.png" alt="Prévia da foto" class="rounded-circle mb-3" style="width:160px;height:160px;object-fit:cover;">
                <div class="mb-2">
                  <label class="btn btn-outline-secondary btn-sm">
                    Escolher foto
                    <input id="photoV2" name="photo" type="file" accept="image/*" hidden>
                  </label>
                </div>
                <small class="text-muted d-block">PNG, JPG ou WEBP (máx. 5MB)</small>
              </div>
            </div>

            <div class="mt-3">
              <div class="card p-3">
                <div class="mb-2"><strong>Observações</strong></div>
                <div class="text-muted small">Preencha os campos obrigatórios marcados com *</div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

<?php
unset($_SESSION['old']);
require_once dirname(__DIR__, 1) . '/partials/footer.php';
?>

<script>
document.addEventListener('DOMContentLoaded', function(){
  const photoInput = document.getElementById('photoV2');
  const preview = document.getElementById('photoPreviewV2');
  if (photoInput && preview) {
    photoInput.addEventListener('change', (e)=>{
      const f = e.target.files[0];
      if (!f) return;
      const reader = new FileReader();
      reader.onload = (ev)=> preview.src = ev.target.result;
      reader.readAsDataURL(f);
    });
  }

  const cpfInput = document.getElementById('cpf');
  if (cpfInput) cpfInput.addEventListener('input', e => {
    e.target.value = e.target.value.replace(/\D/g,'').replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d)/,'$1.$2').replace(/(\d{3})(\d{1,2})$/,'$1-$2').slice(0,14);
  });

  const phoneInput = document.getElementById('phone_number');
  if (phoneInput) phoneInput.addEventListener('input', e=>{
    let v = e.target.value.replace(/\D/g,'');
    if (v.length > 10) v = v.replace(/(\d{2})(\d{5})(\d{4}).*/,'($1) $2-$3');
    else v = v.replace(/(\d{2})(\d{4})(\d{0,4}).*/,'($1) $2-$3');
    e.target.value = v;
  });

  const salaryInput = document.getElementById('salary');
  if (salaryInput) salaryInput.addEventListener('input', e=>{
    let v = e.target.value.replace(/\D/g,'');
    if (!v) { e.target.value = ''; return; }
    v = (parseInt(v,10)/100).toFixed(2).replace('.',',');
    e.target.value = v.replace(/(\d)(?=(\d{3})+(?!\d))/g,'$1.');
  });
});
</script>
