<?php
require_once __DIR__ . '/auth.php';

// Badges (protegido com try)
try {
  $badge_loans   = (int)$pdo->query("SELECT COUNT(*) FROM loans WHERE status='DISPONIBILIZADO'")->fetchColumn();
  $badge_stock   = (int)$pdo->query("SELECT COUNT(*) FROM equipment WHERE status='EM_ESTOQUE'")->fetchColumn();
  $badge_returns = (int)$pdo->query("SELECT COUNT(*) FROM return_requests WHERE status IN ('ABERTA','EM_ANDAMENTO')")->fetchColumn();

  $ALERT_MAINT_DAYS = 15; $ALERT_TERM_GRACE = 3;
  $badge_overdue_loans = (int)$pdo->query("SELECT COUNT(*) FROM loans WHERE status='DISPONIBILIZADO' AND due_date IS NOT NULL AND due_date < CURDATE()")->fetchColumn();
  $badge_rr_overdue   = (int)$pdo->query("SELECT COUNT(*) FROM return_requests WHERE status IN ('ABERTA','EM_ANDAMENTO') AND deadline IS NOT NULL AND deadline < CURDATE()")->fetchColumn();

  $stNT=$pdo->prepare("SELECT COUNT(*) FROM loans l WHERE l.status='DISPONIBILIZADO' AND l.data_entrega <= DATE_SUB(CURDATE(), INTERVAL ? DAY) AND NOT EXISTS (SELECT 1 FROM loan_terms t WHERE t.loan_id=l.id)");
  $stNT->execute([$ALERT_TERM_GRACE]); $badge_no_term=(int)$stNT->fetchColumn();

  $stM=$pdo->prepare("
    SELECT COUNT(*) FROM (
      SELECT e.id,(SELECT MAX(l.created_at) FROM equipment_log l WHERE l.equipment_id=e.id AND l.to_status='MANUTENCAO') since
      FROM equipment e WHERE e.status='MANUTENCAO'
    ) x WHERE x.since IS NULL OR DATEDIFF(CURDATE(), DATE(x.since)) > ?
  "); $stM->execute([$ALERT_MAINT_DAYS]); $badge_maint=(int)$stM->fetchColumn();

  $badge_alerts = $badge_overdue_loans + $badge_rr_overdue + $badge_no_term + $badge_maint;
} catch(Throwable $e){ $badge_loans=$badge_stock=$badge_returns=$badge_alerts=0; }

$self = basename($_SERVER['PHP_SELF'] ?? '');
function nav_active($f,$s){ return $f===$s?'active':''; }

$isRH = (current_user()['role'] ?? '') === 'RH';
$dashFile = $isRH ? 'rh_dashboard.php' : 'index.php';
?>
<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= h($title ?? 'SDTrack') ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<link href="<?= base_url('assets/css/custom.css') ?>" rel="stylesheet">

<!-- Chart.js (CDN + fallback local) -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js" crossorigin="anonymous"></script>
<script>if(!window.Chart){var s=document.createElement('script');s.src='<?= base_url('assets/js/chart.umd.min.js') ?>';document.head.appendChild(s);}</script>
</head>
<body>
<div class="d-flex">
<nav class="flex-shrink-0 p-3 bg-dark text-white min-vh-100" style="width:260px;">
  <a href="<?= base_url($dashFile) ?>" class="d-flex align-items-center mb-3 text-white text-decoration-none">
    <i class="bi bi-layers fs-3 me-2"></i><span class="fs-5">SDTrack</span>
  </a>
  <hr class="border-secondary">
  <ul class="nav nav-pills flex-column mb-auto">
    <?php if (user_has_perm('dashboard.view') || $isRH): ?>
    <li class="nav-item">
      <a class="nav-link text-white <?= nav_active($dashFile,$self) ?>" href="<?= base_url($dashFile) ?>">
        <i class="bi bi-speedometer2 me-2"></i>Dashboard
      </a>
    </li>
    <?php endif; ?>

    <?php if (user_has_perm('loans.view')): ?>
    <li><a class="nav-link text-white d-flex justify-content-between align-items-center <?= nav_active('loans.php',$self) ?>" href="<?= base_url('loans.php') ?>"><span><i class="bi bi-clipboard2-check me-2"></i>Empréstimos</span><span class="badge bg-primary rounded-pill"><?= $badge_loans ?></span></a></li>
    <?php endif; ?>

    <?php if (user_has_perm('employees.*')): ?>
    <li><a class="nav-link text-white <?= nav_active('employees.php',$self) ?>" href="<?= base_url('employees.php') ?>"><i class="bi bi-people me-2"></i>Colaboradores</a></li>
    <?php endif; ?>

    <?php if (user_has_perm('operations.*')): ?>
    <li><a class="nav-link text-white <?= nav_active('operations.php',$self) ?>" href="<?= base_url('operations.php') ?>"><i class="bi bi-diagram-3 me-2"></i>Operações</a></li>
    <?php endif; ?>

    <?php if (user_has_perm('types.*')): ?>
    <li><a class="nav-link text-white <?= nav_active('types.php',$self) ?>" href="<?= base_url('types.php') ?>"><i class="bi bi-hdd-stack me-2"></i>Tipos</a></li>
    <?php endif; ?>

    <?php if (user_has_perm('equipment.view')): ?>
    <li><a class="nav-link text-white d-flex justify-content-between align-items-center <?= nav_active('equipment.php',$self) ?>" href="<?= base_url('equipment.php') ?>"><span><i class="bi bi-box-seam me-2"></i>Equipamentos / Estoque</span><span class="badge bg-success rounded-pill"><?= $badge_stock ?></span></a></li>
    <?php endif; ?>

    <?php if (user_has_perm('equipment.*')): ?>
      <li><a class="nav-link text-white <?= nav_active('stock.php',$self) ?>" href="<?= base_url('stock.php') ?>"><i class="bi bi-archive me-2"></i>Movimentar Status</a></li>
      <li><a class="nav-link text-white <?= nav_active('locations.php',$self) ?>" href="<?= base_url('locations.php') ?>"><i class="bi bi-geo-alt me-2"></i>Locais</a></li>
      <li><a class="nav-link text-white <?= nav_active('scan.php',$self) ?>" href="<?= base_url('scan.php') ?>"><i class="bi bi-qr-code-scan me-2"></i>Scanner (beta)</a></li>
    <?php endif; ?>

    <?php if (user_has_perm('returns.view')): ?>
    <li><a class="nav-link text-white d-flex justify-content-between align-items-center <?= nav_active('return_requests.php',$self) ?>" href="<?= base_url('return_requests.php') ?>"><span><i class="bi bi-arrow-90deg-left me-2"></i>Devoluções</span><span class="badge bg-warning text-dark rounded-pill"><?= $badge_returns ?></span></a></li>
    <?php endif; ?>

    <?php if (user_has_perm('rh.portal')): ?>
    <li><a class="nav-link text-white <?= nav_active('rh_portal.php',$self) ?>" href="<?= base_url('rh_portal.php') ?>"><i class="bi bi-buildings me-2"></i>Portal RH</a></li>
    <?php endif; ?>

    <?php if (user_has_perm('alerts.*')): ?>
    <li><a class="nav-link text-white d-flex justify-content-between align-items-center <?= nav_active('alerts.php',$self) ?>" href="<?= base_url('alerts.php') ?>"><span><i class="bi bi-bell me-2"></i>Alertas</span><span class="badge bg-danger rounded-pill"><?= $badge_alerts ?></span></a></li>
    <?php endif; ?>

    <?php if (user_has_perm('reports.*')): ?>
    <li><a class="nav-link text-white <?= nav_active('reports.php',$self) ?>" href="<?= base_url('reports.php') ?>"><i class="bi bi-graph-up me-2"></i>Relatórios</a></li>
    <?php endif; ?>

    <?php if (user_has_perm('users.view')): ?>
    <li><a class="nav-link text-white <?= nav_active('users.php',$self) ?>" href="<?= base_url('users.php') ?>"><i class="bi bi-person-gear me-2"></i>Usuários & Acessos</a></li>
    <?php endif; ?>

    <?php if (user_has_perm('logs.view')): ?>
    <li><a class="nav-link text-white <?= nav_active('access_logs.php',$self) ?>" href="<?= base_url('access_logs.php') ?>"><i class="bi bi-journal-text me-2"></i>Logs de acesso</a></li>
    <?php endif; ?>
  </ul>

  <hr class="border-secondary">
  <div>
    <div class="small opacity-75">Logado como</div>
    <div class="fw-semibold"><?= h(current_user()['name'] ?? '') ?> <span class="text-muted">(<?= h(current_user()['role'] ?? '') ?>)</span></div>
    <a href="<?= base_url('logout.php') ?>" class="btn btn-outline-light btn-sm mt-2"><i class="bi bi-box-arrow-right me-1"></i>Sair</a>
  </div>
</nav>
<main class="flex-grow-1 p-4">

