<?php
// employees.php — Lista + modal "Novo colaborador" (padrão loans.php)
$title = 'Colaboradores';
require_once __DIR__ . '/auth.php';
require_login();
require_perm('employees.*');
check_csrf();

/* ==== helpers tolerantes ================================================== */
if (!function_exists('db_has_col')) {
  function db_has_col(PDO $pdo, string $table, string $col): bool {
    try {
      $st = $pdo->prepare("SELECT 1
         FROM INFORMATION_SCHEMA.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?");
      $st->execute([$table,$col]);
      return (bool)$st->fetchColumn();
    } catch (Throwable $e) {
      try {
        $st = $pdo->query("DESCRIBE `$table`");
        while ($r = $st->fetch(PDO::FETCH_ASSOC)) {
          if (($r['Field'] ?? '') === $col) return true;
        }
      } catch (Throwable $e2) {}
      return false;
    }
  }
}

/* ==== POST: criar colaborador ============================================ */
$err=''; $ok='';
if ($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['action'] ?? '')==='create') {
  $matricula = trim($_POST['matricula'] ?? '');
  $nome      = trim($_POST['nome'] ?? '');
  $formato   = trim($_POST['tipo_formato'] ?? 'PRESENCIAL');

  $hasOpId   = db_has_col($pdo,'employees','operation_id');
  $op_id     = (int)($_POST['operation_id'] ?? 0);
  $op_text   = trim($_POST['operacao_text'] ?? '');

  // extras
  $payload = [
    'cargo'          => trim($_POST['cargo'] ?? ''),
    'gestor_nome'    => trim($_POST['gestor_nome'] ?? ''),
    'gestor_email'   => trim($_POST['gestor_email'] ?? ''),
    'gestor_tel'     => trim($_POST['gestor_tel'] ?? ''),
    'celular'        => trim($_POST['celular'] ?? ''),
    'email_pessoal'  => trim($_POST['email_pessoal'] ?? ''),
    'end_cep'        => trim($_POST['end_cep'] ?? ''),
    'end_rua'        => trim($_POST['end_rua'] ?? ''),
    'end_numero'     => trim($_POST['end_numero'] ?? ''),
    'end_comp'       => trim($_POST['end_comp'] ?? ''),
    'end_bairro'     => trim($_POST['end_bairro'] ?? ''),
    'end_cidade'     => trim($_POST['end_cidade'] ?? ''),
    'end_uf'         => trim($_POST['end_uf'] ?? ''),
  ];

  if ($matricula==='') $err='Informe a matrícula.';
  elseif ($nome==='')  $err='Informe o nome.';

  if ($err==='') {
    try {
      $cols = ['matricula','nome','tipo_formato'];
      $vals = [$matricula,$nome,$formato];

      if ($hasOpId) { $cols[]='operation_id'; $vals[]=$op_id; }
      elseif (db_has_col($pdo,'employees','operacao')) { $cols[]='operacao'; $vals[]=$op_text; }

      foreach ($payload as $c=>$v) {
        if (db_has_col($pdo,'employees',$c)) { $cols[]=$c; $vals[]=$v; }
      }

      $ph = implode(',', array_fill(0,count($cols),'?'));
      $sql = "INSERT INTO employees (".implode(',',$cols).") VALUES ($ph)";
      $pdo->prepare($sql)->execute($vals);
      $ok='Colaborador cadastrado com sucesso.';
    } catch(Throwable $e){ $err='Erro ao salvar: '.$e->getMessage(); }
  }
}

/* ==== LISTA com busca (estilo loans.php) ================================= */
$hasOpId       = db_has_col($pdo,'employees','operation_id');
$hasOpText     = db_has_col($pdo,'employees','operacao');
$hasEmail      = db_has_col($pdo,'employees','email_pessoal');
$hasGestNome   = db_has_col($pdo,'employees','gestor_nome');
$hasCargo      = db_has_col($pdo,'employees','cargo');

$selectOper =
  $hasOpId   ? 'o.name' :
  ($hasOpText ? 'e.operacao' : 'NULL');

