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

$mat = trim($_GET['matricula'] ?? '');
$emp = null; $loans = []; $openReq = null;

if ($mat !== '') {
  // Colaborador
  $st = $pdo->prepare('SELECT * FROM employees WHERE matricula=?');
  $st->execute([$mat]);
  $emp = $st->fetch();

  if ($emp) {
    // Empréstimos ativos
    $q = $pdo->prepare("SELECT * FROM loans WHERE employee_id=? AND status='DISPONIBILIZADO' ORDER BY id DESC");
    $q->execute([(int)$emp['id']]);
    $loans = $q->fetchAll();

    // Solicitação de devolução em aberto/andamento (se houver)
    $r = $pdo->prepare("SELECT * FROM return_requests WHERE employee_id=? AND status IN ('ABERTA','EM_ANDAMENTO') ORDER BY id DESC LIMIT 1");
    $r->execute([(int)$emp['id']]);
    $openReq = $r->fetch();
  }
}

include __DIR__ . '/header.php';
?>
<div class="container-fluid">
  <h2 class="h5 mb-3">Offboarding por matrícula</h2>

  <form class="row g-2 mb-3" method="get">
    <div class="col-auto">
      <input class="form-control" name="matricula" placeholder="Matrícula" value="<?= h($mat) ?>" required>
    </div>
    <div class="col-auto">
      <button class="btn btn-primary">Buscar</button>
    </div>
  </form>

  <?php if ($mat !== '' && !$emp): ?>
    <div class="alert alert-warning">Matrícula não encontrada.</div>
  <?php endif; ?>

  <?php if ($emp): ?>
    <div class="card border-0 shadow-sm mb-3">
      <div class="card-body">
        <div class="fw-semibold">Colaborador</div>
        <div><?= h($emp['matricula'].' • '.$emp['nome']) ?> — <?= h($emp['tipo_formato']) ?></div>
      </div>
    </div>

    <?php if ($openReq): ?>
      <div class="alert alert-info d-flex justify-content-between align-items-center">
        <div>
          Já existe uma solicitação de devolução aberta (#<?= (int)$openReq['id'] ?> — <?= t_rr_status($openReq['status']) ?>).
        </div>
        <a class="btn btn-sm btn-outline-primary" href="<?= base_url('return_request_view.php?id='.(int)$openReq['id']) ?>">Abrir solicitação</a>
      </div>
    <?php elseif ($loans): ?>
      <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white">Ação rápida</div>
        <div class="card-body">
          <form method="post" action="<?= base_url('return_request_create.php') ?>" class="row g-2">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="employee_id" value="<?= (int)$emp['id'] ?>">
            <div class="col-sm-3">
              <label class="form-label">Prazo sugerido</label>
              <input type="date" name="deadline" class="form-control">
            </div>
            <div class="col-sm-7">
              <label class="form-label">Observações</label>
              <input name="notes" class="form-control" placeholder="Ex.: desligamento previsto em DD/MM">
            </div>
            <div class="col-sm-2 d-flex align-items-end">
              <button class="btn btn-warning w-100">
                <i class="bi bi-flag me-1"></i>Iniciar solicitação
              </button>
            </div>
          </form>
        </div>
      </div>
    <?php endif; ?>

    <?php foreach ($loans as $l): ?>
      <?php
        $items = $pdo->prepare("SELECT li.equipment_id, e.patrimonio, e.serial, et.name tipo, e.modelo, e.status
          FROM loan_items li
          JOIN equipment e ON e.id=li.equipment_id
          JOIN equipment_types et ON et.id=e.type_id
          WHERE li.loan_id=?");
        $items->execute([(int)$l['id']]);
        $items = $items->fetchAll();
      ?>
      <div class="card border-0 shadow-sm mb-3">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
          <div>
            Empréstimo #<?= (int)$l['id'] ?> — <span class="badge bg-secondary"><?= t_status($l['status']) ?></span>
            <span class="ms-3 text-muted small">Entrega: <?= br_date($l['data_entrega']) ?></span>
            <?php if (!empty($l['due_date'])): ?>
              <span class="ms-3 text-muted small">Prev. devolução: <?= br_date($l['due_date']) ?></span>
            <?php endif; ?>
          </div>
          <a class="btn btn-sm btn-success" href="<?= base_url('return_checklist.php?loan_id='.(int)$l['id']) ?>">
            <i class="bi bi-clipboard-check me-1"></i>Checklist de devolução
          </a>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table mb-0">
              <thead><tr><th>#</th><th>Tipo/Modelo</th><th>Patrimônio</th><th>Serial</th><th>Status item</th></tr></thead>
              <tbody>
                <?php foreach ($items as $it): ?>
                  <tr>
                    <td>#<?= (int)$it['equipment_id'] ?></td>
                    <td><?= h(($it['tipo'] ?? '—') . ($it['modelo'] ? ' • '.$it['modelo'] : '')) ?></td>
                    <td><?= h($it['patrimonio'] ?? '—') ?></td>
                    <td><?= h($it['serial'] ?? '—') ?></td>
                    <td><span class="badge bg-secondary"><?= t_status($it['status']) ?></span></td>
                  </tr>
                <?php endforeach; ?>
                <?php if (!$items): ?>
                  <tr>
                    <td colspan="5" class="text-muted d-flex justify-content-between align-items-center">
                      <span>Sem itens vinculados a este empréstimo.</span>
                      <a class="btn btn-sm btn-outline-primary" href="<?= base_url('loan_attach_items.php?loan_id='.(int)$l['id']) ?>">
                        <i class="bi bi-link-45deg me-1"></i>Anexar itens do estoque
                      </a>
                    </td>
                  </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    <?php endforeach; ?>

    <?php if (!$loans): ?>
      <div class="alert alert-success">Nenhum empréstimo ativo para esta matrícula.</div>
    <?php endif; ?>
  <?php endif; ?>
</div>
<?php include __DIR__ . '/footer.php'; ?>

