<?php
$title = 'Empréstimos';
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();

/* ============================================================
   Helpers de compatibilidade e utilidades locais
   ============================================================ */
function db_has_column(PDO $pdo, string $table, string $col): bool {
  try {
    $stmt = $pdo->prepare("SELECT 1
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
    $stmt->execute([$table, $col]);
    return (bool)$stmt->fetchColumn();
  } catch (Throwable $e) {
    // Fallback
    try {
      $stmt = $pdo->query("DESCRIBE `$table`");
      while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if (isset($r['Field']) && $r['Field'] === $col) return true;
      }
    } catch (Throwable $e2) {}
  }
  return false;
}

function current_uid(): ?int {
  return $_SESSION['user']['id'] ?? ($_SESSION['user_id'] ?? ($_SESSION['uid'] ?? null));
}

function br_to_sql_date(?string $d): ?string {
  if (!$d) return null;
  if (preg_match('~^\d{4}-\d{2}-\d{2}$~', $d)) return $d; // yyyy-mm-dd
  if (preg_match('~^(\d{2})/(\d{2})/(\d{4})$~', $d, $m)) return "{$m[3]}-{$m[2]}-{$m[1]}";
  return null;
}

function status_badge_class(string $s): string {
  $map = [
    'DISPONIBILIZADO' => 'secondary',
    'DEVOLVIDO'       => 'success',
    'EXTRAVIADO'      => 'dark',
    'DEFEITO'         => 'warning',
    'MANUTENCAO'      => 'warning',
    'EM MANUTENÇÃO'   => 'warning',
    'EMPRESTADO'      => 'primary',
  ];
  return 'badge bg-' . ($map[$s] ?? 'secondary');
}

/* ============================================================
   AJAX leve para buscar colaborador por matrícula
   GET loans.php?ajax=emp&matricula=123
   ============================================================ */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'emp') {
  header('Content-Type: application/json; charset=utf-8');
  $mat = trim($_GET['matricula'] ?? '');
  if ($mat === '') { echo json_encode(['ok'=>false]); exit; }
  $st = $pdo->prepare("SELECT id, nome FROM employees WHERE matricula=? LIMIT 1");
  $st->execute([$mat]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  if ($row) {
    echo json_encode(['ok'=>true, 'id'=>(int)$row['id'], 'name'=>$row['nome']]);
  } else {
    echo json_encode(['ok'=>false]);
  }
  exit;
}

/* ============================================================
   POST: criação do empréstimo
   ============================================================ */
$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_loan'])) {
  try {
    $matricula      = trim($_POST['matricula'] ?? '');
    $employee_id    = null;
    if ($matricula !== '') {
      $q = $pdo->prepare("SELECT id FROM employees WHERE matricula=? LIMIT 1");
      $q->execute([$matricula]);
      $employee_id = $q->fetchColumn();
    }
    if (!$employee_id) throw new RuntimeException('Matrícula não encontrada.');

    $operation_id   = $_POST['operation_id'] !== '' ? (int)$_POST['operation_id'] : null;
    $chamado_glpi   = trim($_POST['chamado_glpi'] ?? '');
    $data_entrega   = br_to_sql_date($_POST['data_entrega'] ?? date('Y-m-d')) ?? date('Y-m-d');
    $prev_devol     = br_to_sql_date($_POST['prev_devolucao'] ?? null);
    $forma_entrega  = trim($_POST['forma_entrega'] ?? '');
    $rastreio       = trim($_POST['rastreio'] ?? '');
    $descricao      = trim($_POST['descricao'] ?? '');
    $itens          = $_POST['equip_ids'] ?? [];

    if (!is_array($itens) || count($itens) === 0) {
      throw new RuntimeException('Selecione ao menos 1 item em estoque.');
    }

    $has_prev   = db_has_column($pdo, 'loans', 'prev_devolucao');
    $has_forma  = db_has_column($pdo, 'loans', 'forma_entrega');

    if (!$has_forma && $forma_entrega !== '') {
      $descricao = "Forma de entrega: {$forma_entrega}" . ($rastreio ? " • Rastreio: {$rastreio}" : '') .
                   ($descricao ? " — {$descricao}" : '');
    } elseif ($rastreio !== '') {
      $descricao = ($descricao ? "{$descricao} — " : '') . "Rastreio: {$rastreio}";
    }

    $uid = current_uid();
    if (!$uid) $uid = 1; // fallback

    $pdo->beginTransaction();

    $cols = ['employee_id','operation_id','chamado_glpi','data_entrega','status','descricao','disponibilizado_por','created_at'];
    $vals = [ $employee_id, $operation_id, $chamado_glpi, $data_entrega, 'DISPONIBILIZADO', $descricao, $uid, date('Y-m-d H:i:s') ];

    if ($has_prev)  { $cols[] = 'prev_devolucao';  $vals[] = $prev_devol; }
    if ($has_forma) { $cols[] = 'forma_entrega';   $vals[] = $forma_entrega; }

    $ph  = implode(',', array_fill(0, count($cols), '?'));
    $sql = "INSERT INTO loans (".implode(',', $cols).") VALUES ($ph)";
    $ins = $pdo->prepare($sql);
    $ins->execute($vals);
    $loan_id = (int)$pdo->lastInsertId();

    $insItem = $pdo->prepare("INSERT INTO loan_items (loan_id, equipment_id) VALUES (?,?)");
    $upEq    = $pdo->prepare("UPDATE equipment SET status='EMPRESTADO' WHERE id=? AND status='EM_ESTOQUE'");
    foreach ($itens as $eqid) {
      $eqid = (int)$eqid;
      $insItem->execute([$loan_id, $eqid]);
      $upEq->execute([$eqid]);
    }

    $pdo->commit();
    header('Location: '.base_url('loan_view.php?id='.$loan_id));
    exit;

  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    $err = $e->getMessage();
  }
}