$selEmail     = $hasEmail    ? 'e.email_pessoal' : 'NULL';
$selGestNome  = $hasGestNome ? 'e.gestor_nome'   : 'NULL';
$selCargo     = $hasCargo    ? 'e.cargo'         : 'NULL';

$q = trim($_GET['q'] ?? '');

$sql = "SELECT
          e.matricula,
          e.nome,
          e.tipo_formato,
          $selectOper  AS operacao,
          $selCargo    AS cargo,
          $selEmail    AS email_pessoal,
          $selGestNome AS gestor_nome
        FROM employees e";
if ($hasOpId) $sql .= " LEFT JOIN operations o ON o.id = e.operation_id";

$where=[]; $args=[];
if ($q !== '') {
  $likeFields = ['e.matricula','e.nome'];
  if ($hasOpId)        $likeFields[] = 'o.name';
  elseif ($hasOpText)  $likeFields[] = 'e.operacao';
  if ($hasEmail)       $likeFields[] = 'e.email_pessoal';
  if ($hasGestNome)    $likeFields[] = 'e.gestor_nome';
  if ($hasCargo)       $likeFields[] = 'e.cargo';

  $where[] = '(' . implode(' OR ', array_map(fn($f)=>"$f LIKE ?", $likeFields)) . ')';
  $args = array_fill(0, count($likeFields), "%{$q}%");
}
if ($where) $sql .= " WHERE ".implode(' AND ', $where);
$sql .= " ORDER BY e.id DESC";

$rows = $pdo->prepare($sql);
$rows->execute($args);
$rows = $rows->fetchAll();

/* ==== operações para combo do modal (se houver FK) ======================= */
$ops  = $hasOpId ? $pdo->query("SELECT id,name FROM operations ORDER BY name")->fetchAll(PDO::FETCH_ASSOC) : [];

