<?php
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/flash.php';
requireRol(ROL_GESTOR_PPP);
$user = currentUser(); $db = getDB(); $pageTitle = 'Calificaciones — Gestor PPP';

$cfg        = getAllConfig();
$notaMinima = (float)($cfg['nota_minima_aprobacion'] ?? 60);
$horasMin   = (int)($cfg['horas_minimas_ppp'] ?? 240);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id   = (int)($_POST['id_practica'] ?? 0);
    $nBit = min(100, max(0, (float)str_replace(',','.',($_POST['nota_bitacoras']       ?? 0))));
    $nInf = min(100, max(0, (float)str_replace(',','.',($_POST['nota_informe']         ?? 0))));
    $nEmp = min(100, max(0, (float)str_replace(',','.',($_POST['nota_tutor_empresa']   ?? 0))));
    $nTut = min(100, max(0, (float)str_replace(',','.',($_POST['nota_tutor_academico'] ?? 0))));
    $obs  = trim($_POST['observaciones_gestor'] ?? '');
    $nFin = round($nBit*0.20 + $nInf*0.25 + $nEmp*0.30 + $nTut*0.25, 2);

    $db->prepare("UPDATE practicas SET nota_bitacoras=:nb, nota_informe=:ni, nota_tutor_empresa=:ne, nota_tutor_academico=:nt, nota_final=:nf, observaciones_gestor=:obs, calificado_por=:uid, fecha_calificacion=CURDATE(), estado='calificado' WHERE id_practica=:id")
       ->execute([':nb'=>$nBit,':ni'=>$nInf,':ne'=>$nEmp,':nt'=>$nTut,':nf'=>$nFin,':obs'=>$obs,':uid'=>$user['id'],':id'=>$id]);

    registrarAudit($user['id'], 'calificar_practica', 'practicas');
    flashSet('ok', "Nota final: {$nFin}/100 — ".($nFin>=$notaMinima?'APROBADO':'REPROBADO'));
    header("Location: calificaciones.php?id=$id"); exit;
}

$idPractica = (int)($_GET['id'] ?? 0);
$practica   = null;
if ($idPractica) {
    $st = $db->prepare("SELECT p.*, CONCAT(u.apellidos,' ',u.nombres) AS estudiante, u.email AS estudiante_email, u.cedula, c.nombre AS carrera, em.razon_social AS empresa, pa.nombre AS periodo, CONCAT(ut.nombres,' ',ut.apellidos) AS tutor_nombre, (SELECT COUNT(*) FROM bitacoras b WHERE b.id_practica=p.id_practica AND b.estado='validada') AS bit_validadas, (SELECT COUNT(*) FROM bitacoras b WHERE b.id_practica=p.id_practica) AS bit_total, (SELECT COALESCE(SUM(horas_semana),0) FROM bitacoras b WHERE b.id_practica=p.id_practica AND b.estado='validada') AS horas_validadas 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 JOIN periodos_academicos pa ON pa.id_periodo=p.id_periodo LEFT JOIN tutores t ON t.id_tutor=p.id_tutor LEFT JOIN usuarios ut ON ut.id_usuario=t.id_usuario WHERE p.id_practica=:id");
    $st->execute([':id'=>$idPractica]);
    $practica = $st->fetch();
}

