<?php
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';
requireRol([ROL_TUTOR_EMPRESA, ROL_ADMIN]);

$user = currentUser(); $db = getDB(); $pageTitle = 'Dashboard Tutor Empresa';

// Tutor empresa asociado
$te = $db->prepare("SELECT te.id, te.id_empresa, te.cargo, em.razon_social FROM tutores_empresa te JOIN empresas em ON em.id_empresa=te.id_empresa WHERE te.id_usuario=:uid AND te.activo=1");
$te->execute([':uid'=>$user['id']]);
$empresas       = $te->fetchAll();
$idTutorEmpresa = (int)($empresas[0]['id'] ?? 0);

$stats = ['total'=>0,'en_progreso'=>0,'sin_calificar'=>0,'calificados'=>0];
$practicas = [];

if ($idTutorEmpresa) {
    $st = $db->prepare("
        SELECT COUNT(*) AS total,
               SUM(p.estado='en_progreso') AS en_progreso,
               SUM(p.nota_empresa_100 IS NULL AND p.estado IN ('en_progreso','informe_enviado','calificado')) AS sin_calificar,
               SUM(p.nota_empresa_100 IS NOT NULL) AS calificados
        FROM practicas p WHERE p.id_tutor_empresa = :tid
    ");
    $st->execute([':tid' => $idTutorEmpresa]);
    $stats = $st->fetch();

    $stPr = $db->prepare("
        SELECT p.id_practica, p.estado, p.nota_empresa_100, p.horas_cumplidas, p.horas_requeridas,
               CONCAT(u.apellidos,' ',u.nombres) AS estudiante,
               c.nombre AS carrera, em.razon_social AS empresa
        FROM practicas p
        JOIN estudiantes est ON est.id_estudiante=p.id_estudiante
        JOIN usuarios u      ON u.id_usuario=est.id_usuario
        JOIN carreras c      ON c.id_carrera=est.id_carrera
        JOIN empresas em     ON em.id_empresa=p.id_empresa
        WHERE p.id_tutor_empresa = :tid
          AND p.estado IN ('aprobado','en_progreso','informe_enviado','calificado','completado')
        ORDER BY p.updated_at DESC LIMIT 10
    ");
    $stPr->execute([':tid' => $idTutorEmpresa]);
    $practicas = $stPr->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="es">
<head><?php include __DIR__ . '/../../includes/head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar.css">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-tutor-empresa.css">
</head>
<body>
<?php include __DIR__ . '/../../includes/navbar.php'; ?>
<div class="app-shell">
  <aside class="sidebar">
    <div class="sidebar-label">Tutor Empresa</div>
    <a href="dashboard.php" class="active"><span class="icon"><i class="fa fa-gauge"></i></span> Dashboard</a>

    <div class="sidebar-group g-practicas">
      <span class="sg-label"><i class="fa fa-briefcase me-1"></i>Prácticas</span>
      <a href="mis_estudiantes.php"><span class="icon"><i class="fa fa-users"></i></span> Mis Estudiantes</a>
      <a href="bitacoras.php"><span class="icon"><i class="fa fa-book-open"></i></span> Bitácoras</a>
    </div>


    <!-- Calificación — Ámbar -->
    <div class="sidebar-group g-calificacion">
      <span class="sg-label"><i class="fa fa-star me-1"></i>Calificación</span>
      <a href="calificacion.php"><span class="icon"><i class="fa fa-star"></i></span> Calificar
        <?php if($stats['sin_calificar']>0): ?>
          <span class="badge rounded-pill ms-auto" style="background:#ec4899;color:#fff;font-size:10px;"><?= $stats['sin_calificar'] ?></span>
        <?php endif; ?>
      </a>
    </div>

    <!-- Cuenta — Neutro -->
    <div class="sidebar-group g-cuenta">
      <span class="sg-label"><i class="fa fa-user me-1"></i>Cuenta</span>
      <a href="<?= BASE_URL ?>/auth/cambiar_password.php"><span class="icon"><i class="fa fa-lock"></i></span> Contraseña</a>
    </div>

    <div class="sidebar-sep"></div>
    <a href="<?= BASE_URL ?>/auth/logout.php"><span class="icon"><i class="fa fa-right-from-bracket"></i></span> Salir</a>
  </aside>
  <main class="main-area">
    <div class="page-header">
      <h4>Bienvenido, <?= htmlspecialchars($user['nombre']) ?> 🏢</h4>
      <p><?= implode(', ', array_column($empresas,'razon_social')) ?></p>
    </div>

    <div class="row g-3 mb-4">
      <div class="col-6 col-lg-3"><div class="stat-card"><div><div class="stat-num" style="color:var(--accent)"><?= $stats['total'] ?></div><div class="stat-label">Total practicantes</div></div><div class="stat-icon">👥</div></div></div>
      <div class="col-6 col-lg-3"><div class="stat-card"><div><div class="stat-num" style="color:var(--yellow)"><?= $stats['en_progreso'] ?></div><div class="stat-label">En progreso</div></div><div class="stat-icon">⚡</div></div></div>
      <div class="col-6 col-lg-3"><div class="stat-card"><div><div class="stat-num" style="color:#ec4899"><?= $stats['sin_calificar'] ?></div><div class="stat-label">Sin calificar</div></div><div class="stat-icon">📋</div></div></div>
      <div class="col-6 col-lg-3"><div class="stat-card"><div><div class="stat-num" style="color:var(--green)"><?= $stats['calificados'] ?></div><div class="stat-label">Calificados</div></div><div class="stat-icon">✅</div></div></div>
    </div>

    <?php if($stats['sin_calificar']>0): ?>
    <div class="alert-dark-warn p-3 mb-4">
      <i class="fa fa-triangle-exclamation me-2"></i>
      Tienes <strong><?= $stats['sin_calificar'] ?></strong> estudiante(s) pendiente(s) de calificación.
      <a href="calificacion.php" style="color:#f7b93e;font-weight:600;"> Calificar ahora →</a>
    </div>
    <?php endif; ?>

    <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--text-2);margin-bottom:10px;">Practicantes recientes</div>
    <div class="tbl-wrap">
      <table class="table table-borderless mb-0" style="font-size:13px;">
        <thead><tr><th>Estudiante</th><th>Carrera</th><th>Estado</th><th style="text-align:center;">Progreso horas</th><th style="text-align:center;">Mi nota (100)</th></tr></thead>
        <tbody>
          <?php if(empty($practicas)): ?>
          <tr><td colspan="5" class="text-center text-muted py-4">Sin practicantes activos</td></tr>
          <?php else: foreach($practicas as $r):
            $pct = $r['horas_requeridas']>0 ? min(100,round($r['horas_cumplidas']/$r['horas_requeridas']*100)) : 0;
            $pc  = $pct>=80?'var(--green)':($pct>=40?'var(--yellow)':'var(--red)');
          ?>
          <tr>
            <td><strong><?= htmlspecialchars($r['estudiante']) ?></strong></td>
            <td style="color:var(--text-2);font-size:12px;"><?= htmlspecialchars($r['carrera']) ?></td>
            <td><?= badgeEstado($r['estado']) ?></td>
            <td style="min-width:120px;">
              <div style="display:flex;align-items:center;gap:6px;">
                <div style="flex:1;background:var(--border);border-radius:3px;height:6px;">
                  <div style="width:<?= $pct ?>%;height:6px;border-radius:3px;background:<?= $pc ?>;"></div>
                </div>
                <span style="font-size:11px;color:<?= $pc ?>;"><?= $r['horas_cumplidas'] ?>/<?= $r['horas_requeridas'] ?>h</span>
              </div>
            </td>
            <td style="text-align:center;">
              <?php if($r['nota_empresa_100'] !== null): ?>
              <span style="font-size:18px;font-weight:800;color:<?= $r['nota_empresa_100']>=60?'var(--green)':'var(--red)' ?>;">
                <?= number_format($r['nota_empresa_100'],1) ?>
              </span>
              <span style="font-size:11px;color:var(--text-2);">/100</span>
              <?php else: ?>
              <a href="calificacion.php?id=<?= $r['id_practica'] ?>" style="font-size:11px;color:#ec4899;font-weight:700;">
                <i class="fa fa-star me-1"></i>Calificar
              </a>
              <?php endif; ?>
            </td>
          </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </main>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
<script>var BASE_URL='<?= BASE_URL ?>';</script>
<script src="<?= BASE_URL ?>/assets/js/sigvp.js"></script>
</body></html>