<?php include __DIR__ . '/includes/header.php';
$employeesCount = count_table('employees');
$departmentsCount = count_table('departments');
$leavesCount = count_table('leaves_requests');
$periodsCount = count_table('payroll_periods');
$pendingLeaves = (int) db()->query("SELECT COUNT(*) c FROM leaves_requests WHERE status = 'Pendiente'")->fetch()['c'];
$approvedLeaves = (int) db()->query("SELECT COUNT(*) c FROM leaves_requests WHERE status = 'Aprobado'")->fetch()['c'];
$activeEmployees = (int) db()->query("SELECT COUNT(*) c FROM employees WHERE status = 'active'")->fetch()['c'];
$currentPayroll = db()->query("SELECT COALESCE(SUM(net_pay),0) total FROM payroll_items")->fetch()['total'] ?? 0;
$openVacancies = (int) db()->query("SELECT COUNT(*) c FROM recruitment_vacancies WHERE status = 'Abierta'")->fetch()['c'];
$candidatesCount = count_table('recruitment_candidates');
$pendingApplications = (int) db()->query("SELECT COUNT(*) c FROM recruitment_applications WHERE stage IN ('Postulado','Entrevista')")->fetch()['c'];
?>
<div class="kpi-grid mb-4">
  <div class="card card-stat"><div class="card-body"><div class="metric-label">Empleados registrados</div><div class="metric-value"><?= $employeesCount ?></div><div class="metric-note">Activos: <?= $activeEmployees ?></div></div></div>
  <div class="card card-stat"><div class="card-body"><div class="metric-label">Permisos cargados</div><div class="metric-value"><?= $leavesCount ?></div><div class="metric-note">Pendientes: <?= $pendingLeaves ?></div></div></div>
  <div class="card card-stat"><div class="card-body"><div class="metric-label">Pago neto acumulado</div><div class="metric-value"><?= money_gs($currentPayroll) ?></div><div class="metric-note">Períodos: <?= $periodsCount ?></div></div></div>
  <div class="card card-stat"><div class="card-body"><div class="metric-label">Vacantes abiertas</div><div class="metric-value"><?= $openVacancies ?></div><div class="metric-note">Candidatos: <?= $candidatesCount ?></div></div></div>
</div>
<div class="info-card mb-4">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
    <div><h5 class="mb-1">Acciones rápidas</h5><div class="text-muted">Atajos para la operación diaria del sistema.</div></div>
    <div class="d-flex flex-wrap gap-2 quick-actions">
      <?php if (can_manage_master_data()): ?><a class="btn btn-primary rounded-4" href="<?= e(base_url('employees/create.php')) ?>">Nuevo empleado</a><?php endif; ?>
      <a class="btn btn-outline-primary rounded-4" href="<?= e(base_url('attendance/create.php')) ?>">Nueva asistencia</a>
      <a class="btn btn-outline-primary rounded-4" href="<?= e(base_url('leaves/create.php')) ?>">Nueva solicitud</a>
      <a class="btn btn-outline-primary rounded-4" href="<?= e(base_url('recruitment/index.php')) ?>">Reclutamiento</a>
      <?php if (can_manage_payroll()): ?><a class="btn btn-outline-primary rounded-4" href="<?= e(base_url('payroll/create.php')) ?>">Nuevo período</a><?php endif; ?>
      <a class="btn btn-outline-primary rounded-4" href="<?= e(base_url('reports/index.php')) ?>">Ver reportes</a>
    </div>
  </div>
</div>
<div class="row g-3">
  <div class="col-lg-4"><div class="info-card h-100"><h5>Ficha comercial</h5><ul class="list-clean"><li>Empresa: <strong><?= e(setting('company_name', 'HM Servicios Informáticos')) ?></strong></li><li>RUC: <strong><?= e(setting('company_ruc', '-')) ?></strong></li><li>Teléfono: <strong><?= e(setting('company_phone', '-')) ?></strong></li><li>Correo: <strong><?= e(setting('company_email', '-')) ?></strong></li></ul><?php if (can_manage_master_data()): ?><div class="mt-3"><a class="btn btn-sm btn-outline-primary rounded-4" href="<?= e(base_url('settings/index.php')) ?>">Editar datos</a></div><?php endif; ?></div></div>
  <div class="col-lg-4"><div class="info-card h-100"><h5>Alertas de RRHH</h5><ul class="list-clean"><li>Solicitudes pendientes: <strong><?= $pendingLeaves ?></strong></li><li>Solicitudes aprobadas: <strong><?= $approvedLeaves ?></strong></li><li>Empleados activos: <strong><?= $activeEmployees ?></strong></li><li>Procesos de selección activos: <strong><?= $pendingApplications ?></strong></li></ul></div></div>
  <div class="col-lg-4"><div class="info-card h-100"><h5>Lo nuevo en v5</h5><ul class="list-clean"><li>Módulo de reclutamiento</li><li>Exportación real XLSX</li><li>Vacaciones con saldo acumulado</li><li>Control de aprobación con validación de saldo</li></ul></div></div>
</div>
<div class="row g-3 mt-1">
  <div class="col-lg-7"><div class="table-wrap h-100"><div class="d-flex justify-content-between align-items-center mb-3"><h5 class="mb-0">Últimos empleados</h5><a class="btn btn-sm btn-outline-primary rounded-4" href="<?= e(base_url('employees/index.php')) ?>">Ver todos</a></div><div class="table-responsive"><table class="table table-sm align-middle"><thead><tr><th>Nombre</th><th>Cédula</th><th>Ingreso</th><th>Vacaciones</th><th>Estado</th></tr></thead><tbody><?php foreach (db()->query("SELECT id, full_name, document_number, hire_date, status FROM employees ORDER BY id DESC LIMIT 6") as $row): $vac = vacation_balance($row); ?><tr><td><?= e($row['full_name']) ?></td><td><?= e($row['document_number']) ?></td><td><?= e($row['hire_date']) ?></td><td><?= e($vac['pending']) ?> días</td><td><span class="badge text-bg-<?= e(status_badge_class($row['status'])) ?>"><?= e($row['status']) ?></span></td></tr><?php endforeach; ?></tbody></table></div></div></div>
  <div class="col-lg-5"><div class="table-wrap h-100"><div class="d-flex justify-content-between align-items-center mb-3"><h5 class="mb-0">Últimos procesos</h5><a class="btn btn-sm btn-outline-primary rounded-4" href="<?= e(base_url('recruitment/index.php')) ?>">Gestionar</a></div><div class="table-responsive"><table class="table table-sm align-middle"><thead><tr><th>Candidato</th><th>Vacante</th><th>Etapa</th><th>Fecha</th></tr></thead><tbody><?php $stmt = db()->query("SELECT c.full_name, v.title, a.stage, a.applied_at FROM recruitment_applications a JOIN recruitment_candidates c ON c.id=a.candidate_id JOIN recruitment_vacancies v ON v.id=a.vacancy_id ORDER BY a.id DESC LIMIT 6"); foreach ($stmt as $row): ?><tr><td><?= e($row['full_name']) ?></td><td><?= e($row['title']) ?></td><td><?= e($row['stage']) ?></td><td><?= e($row['applied_at']) ?></td></tr><?php endforeach; ?></tbody></table></div></div></div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>