/* ============================================================
   Dados para a listagem (filtros/ordenação/busca)
   ============================================================ */
$q       = trim($_GET['q'] ?? '');
$sort    = $_GET['sort'] ?? 'l.id';
$dir     = strtoupper($_GET['dir'] ?? 'DESC');
$dir     = in_array($dir, ['ASC','DESC'], true) ? $dir : 'DESC';

$sortable = [
  'matricula'     => 'e.matricula',
  'nome'          => 'e.nome',
  'operacao'      => 'o.name',
  'qtd'           => 'qtd',
  'chamado'       => 'l.chamado_glpi',
  'entrega'       => 'l.data_entrega',
  'prev'          => 'l.prev_devolucao',
  'status'        => 'l.status',
  'id'            => 'l.id'
];
if (isset($sortable[$sort])) $sort = $sortable[$sort]; else $sort = 'l.id';

$has_prev = db_has_column($pdo, 'loans', 'prev_devolucao');

$sql = "SELECT
          l.id,
          e.matricula, e.nome,
          o.name AS operacao,
          (SELECT COUNT(*) FROM loan_items li WHERE li.loan_id=l.id) AS qtd,
          l.chamado_glpi,
          l.data_entrega".
        ($has_prev ? ", l.prev_devolucao" : ", NULL AS prev_devolucao").",
          l.status
        FROM loans l
        JOIN employees e ON e.id=l.employee_id
        LEFT JOIN operations o ON o.id=l.operation_id";

$where = [];
$args  = [];
if ($q !== '') {
  $where[] = "(e.matricula LIKE ? OR e.nome LIKE ? OR o.name LIKE ? OR l.chamado_glpi LIKE ?)";
  $args = array_fill(0, 4, "%{$q}%");
}
if ($where) $sql .= " WHERE ".implode(' AND ', $where);
$sql .= " ORDER BY {$sort} {$dir} LIMIT 500";

$list = $pdo->prepare($sql);
$list->execute($args);
$list = $list->fetchAll(PDO::FETCH_ASSOC);

/* ============================================================
   Dados para o modal (combo de operações e itens em estoque)
   ============================================================ */
