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

// Abas: buscar | status
$tab = $_GET['tab'] ?? 'buscar';

// Resumo para o topo (sempre útil ao RH)
$rr_abertas = (int)$pdo->query("SELECT COUNT(*) FROM return_requests WHERE status IN ('ABERTA','EM_ANDAMENTO')")->fetchColumn();
$rr_vencidas = (int)$pdo->query("
  SELECT COUNT(*) FROM return_requests
  WHERE status IN ('ABERTA','EM_ANDAMENTO') AND deadline IS NOT NULL AND deadline < CURDATE()
")->fetchColumn();

include __DIR__ . '/header.php';
?>
<style>
  /* micro-ajustes visuais, mantendo o padrão do sistema */
  .badge-counter { font-size: .95rem; padding: .5rem .75rem; }
  .nav-tabs .nav-link { border: 0; border-bottom: 2px solid transparent; color: #6c757d; }
  .nav-tabs .nav-link.active { border-bottom-color: #0d6efd; color: #0d6efd; font-weight: 600; }
  .input-pill .form-control { border-radius: 2rem; }
  .input-pill .input-group-text { border-radius: 2rem 0 0 2rem; }
</style>

<div class="container-fluid">
  <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
    <h2 class="h5 m-0">Portal RH — Solicitação de devolução</h2>
    <div class="d-flex gap-2">
      <span class="badge badge-counter rounded-pill bg-warning text-dark">Abertas: <?= $rr_abertas ?></span>
      <span class="badge badge-counter rounded-pill bg-danger">Vencidas: <?= $rr_vencidas ?></span>
    </div>
  </div>

  <!-- Abas -->
  <ul class="nav nav-tabs mb-3">
    <li class="nav-item">
      <a class="nav-link <?= $tab==='buscar'?'active':'' ?>" href="<?= base_url('rh_portal.php?tab=buscar') ?>">
        Buscar colaborador
      </a>
    </li>
    <li class="nav-item">
      <a class="nav-link <?= $tab==='status'?'active':'' ?>" href="<?= base_url('rh_portal.php?tab=status') ?>">
        Status das solicitações
      </a>
    </li>
  </ul>

  <?php if ($tab==='buscar'): ?>
    <?php
      $mat = trim($_GET['matricula'] ?? '');
      $emp = null; $loans = []; $openReq = null; $history = [];

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

        if ($emp) {
          // Empréstimos ativos do colaborador
          $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 em aberto (se existir)
          $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();

          // Histórico do colaborador
          $h = $pdo->prepare("SELECT * FROM return_requests WHERE employee_id=? ORDER BY id DESC LIMIT 10");
          $h->execute([(int)$emp['id']]);
          $history = $h->fetchAll();
        }
      }
    ?>
    <form class="row g-2 mb-3" method="get" action="<?= base_url('rh_portal.php') ?>">
      <input type="hidden" name="tab" value="buscar">
      <div class="col-12 col-sm-8 col-md-6 col-lg-4">
        <div class="input-group input-pill">
          <span class="input-group-text"><i class="bi bi-search"></i></span>
          <input class="form-control" name="matricula" placeholder="Buscar por matrícula" value="<?= h($mat ?? '') ?>" required>
        </div>
      </div>
      <div class="col-auto">
        <button class="btn btn-primary">Buscar</button>
        <?php if ($mat!==''): ?>
          <a class="btn btn-outline-secondary" href="<?= base_url('rh_portal.php?tab=buscar') ?>">Limpar</a>
        <?php endif; ?>
      </div>
    </form>

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

    <?php if ($emp): ?>
      <div class="row g-3">
        <!-- Colaborador + ação rápida -->
        <div class="col-xl-5">
          <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">Colaborador</div>
            <div class="card-body">
              <div class="fs-6 fw-semibold mb-1"><?= h($emp['matricula'].' • '.$emp['nome']) ?></div>
              <div class="text-muted mb-3"><?= h($emp['tipo_formato']) ?> — <?= h($emp['operacao'] ?? '') ?></div>

              <?php if ($openReq): ?>
                <div class="alert alert-info d-flex justify-content-between align-items-center">
                  <div>Já existe solicitação aberta (<?= 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</a>
                </div>
              <?php elseif ($loans): ?>
                <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'] ?>">
                  <input type="hidden" name="source" value="RH_PORTAL">
                  <div class="col-lg-6">
                    <label class="form-label">Prazo sugerido</label>
                    <input type="date" name="deadline" class="form-control">
                  </div>
                  <div class="col-lg-6">
                    <label class="form-label">Observações</label>
                    <input name="notes" class="form-control" placeholder="Ex.: desligamento dia DD/MM">
                  </div>
                  <div class="col-12 d-grid">
                    <button class="btn btn-warning"><i class="bi bi-flag me-1"></i>Iniciar solicitação de devolução</button>
                  </div>
                </form>
              <?php else: ?>
                <div class="alert alert-success">Sem empréstimos ativos para este colaborador.</div>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- Empréstimos ativos -->
        <div class="col-xl-7">
          <div class="card border-0 shadow-sm h-100">
            <div class="card-header bg-white">Empréstimos ativos</div>
            <div class="card-body p-0">
              <div class="table-responsive">
                <table class="table table-striped mb-0 align-middle">
                  <thead><tr><th>Entrega</th><th>Prev. devolução</th><th>Itens</th><th></th></tr></thead>
                  <tbody>
                    <?php foreach ($loans as $l): ?>
                      <?php
                        $it = $pdo->prepare("SELECT COUNT(*) FROM loan_items WHERE loan_id=?");
                        $it->execute([(int)$l['id']]);
                        $countItems = (int)$it->fetchColumn();
                      ?>
                      <tr>
                        <td><?= br_date($l['data_entrega']) ?></td>
                        <td><?= br_date($l['due_date'] ?? null) ?></td>
                        <td><?= $countItems ?></td>
                        <td class="text-end">
                          <a class="btn btn-sm btn-outline-primary" href="<?= base_url('loan_view.php?id='.(int)$l['id']) ?>">Abrir</a>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                    <?php if (!$loans): ?>
                      <tr><td colspan="4" class="text-muted">Nenhum empréstimo ativo.</td></tr>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        <!-- Histórico de solicitações do colaborador -->
        <div class="col-12">
          <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">Solicitações anteriores deste colaborador</div>
            <div class="card-body p-0">
              <div class="table-responsive">
                <table class="table table-striped align-middle mb-0">
                  <thead><tr><th>Status</th><th>Prazo</th><th>Abertura</th><th>Atualização</th><th></th></tr></thead>
                  <tbody>
                    <?php foreach ($history as $r): ?>
                      <?php $warn = (in_array($r['status'],['ABERTA','EM_ANDAMENTO'], true) && $r['deadline'] && $r['deadline'] < date('Y-m-d')); ?>
                      <tr class="<?= $warn ? 'table-warning' : '' ?>">
                        <td><span class="badge bg-secondary"><?= t_rr_status($r['status']) ?></span></td>
                        <td><?= br_date($r['deadline'] ?? null) ?></td>
                        <td><?= br_datetime($r['created_at'] ?? null) ?></td>
                        <td><?= br_datetime($r['updated_at'] ?? null) ?></td>
                        <td class="text-end"><a class="btn btn-sm btn-outline-primary" href="<?= base_url('return_request_view.php?id='.(int)$r['id']) ?>">Abrir</a></td>
                      </tr>
                    <?php endforeach; ?>
                    <?php if (!$history): ?>
                      <tr><td colspan="5" class="text-muted">Sem histórico para este colaborador.</td></tr>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

      </div>
    <?php endif; // emp ?>
  <?php endif; // buscar ?>

  <?php if ($tab==='status'): ?>
    <?php
      // Filtros
      $f_status = $_GET['status'] ?? 'ABERTAS';
      $q = trim($_GET['q'] ?? '');
      $where=[]; $args=[];
      switch ($f_status) {
        case 'CONCLUIDAS': $where[]="rr.status='CONCLUIDA'"; break;
        case 'COBRANCA':   $where[]="rr.status='COBRANCA'"; break;
        case 'CANCELADAS': $where[]="rr.status='CANCELADA'"; break;
        case 'TODAS': break;
        default: $where[]="rr.status IN ('ABERTA','EM_ANDAMENTO')"; $f_status='ABERTAS';
      }
      if ($q!==''){ $where[]="(e.matricula LIKE ? OR e.nome LIKE ?)"; $args[]="%$q%"; $args[]="%$q%"; }

      $sql="SELECT rr.*, e.matricula, e.nome,
            (SELECT COUNT(*) FROM return_request_items i WHERE i.request_id=rr.id) AS itens
            FROM return_requests rr JOIN employees e ON e.id=rr.employee_id";
      if ($where) $sql .= ' WHERE '.implode(' AND ',$where);
      $sql .= ' ORDER BY rr.id DESC LIMIT 300';
      $rows = $pdo->prepare($sql); $rows->execute($args); $rows=$rows->fetchAll();
    ?>
    <form class="row g-2 align-items-end mb-3" method="get">
      <input type="hidden" name="tab" value="status">
      <div class="col-sm-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <?php foreach (['ABERTAS','CONCLUIDAS','COBRANCA','CANCELADAS','TODAS'] as $opt): ?>
            <option <?= $f_status===$opt?'selected':'' ?>><?= $opt ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-5">
        <label class="form-label">Matrícula ou nome</label>
        <input name="q" class="form-control" value="<?= h($q) ?>">
      </div>
      <div class="col-sm-4 d-flex gap-2">
        <button class="btn btn-outline-primary flex-fill">Filtrar</button>
        <a class="btn btn-outline-secondary" href="<?= base_url('rh_portal.php?tab=status') ?>">Limpar</a>
      </div>
    </form>

    <div class="card border-0 shadow-sm">
      <div class="table-responsive">
        <table class="table table-striped align-middle mb-0">
          <thead>
            <tr>
              <th>Matrícula</th><th>Nome</th><th>Status</th>
              <th>Prazo</th><th>Itens</th><th>Abertura</th><th>Atualização</th><th></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $r): $venc = in_array($r['status'],['ABERTA','EM_ANDAMENTO']) && $r['deadline'] && $r['deadline']<date('Y-m-d'); ?>
              <tr class="<?= $venc ? 'table-warning' : '' ?>">
                <td><?= h($r['matricula']) ?></td>
                <td><?= h($r['nome']) ?></td>
                <td><span class="badge bg-secondary"><?= t_rr_status($r['status']) ?></span></td>
                <td><?= br_date($r['deadline'] ?? null) ?></td>
                <td><?= (int)$r['itens'] ?></td>
                <td><?= br_datetime($r['created_at'] ?? null) ?></td>
                <td><?= br_datetime($r['updated_at'] ?? null) ?></td>
                <td class="text-end">
                  <a class="btn btn-sm btn-outline-primary" href="<?= base_url('return_request_view.php?id='.(int)$r['id']) ?>">Abrir</a>
                </td>
              </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?>
              <tr><td colspan="8" class="text-muted">Nenhuma solicitação encontrada.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; // status ?>
</div>
<?php include __DIR__ . '/footer.php'; ?>