$pendientes = $db->query("SELECT p.id_practica, p.estado, p.nota_final, CONCAT(u.apellidos,' ',u.nombres) AS estudiante, em.razon_social AS empresa, c.nombre AS carrera 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.estado IN ('informe_enviado','en_progreso','calificado','completado') ORDER BY (p.nota_final IS NULL) DESC, p.updated_at DESC")->fetchAll();
?>
<!DOCTYPE html><html lang="es">
<head><?php include __DIR__ . '/../../includes/head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-gestor-ppp.css">
</head>
<body><?php include __DIR__ . '/../../includes/navbar.php'; ?>
<div class="app-shell">
  <aside class="sidebar">
    <div class="sidebar-label">Gestor PPP</div>
    <a href="dashboard.php"><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="practicas.php"><span class="icon"><i class="fa fa-briefcase"></i></span> Prácticas</a>
      <a href="bitacoras.php"><span class="icon"><i class="fa fa-book-open"></i></span> Bitácoras</a>
    </div>

    <div class="sidebar-group g-evaluacion">
      <span class="sg-label"><i class="fa fa-star me-1"></i>Evaluación</span>
      <a href="calificaciones.php" class="active"><span class="icon"><i class="fa fa-star"></i></span> Calificaciones</a>
    </div>

    <div class="sidebar-group g-reportes">
      <span class="sg-label"><i class="fa fa-chart-bar me-1"></i>Reportes</span>
      <a href="reportes.php"><span class="icon"><i class="fa fa-chart-bar"></i></span> Reportes</a>
      <a href="reporte_ces.php"><span class="icon"><i class="fa fa-file-contract"></i></span> Reporte CES</a>
    </div>

    <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">
    <?= flashHtml() ?>
    <div class="page-header">
      <h4><i class="fa fa-star me-2" style="color:#f59e0b;"></i>Calificaciones PPP</h4>
      <p>Bitácoras <strong>20</strong> · Informe <strong>25</strong> · Empresa <strong>30</strong> · Tutor <strong>25</strong> — Total: <strong>100 pts</strong> · Mínimo: <strong style="color:var(--green);"><?= $notaMinima ?>/100</strong></p>
    </div>
    <div class="row g-3">
      <div class="col-lg-4">
        <div class="tbl-wrap p-0" style="max-height:75vh;overflow-y:auto;">
          <?php if(empty($pendientes)): ?>
          <div class="p-4 text-center text-muted">Sin prácticas</div>
          <?php else: foreach($pendientes as $p): $activo=$idPractica==$p['id_practica']; $ap=$p['nota_final']!==null&&$p['nota_final']>=$notaMinima; ?>
          <a href="calificaciones.php?id=<?= $p['id_practica'] ?>" style="display:block;padding:12px 16px;border-bottom:1px solid var(--border);text-decoration:none;background:<?= $activo?'var(--card-alt)':'transparent' ?>;border-left:3px solid <?= $activo?'#ec4899':'transparent' ?>;">
            <div style="font-size:12px;font-weight:700;color:var(--text);"><?= htmlspecialchars($p['estudiante']) ?></div>
            <div style="font-size:11px;color:var(--text-2);"><?= htmlspecialchars($p['empresa']) ?></div>
            <div class="d-flex justify-content-between align-items-center mt-1">
              <?= badgeEstado($p['estado']) ?>
              <?php if($p['nota_final']!==null): ?><span style="font-size:14px;font-weight:800;color:<?= $ap?'var(--green)':'var(--red)' ?>;"><?= number_format($p['nota_final'],2) ?>/100</span>
              <?php else: ?><span style="font-size:10px;color:#ec4899;font-weight:700;">SIN NOTA</span><?php endif; ?>
            </div>
          </a>
          <?php endforeach; endif; ?>
        </div>
      </div>
      <div class="col-lg-8">
        <?php if(!$practica): ?>
        <div class="tbl-wrap p-5 text-center" style="color:var(--text-2);"><div style="font-size:48px;margin-bottom:16px;">👈</div><div>Selecciona un estudiante</div></div>
        <?php else: $nota=$practica['nota_final']; $aprueba=$nota!==null&&$nota>=$notaMinima; ?>
        <div class="tbl-wrap p-3 mb-3" style="border-left:4px solid #ec4899;">
          <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
            <div>
              <div style="font-size:16px;font-weight:800;"><?= htmlspecialchars($practica['estudiante']) ?></div>
              <div style="font-size:12px;color:var(--text-2);"><?= htmlspecialchars($practica['carrera']) ?> · <?= htmlspecialchars($practica['empresa']) ?></div>
              <div style="font-size:11px;color:var(--text-2);margin-top:4px;">
                📓 <?= $practica['bit_validadas'] ?>/<?= $practica['bit_total'] ?> bitácoras · ⏱️ <?= $practica['horas_validadas'] ?>/<?= $horasMin ?>h
              </div>
            </div>
            <?php if($nota!==null): ?>
            <div style="text-align:center;">
              <div style="font-size:28px;font-weight:900;color:<?= $aprueba?'var(--green)':'var(--red)' ?>;"><?= number_format($nota,2) ?>/100</div>
              <div style="font-size:11px;font-weight:700;color:<?= $aprueba?'var(--green)':'var(--red)' ?>;"><?= $aprueba?'✅ APROBADO':'❌ REPROBADO' ?></div>
            </div>
            <?php endif; ?>
          </div>
        </div>
        <form method="POST" id="formCalif">
          <input type="hidden" name="id_practica" value="<?= $practica['id_practica'] ?>">
          <div class="tbl-wrap p-4 mb-3">
            <div style="font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--text-2);margin-bottom:16px;">Rúbrica — escala 0 a 100 puntos por componente</div>
            <div class="row g-3">
              <?php foreach([
                ['nota_bitacoras','Bitácoras semanales','20 pts · 20%','#4fc3f7','📓',20],
                ['nota_informe','Informe final CES','25 pts · 25%','#ab47bc','📄',25],
                ['nota_tutor_empresa','Evaluación empresa','30 pts · 30%','#ff7043','🏢',30],
                ['nota_tutor_academico','Evaluación tutor académico','25 pts · 25%','#66bb6a','👨‍🏫',25],
              ] as [$campo,$label,$peso,$color,$icon,$pct]): $val=$practica[$campo]??''; ?>
              <div class="col-sm-6">
                <div style="background:var(--card-alt);border-radius:var(--r-lg);padding:14px;border-top:3px solid <?= $color ?>;">
                  <label style="font-size:11px;font-weight:700;color:var(--text-2);text-transform:uppercase;letter-spacing:.5px;"><?= $icon ?> <?= $label ?> <span style="color:<?= $color ?>;">(<?= $peso ?>)</span></label>
                  <input type="number" name="<?= $campo ?>" class="form-control nota-input mt-2" data-peso="<?= $pct ?>" min="0" max="100" step="0.5" value="<?= htmlspecialchars($val) ?>" placeholder="0 – 100" style="font-size:22px;font-weight:800;text-align:center;background:var(--card);border-color:<?= $color ?>44;color:<?= $color ?>;height:60px;">
                  <div style="font-size:10px;color:var(--text-2);text-align:right;margin-top:4px;">Aporta: <span class="val-aport" style="font-weight:700;color:<?= $color ?>;">—</span> pts</div>
                </div>
              </div>
              <?php endforeach; ?>
            </div>
            <div class="mt-4 p-3" style="background:var(--card);border-radius:var(--r-lg);border:2px solid var(--border);">
              <div class="d-flex justify-content-between align-items-center">
                <div><div style="font-size:11px;color:var(--text-2);text-transform:uppercase;">Nota final calculada</div><div style="font-size:10px;color:var(--text-2);">Bit×20% + Inf×25% + Emp×30% + Tut×25%</div></div>
                <div><span id="notaPreview" style="font-size:42px;font-weight:900;color:var(--accent);">—</span><span style="font-size:16px;color:var(--text-2);">/100</span></div>
              </div>
              <div style="margin-top:10px;background:var(--border);border-radius:6px;height:10px;overflow:hidden;"><div id="barraPreview" style="height:10px;border-radius:6px;background:var(--accent);width:0%;transition:width .3s;"></div></div>
              <div id="estadoPreview" style="font-size:13px;font-weight:700;margin-top:8px;text-align:right;"></div>
            </div>
            <div class="mt-3">
              <label class="form-label">Observaciones para el estudiante (opcional)</label>
              <textarea name="observaciones_gestor" class="form-control" rows="3" placeholder="Comentarios visibles al estudiante..."><?= htmlspecialchars($practica['observaciones_gestor']??'') ?></textarea>
            </div>
          </div>
          <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary"><i class="fa fa-save me-2"></i>Guardar calificación</button>
            <a href="practicas.php" class="btn btn-outline-secondary">Cancelar</a>
          </div>
        </form>
        <?php endif; ?>
      </div>
    </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 ?>'; var NOTA_MIN=<?= $notaMinima ?>;
$(function(){
  var pesos=[20,25,30,25];
  function calc(){
    var tot=0,ok=true;
    $('.nota-input').each(function(i){
      var v=parseFloat($(this).val());
      var a=isNaN(v)?'—':(v*pesos[i]/100).toFixed(2);
      $(this).closest('.col-sm-6').find('.val-aport').text(a);
      if(isNaN(v)){ok=false;return;} tot+=v*pesos[i]/100;
    });
    if(!ok){$('#notaPreview').text('—').css('color','var(--accent)');$('#barraPreview').css('width','0%');$('#estadoPreview').text('');return;}
    tot=Math.round(tot*100)/100;
    var c=tot>=NOTA_MIN?'var(--green)':'var(--red)';
    $('#notaPreview').text(tot.toFixed(2)).css('color',c);
    $('#barraPreview').css({'width':tot+'%','background':c});
    $('#estadoPreview').text((tot>=NOTA_MIN?'✅ APROBADO':'❌ REPROBADO')+' (mín. '+NOTA_MIN+'/100)').css('color',c);
  }
  $('.nota-input').on('input',calc); calc();
});
</script>
</body></html>
