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

/* ----------------------- Helpers ----------------------- */
if (!function_exists('h')) {
  function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('base_url')) {
  function base_url($p=''){
    $b = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
    return ($b === '' ? '' : $b) . '/' . ltrim($p,'/');
  }
}
if (!function_exists('db_has_table')) {
  function db_has_table(PDO $pdo, string $tbl): bool {
    $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.TABLES
                         WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
    $st->execute([$tbl]); return (bool)$st->fetchColumn();
  }
}
if (!function_exists('db_has_col')) {
  function db_has_col(PDO $pdo, string $tbl, string $col): bool {
    $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS
                         WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?");
    $st->execute([$tbl,$col]); return (bool)$st->fetchColumn();
  }
}
if (!function_exists('t_status')) {
  function t_status(string $s): string { return $s; }
}
if (!function_exists('t_action')) {
  function t_action(string $a): string {
    $map = [
      'CREATE'=>'Criado','LOANED'=>'Emprestado','WRITE_OFF'=>'Baixado',
      'STATUS_CHANGE'=>'Alteração de status','RETURN_REQUEST_OPENED'=>'Solicitação de devolução',
      'MOVE'=>'Movimentação','OTHER'=>'Outro',
    ];
    return $map[$a] ?? $a;
  }
}
$fmt_br_dt = fn($s)=>($s&&($t=strtotime($s)))?date('d/m/Y H:i',$t):'—';
$fmt_br_d  = fn($s)=>($s&&($t=strtotime($s)))?date('d/m/Y',$t):'—';

/* ------------------------------ KPIs ---------------------------------- */
$kpi_active_loans   = (int)$pdo->query("SELECT COUNT(*) FROM loans WHERE status='DISPONIBILIZADO'")->fetchColumn();
$kpi_returned_loans = (int)$pdo->query("SELECT COUNT(*) FROM loans WHERE status='DEVOLVIDO'")->fetchColumn();