$ops = $pdo->query("SELECT id, name FROM operations ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$stock = $pdo->query("SELECT e.id, et.name AS tipo, e.modelo, e.patrimonio, e.serial
                      FROM equipment e
                      JOIN equipment_types et ON et.id=e.type_id
                      WHERE e.status='EM_ESTOQUE'
                      ORDER BY et.name, e.modelo, e.id DESC")->fetchAll(PDO::FETCH_ASSOC);

include __DIR__ . '/header.php';
?>

<!-- CSS mínimo para garantir barra de rolagem e não esconder o textarea -->
<style>
  /* Força rolagem vertical dentro do corpo do modal
     e dá espaço pro rodapé não sobrepor o campo de descrição */
  #newLoanModal .modal-body{
    max-height: calc(100vh - 180px);
    overflow-y: auto;
    padding-bottom: 5.5rem;
  }
</style>

<div class="container-fluid">
  <div class="d-flex align-items-center mb-3">
    <h2 class="h5 m-0">Empréstimos</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, chamado..." />
        <button class="btn btn-outline-secondary">Filtrar</button>
        <a class="btn btn-outline-secondary" href="<?= base_url('loans.php') ?>">Limpar</a>
      </div>
    </form>

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

  <div class="table-responsive">
    <table class="table table-hover table-striped align-middle">
      <thead>
        <tr>
          <th>
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'matricula','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Matrícula</a>
          </th>
          <th>
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'nome','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Nome</a>
          </th>
          <th>
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'operacao','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Operação</a>
          </th>
          <th class="text-center">
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'qtd','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Qtd</a>
          </th>
          <th>
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'chamado','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Chamado</a>
          </th>
          <th>
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'entrega','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Entrega</a>
          </th>
          <th>
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'prev','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Prev. devolução</a>
          </th>
          <th>
            <a href="?<?= http_build_query(['q'=>$q,'sort'=>'status','dir'=>$dir==='ASC'?'DESC':'ASC']) ?>" class="text-decoration-none">Status</a>
          </th>
          <th class="text-end">Ações</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($list as $r): ?>
          <tr>
            <td><?= h($r['matricula']) ?></td>
            <td><?= h($r['nome']) ?></td>
            <td><?= h($r['operacao'] ?? '—') ?></td>
            <td class="text-center"><?= (int)$r['qtd'] ?></td>
            <td><?= h($r['chamado_glpi'] ?? '—') ?></td>
            <td><?= br_date($r['data_entrega']) ?></td>
            <td><?= br_date($r['prev_devolucao'] ?? null) ?></td>
            <td><span class="<?= status_badge_class($r['status']) ?>"><?= h($r['status']) ?></span></td>
            <td class="text-end">
              <a class="btn btn-sm btn-outline-primary" href="<?= base_url('loan_view.php?id='.(int)$r['id']) ?>">Abrir</a>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$list): ?>
          <tr><td colspan="9" class="text-muted">Nenhum empréstimo encontrado.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal Novo Empréstimo -->