include __DIR__ . '/header.php';
?>
<div class="container-fluid">
  <div class="d-flex align-items-center mb-3">
    <h2 class="h5 m-0">Colaboradores</h2>

    <form method="get" class="ms-auto" style="max-width:420px;">
      <div class="input-group">
        <input class="form-control" name="q" value="<?= h($q) ?>" placeholder="Buscar por matrícula, nome, operação, cargo...">
        <button class="btn btn-outline-secondary">Filtrar</button>
        <a class="btn btn-outline-secondary" href="<?= base_url('employees.php') ?>">Limpar</a>
      </div>
    </form>

    <button class="btn btn-primary ms-2" data-bs-toggle="modal" data-bs-target="#modalNew">+ Novo</button>
  </div>

  <?php if ($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>
  <?php if ($ok):  ?><div class="alert alert-success"><?= h($ok)  ?></div><?php endif; ?>

  <div class="table-responsive">
    <table class="table table-hover table-striped align-middle mb-0">
      <thead>
        <tr>
          <th>Matrícula</th>
          <th>Nome</th>
          <th>Formato</th>
          <th>Operação</th>
          <th>Cargo</th>
          <th>E-mail</th>
          <th>Gestor (nome)</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($rows as $r): ?>
          <tr>
            <td><?= h($r['matricula']) ?></td>
            <td><?= h($r['nome']) ?></td>
            <td><?= h($r['tipo_formato']) ?></td>
            <td><?= h($r['operacao'] ?? '—') ?></td>
            <td><?= h($r['cargo'] ?? '—') ?></td>
            <td><?= h($r['email_pessoal'] ?? '—') ?></td>
            <td><?= h($r['gestor_nome'] ?? '—') ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if(!$rows): ?>
          <tr><td colspan="7" class="text-muted">Nenhum colaborador.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal Novo colaborador -->
<div class="modal fade" id="modalNew" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form class="modal-content" method="post" novalidate>
      <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
      <input type="hidden" name="action" value="create">

      <div class="modal-header">
        <h5 class="modal-title">Novo colaborador</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
      </div>

      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Matrícula</label>
            <input name="matricula" class="form-control" required>
          </div>
          <div class="col-md-8">
            <label class="form-label">Nome</label>
            <input name="nome" class="form-control" required>
          </div>

          <div class="col-md-4">
            <label class="form-label">Formato</label>
            <select name="tipo_formato" class="form-select">
              <option value="PRESENCIAL">Presencial</option>
              <option value="HOME">Home Office</option>
              <option value="HIBRIDO">Híbrido</option>
            </select>
          </div>

          <div class="col-md-8">
            <label class="form-label">Operação / Depto</label>
            <?php if ($hasOpId): ?>
              <select name="operation_id" class="form-select">
                <option value="0">—</option>
                <?php foreach($ops as $o): ?>
                  <option value="<?= (int)$o['id'] ?>"><?= h($o['name']) ?></option>
                <?php endforeach; ?>
              </select>
            <?php elseif ($hasOpText): ?>
              <input name="operacao_text" class="form-control" placeholder="Nome da operação / área">
            <?php else: ?>
              <input name="operacao_text" class="form-control" placeholder="(coluna não existe, salvo apenas se criada)">
            <?php endif; ?>
          </div>

          <div class="col-md-6">
            <label class="form-label">Cargo</label>
            <input name="cargo" class="form-control" placeholder="Ex.: Analista de Suporte">
          </div>

          <div class="col-12"><hr></div>

          <div class="col-md-4">
            <label class="form-label">Gestor — nome</label>
            <input name="gestor_nome" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Gestor — e-mail</label>
            <input type="email" name="gestor_email" class="form-control" inputmode="email" placeholder="gestor@empresa.com">
          </div>
          <div class="col-md-4">
            <label class="form-label">Gestor — telefone</label>
            <input name="gestor_tel" class="form-control" placeholder="(DDD) 9xxxx-xxxx" data-mask="tel">
          </div>

          <div class="col-md-4">
            <label class="form-label">Celular</label>
            <input name="celular" class="form-control" placeholder="(DDD) 9xxxx-xxxx" data-mask="tel">
          </div>
          <div class="col-md-8">
            <label class="form-label">E-mail pessoal</label>
            <input type="email" name="email_pessoal" class="form-control" inputmode="email" placeholder="nome@exemplo.com">
          </div>

          <div class="col-12"><hr></div>

          <div class="col-md-3">
            <label class="form-label">CEP</label>
            <input name="end_cep" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Rua</label>
            <input name="end_rua" class="form-control">
          </div>
          <div class="col-md-3">
            <label class="form-label">Número</label>
            <input name="end_numero" class="form-control">
          </div>
          <div class="col-md-3">
            <label class="form-label">Compl.</label>
            <input name="end_comp" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Bairro</label>
            <input name="end_bairro" class="form-control">
          </div>
          <div class="col-md-4">
            <label class="form-label">Cidade</label>
            <input name="end_cidade" class="form-control">
          </div>
          <div class="col-md-1">
            <label class="form-label">UF</label>
            <input name="end_uf" class="form-control" maxlength="2">
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-primary">Salvar</button>
      </div>
    </form>
  </div>
</div>

<script>
// Máscara simples para telefones brasileiros: (DD) 9XXXX-XXXX
(function(){
  function maskTel(value){
    const d = value.replace(/\D/g,'').slice(0,11);
    if (d.length <= 10) {
      return d
        .replace(/^(\d{0,2})/, '($1')
        .replace(/^\((\d{2})(\d{0,4})/, '($1) $2')
        .replace(/^\((\d{2})\) (\d{4})(\d{0,4}).*/, '($1) $2-$3');
    }
    return d
      .replace(/^(\d{0,2})/, '($1')
      .replace(/^\((\d{2})(\d{0,5})/, '($1) $2')
      .replace(/^\((\d{2})\) (\d{5})(\d{0,4}).*/, '($1) $2-$3');
  }
  document.querySelectorAll('input[data-mask="tel"]').forEach(inp=>{
    inp.addEventListener('input', ()=> { inp.value = maskTel(inp.value); });
    inp.addEventListener('blur',  ()=> { inp.value = maskTel(inp.value); });
  });
})();
</script>

<?php include __DIR__ . '/footer.php'; ?>