/* Devoluções (abertas) — mesma regra do return_requests.php */
$kpi_returns = 0;
if ($pdo->query("SHOW TABLES LIKE 'return_requests'")->fetchColumn()) {
  $kpi_returns = (int)$pdo->query("
      SELECT COUNT(*) 
      FROM return_requests rr 
      WHERE rr.status IN ('ABERTA','EM_ANDAMENTO')
  ")->fetchColumn();
}

/* Equipamentos por status */
$kpi_in_stock  = (int)$pdo->query("SELECT COUNT(*) FROM equipment WHERE status='EM_ESTOQUE'")->fetchColumn();
$kpi_loaned_eq = (int)$pdo->query("SELECT COUNT(*) FROM equipment WHERE status='EMPRESTADO'")->fetchColumn();
$kpi_maint     = (int)$pdo->query("SELECT COUNT(*) FROM equipment WHERE status='MANUTENCAO'")->fetchColumn();
$kpi_theft     = (int)$pdo->query("SELECT COUNT(*) FROM equipment WHERE status IN ('FURTO','EXTRAVIO')")->fetchColumn();
$kpi_decom     = (int)$pdo->query("SELECT COUNT(*) FROM equipment WHERE status='BAIXADO'")->fetchColumn();

/* ---------------------------- Gráficos -------------------------------- */
// Donut: distribuição (EM_ESTOQUE) por tipo
$pie_labels=[]; $pie_data=[];
$st = $pdo->query("SELECT COALESCE(t.name,'—') tipo, COUNT(*) qt
                   FROM equipment e
                   LEFT JOIN equipment_types t ON t.id=e.type_id
                   WHERE e.status='EM_ESTOQUE'
                   GROUP BY tipo ORDER BY qt DESC");
foreach($st as $r){ $pie_labels[]=$r['tipo']; $pie_data[]=(int)$r['qt']; }
if (!$pie_labels){ $pie_labels=['Sem dados']; $pie_data=[0]; }

// Barra: empréstimos por operação (mês corrente)
$bar_labels=[]; $bar_data=[];
$st = $pdo->query("SELECT COALESCE(o.name,'—') oper, COUNT(*) qt
                   FROM loans l
                   LEFT JOIN operations o ON o.id=l.operation_id
                   WHERE MONTH(l.data_entrega)=MONTH(CURDATE())
                     AND YEAR(l.data_entrega)=YEAR(CURDATE())
                   GROUP BY oper ORDER BY qt DESC");
foreach($st as $r){ $bar_labels[]=$r['oper']; $bar_data[]=(int)$r['qt']; }
if (!$bar_labels){ $bar_labels=['—']; $bar_data=[0]; }

/* ------------------------------ Listas -------------------------------- */
// Últimos empréstimos (Top 5)
$selectPrev = db_has_col($pdo,'loans','prev_devolucao') ? 'l.prev_devolucao' : 'NULL AS prev_devolucao';
$sqlLastLoans = "SELECT l.id, l.status, l.data_entrega, {$selectPrev}, l.chamado_glpi,
                        e.matricula, e.nome
                 FROM loans l
                 LEFT JOIN employees e ON e.id=l.employee_id
                 ORDER BY l.id DESC LIMIT 5";
$last_loans = $pdo->query($sqlLastLoans)->fetchAll();

// Últimas movimentações (Top 5) — tenta equipment_log, senão asset_log
$logTbl = db_has_table($pdo,'equipment_log') ? 'equipment_log'
        : (db_has_table($pdo,'asset_log') ? 'asset_log' : '');
$lastMoves=[]; $hasFrom=$hasTo=$hasLoan=$hasEmp=$hasUser=$hasNotes=false;
if ($logTbl){
  $hasFrom  = db_has_col($pdo,$logTbl,'from_status');
  $hasTo    = db_has_col($pdo,$logTbl,'to_status');
  $hasLoan  = db_has_col($pdo,$logTbl,'loan_id');
  $hasEmp   = db_has_col($pdo,$logTbl,'employee_id');
  $hasUser  = db_has_col($pdo,$logTbl,'user_id');
  $hasNotes = db_has_col($pdo,$logTbl,'notes');

  $cols = "lg.id, lg.action, lg.created_at";
  if ($hasFrom)  $cols.=", lg.from_status";
  if ($hasTo)    $cols.=", lg.to_status";
  if ($hasLoan)  $cols.=", lg.loan_id";
  if ($hasEmp)   $cols.=", lg.employee_id";
  if ($hasUser)  $cols.=", u.name AS user_name";
  if ($hasNotes) $cols.=", lg.notes";

  $sql = "SELECT {$cols} FROM {$logTbl} lg";
  if ($hasUser) $sql .= " LEFT JOIN users u ON u.id=lg.user_id";
  $sql .= " ORDER BY lg.id DESC LIMIT 5";
  $st = $pdo->query($sql);
  $lastMoves = $st ? $st->fetchAll() : [];
}

include __DIR__ . '/header.php';
?>
<div class="container-fluid">

  <!-- KPIs -->
  <div class="row g-3 mb-3">

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-muted small">Empréstimos ativos</div>
            <div class="fs-2 fw-semibold"><?= (int)$kpi_active_loans ?></div></div>
          <i class="bi bi-clipboard-check fs-1 text-primary opacity-75"></i>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-muted small">Devolvidos</div>
            <div class="fs-2 fw-semibold"><?= (int)$kpi_returned_loans ?></div></div>
          <i class="bi bi-arrow-90deg-left fs-1 text-success opacity-75"></i>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm" style="background:linear-gradient(135deg,#ffe1e1,#ffd3a0)">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-dark small fw-semibold">Devoluções (abertas)</div>
            <div class="fs-2 fw-bold text-dark"><?= (int)$kpi_returns ?></div></div>
          <i class="bi bi-box-arrow-in-left fs-1 text-dark opacity-75"></i>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-muted small">Em estoque</div>
            <div class="fs-2 fw-semibold"><?= (int)$kpi_in_stock ?></div></div>
          <i class="bi bi-box-seam fs-1 text-secondary opacity-75"></i>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-muted small">Emprestados</div>
            <div class="fs-2 fw-semibold"><?= (int)$kpi_loaned_eq ?></div></div>
          <i class="bi bi-arrow-up-right-square fs-1 text-info opacity-75"></i>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-muted small">Manutenção</div>
            <div class="fs-2 fw-semibold"><?= (int)$kpi_maint ?></div></div>
          <i class="bi bi-wrench-adjustable fs-1 text-warning opacity-75"></i>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-muted small">Furtos/Extravio</div>
            <div class="fs-2 fw-semibold"><?= (int)$kpi_theft ?></div></div>
          <i class="bi bi-shield-exclamation fs-1 text-danger opacity-75"></i>
        </div>
      </div>
    </div>

    <div class="col-12 col-md-4 col-xl-3">
      <div class="card border-0 shadow-sm">
        <div class="card-body d-flex justify-content-between align-items-center">
          <div><div class="text-muted small">Baixados</div>
            <div class="fs-2 fw-semibold"><?= (int)$kpi_decom ?></div></div>
          <i class="bi bi-trash3 fs-1 text-muted opacity-75"></i>
        </div>
      </div>
    </div>
  </div>

  <!-- Gráficos e listas -->
  <div class="row g-3">

    <div class="col-xl-6">
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
          <span>Distribuição do estoque</span>
          <span class="badge bg-light text-dark">Total: <?= (int)array_sum($pie_data) ?></span>
        </div>
        <div class="card-body">
          <div style="height:260px"><canvas id="pieStock"></canvas></div>
        </div>
      </div>
    </div>

    <div class="col-xl-6">
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">Empréstimos por operação (mês)</div>
        <div class="card-body">
          <div style="height:260px"><canvas id="barOps"></canvas></div>
        </div>
      </div>
    </div>

    <div class="col-xl-7">
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">Últimos empréstimos</div>
        <div class="table-responsive">
          <table class="table align-middle mb-0">
            <thead>
              <tr>
                <th>Matrícula</th><th>Nome</th><th>Chamado</th>
                <th>Status</th><th>Entrega</th><th>Prev. devolução</th><th></th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($last_loans as $l): ?>
                <tr>
                  <td><?= h($l['matricula']) ?></td>
                  <td><?= h($l['nome']) ?></td>
                  <td><?= h($l['chamado_glpi'] ?? '—') ?></td>
                  <td><span class="badge bg-secondary"><?= h(t_status($l['status'])) ?></span></td>
                  <td><?= $fmt_br_d($l['data_entrega'] ?? null) ?></td>
                  <td><?= $fmt_br_d($l['prev_devolucao'] ?? null) ?></td>
                  <td><a class="btn btn-sm btn-outline-primary" href="<?= base_url('loan_view.php?id='.(int)$l['id']) ?>">Abrir</a></td>
                </tr>
              <?php endforeach; if(!$last_loans): ?>
                <tr><td colspan="7" class="text-muted">Sem registros.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="col-xl-5">
      <div class="card border-0 shadow-sm">
        <div class="card-header bg-white">Últimas movimentações</div>
        <div class="table-responsive">
          <table class="table align-middle mb-0">
            <thead>
              <tr>
                <th>Quando</th><th>Ação</th>
                <?php if ($hasFrom || $hasTo): ?><th>De → Para</th><?php endif; ?>
                <?php if ($hasUser): ?><th>Por</th><?php endif; ?>
                <?php if ($hasLoan): ?><th>Empréstimo</th><?php endif; ?>
                <?php if ($hasEmp):  ?><th>Colaborador</th><?php endif; ?>
                <?php if ($hasNotes): ?><th>Notas</th><?php endif; ?>
              </tr>
            </thead>
            <tbody>
              <?php if ($lastMoves): foreach($lastMoves as $mv): ?>
                <tr>
                  <td><?= $fmt_br_dt($mv['created_at'] ?? null) ?></td>
                  <td><?= h(t_action($mv['action'] ?? '')) ?></td>
                  <?php if ($hasFrom || $hasTo): ?>
                    <td><?= h($hasFrom?($mv['from_status']??'—'):'—') ?> → <?= h($hasTo?($mv['to_status']??'—'):'—') ?></td>
                  <?php endif; ?>
                  <?php if ($hasUser): ?><td><?= h($mv['user_name'] ?? '—') ?></td><?php endif; ?>
                  <?php if ($hasLoan): ?><td><?= h($mv['loan_id'] ?? '—') ?></td><?php endif; ?>
                  <?php if ($hasEmp):  ?><td><?= h($mv['employee_id'] ?? '—') ?></td><?php endif; ?>
                  <?php if ($hasNotes): ?><td><?= h($mv['notes'] ?? '—') ?></td><?php endif; ?>
                </tr>
              <?php endforeach; else: ?>
                <tr><td colspan="7" class="text-muted">Sem movimentações recentes.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
(function(){
  const pieCtx = document.getElementById('pieStock');
  if (pieCtx) {
    new Chart(pieCtx, {
      type: 'doughnut',
      data: { labels: <?= json_encode($pie_labels, JSON_UNESCAPED_UNICODE) ?>,
              datasets: [{ data: <?= json_encode($pie_data) ?> }] },
      options: {
        responsive:true, maintainAspectRatio:false,
        plugins:{ legend:{ position:'bottom' } }, cutout:'60%'
      }
    });
  }
  const barCtx = document.getElementById('barOps');
  if (barCtx) {
    new Chart(barCtx, {
      type: 'bar',
      data: { labels: <?= json_encode($bar_labels, JSON_UNESCAPED_UNICODE) ?>,
              datasets: [{ data: <?= json_encode($bar_data) ?>, borderWidth:1 }] },
      options: { responsive:true, maintainAspectRatio:false,
        scales:{ y:{ beginAtZero:true, ticks:{ precision:0 } } } }
    });
  }
})();
</script>
<?php include __DIR__ . '/footer.php'; ?>