<div class="modal fade" id="newLoanModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="create_loan" value="1">
        <div class="modal-header">
          <h5 class="modal-title">Novo empréstimo</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button>
        </div>

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

          <div class="row g-3">
            <div class="col-lg-6">
              <label class="form-label">Matrícula do colaborador</label>
              <input class="form-control" name="matricula" id="matriculaInput" placeholder="Ex.: 123456" required>
              <div class="form-text">Digite a matrícula e aguarde a confirmação do nome.</div>
            </div>
            <div class="col-lg-6">
              <label class="form-label">Nome do colaborador (confirmação)</label>
              <input class="form-control" id="nomeConfirm" placeholder="—" disabled>
            </div>

            <div class="col-lg-6">
              <label class="form-label">Operação</label>
              <select class="form-select" name="operation_id">
                <option value="">—</option>
                <?php foreach ($ops as $op): ?>
                  <option value="<?= (int)$op['id'] ?>"><?= h($op['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-lg-6">
              <label class="form-label">Chamado GLPI</label>
              <input class="form-control" name="chamado_glpi" placeholder="Ex.: 12345">
            </div>

            <div class="col-lg-6">
              <label class="form-label">Data de entrega</label>
              <input type="date" class="form-control" name="data_entrega" value="<?= date('Y-m-d') ?>" readonly>
              <div class="form-text">Preenchido automaticamente (somente leitura).</div>
            </div>
            <div class="col-lg-6">
              <label class="form-label">Devolução prevista (opcional)</label>
              <div class="input-group">
                <input type="date" class="form-control" name="prev_devolucao" placeholder="dd/mm/aaaa">
              </div>
              <div class="form-text">Use o calendário. Opcional.</div>
            </div>

            <div class="col-12">
              <label class="form-label">Selecionar itens (somente em estoque)</label>
              <select class="form-select" name="equip_ids[]" id="equipSelect" multiple size="8">
                <?php foreach ($stock as $s):
                  $label = trim($s['tipo'].' • '.($s['modelo'] ?: '').($s['patrimonio'] ? ' • PAT '.$s['patrimonio'] : '').($s['serial'] ? ' • SN '.$s['serial'] : ''));
                  $label = preg_replace('~\s+•\s+$~','',$label);
                ?>
                  <option value="<?= (int)$s['id'] ?>"><?= h($label) ?></option>
                <?php endforeach; ?>
              </select>
              <div class="form-text"><span id="selCount">0</span> selecionado(s). A quantidade será calculada automaticamente.</div>
            </div>

            <div class="col-lg-6">
              <label class="form-label">Forma de entrega</label>
              <select class="form-select" name="forma_entrega">
                <option value="">—</option>
                <option>RETIRADA</option>
                <option>MOTOBOY</option>
                <option>CORREIOS</option>
                <option>TERCEIRO</option>
              </select>
            </div>
            <div class="col-lg-6">
              <label class="form-label">Rastreamento (opcional)</label>
              <input class="form-control" name="rastreio" placeholder="Ex.: LB123456789BR">
            </div>

            <div class="col-12">
              <label class="form-label">Descrição/Observação</label>
              <textarea class="form-control" name="descricao" rows="3" placeholder="Regras, condições, observações, etc."></textarea>
            </div>
          </div>
        </div>

        <div class="modal-footer position-sticky bottom-0 bg-white">
          <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Fechar</button>
          <button class="btn btn-primary">Salvar</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
(() => {
  // Atualiza contador de itens selecionados
  const equip = document.getElementById('equipSelect');
  const selCount = document.getElementById('selCount');
  if (equip && selCount) {
    const upd = () => selCount.textContent = [...equip.options].filter(o => o.selected).length;
    equip.addEventListener('change', upd);
    upd();
  }

  // Busca nome por matrícula
  const mat = document.getElementById('matriculaInput');
  const nome = document.getElementById('nomeConfirm');
  let t = null;
  function lookup() {
    const v = mat.value.trim();
    if (!v) { nome.value = '—'; nome.classList.remove('is-invalid'); return; }
    fetch('<?= base_url('loans.php') ?>?ajax=emp&matricula=' + encodeURIComponent(v), {headers: {'X-Requested-With':'fetch'}})
      .then(r => r.json()).then(j => {
        if (j.ok) { nome.value = j.name; nome.classList.remove('is-invalid'); }
        else { nome.value = 'Matrícula não encontrada'; nome.classList.add('is-invalid'); }
      }).catch(() => { nome.value = 'Erro ao buscar'; nome.classList.add('is-invalid'); });
  }
  if (mat && nome) {
    mat.addEventListener('input', () => { clearTimeout(t); t = setTimeout(lookup, 300); });
    mat.addEventListener('blur', lookup);
  }

  // Garante espaçamento extra quando o modal abre (reforço visual)
  const mdl = document.getElementById('newLoanModal');
  if (mdl) mdl.addEventListener('shown.bs.modal', () => {
    document.querySelector('#newLoanModal .modal-body')?.classList.add('pb-2');
  });
})();
</script>

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

