<?php
// auth/cambiar_password.php — con layout de módulo según rol
require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/flash.php';
requireLogin();

$user  = currentUser();
$db    = getDB();
$error = '';
$pageTitle = 'Cambiar Contraseña';

// ── Procesar formulario ──────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $actual = $_POST['actual']  ?? '';
    $nueva  = $_POST['nueva']   ?? '';
    $repite = $_POST['repite']  ?? '';

    $st = $db->prepare("SELECT password_hash FROM usuarios WHERE id_usuario = :id");
    $st->execute([':id' => $user['id']]);
    $row = $st->fetch();

    if (!password_verify($actual, $row['password_hash'])) {
        $error = 'La contraseña actual es incorrecta.';
    } elseif (strlen($nueva) < 8) {
        $error = 'La nueva contraseña debe tener al menos 8 caracteres.';
    } elseif ($nueva !== $repite) {
        $error = 'Las contraseñas nuevas no coinciden.';
    } else {
        $db->prepare("UPDATE usuarios SET password_hash = :h, cambiar_password = 0 WHERE id_usuario = :id")
           ->execute([':h' => password_hash($nueva, PASSWORD_BCRYPT), ':id' => $user['id']]);
        registrarAudit($user['id'], 'cambio_password', 'usuarios', $user['id']);
        flashSet('ok', 'Contraseña actualizada correctamente.');
        header('Location: ' . (ROL_REDIRECT[$user['id_rol']] ?? BASE_URL . '/auth/login.php'));
        exit;
    }
}

// ── Detectar CSS y label de sidebar según rol ────────────────
$rol = (int)$user['id_rol'];

// Mapa: rol → [css, label, links del sidebar]
$sidebarMap = [
    ROL_ADMIN => [
        'css'   => 'sidebar-admin.css',
        'label' => 'Administración',
        'home'  => BASE_URL . '/modules/admin/dashboard.php',
        'links' => [
            ['icon'=>'fa-gauge',        'url'=>'dashboard.php',                  'label'=>'Dashboard',          'rel'=>true],
            ['group'=>'g-gestion', 'glabel'=>'Académico', 'gicon'=>'fa-graduation-cap', 'items'=>[
                ['icon'=>'fa-users',         'url'=>'usuarios.php',     'label'=>'Usuarios'],
                ['icon'=>'fa-graduation-cap','url'=>'carreras.php',     'label'=>'Carreras'],
                ['icon'=>'fa-calendar',      'url'=>'periodos.php',     'label'=>'Períodos'],
            ]],
            ['group'=>'g-empresas','glabel'=>'Empresas','gicon'=>'fa-building','items'=>[
                ['icon'=>'fa-building',  'url'=>'empresas.php',  'label'=>'Empresas'],
                ['icon'=>'fa-handshake', 'url'=>'convenios.php', 'label'=>'Convenios'],
            ]],
            ['group'=>'g-sistema','glabel'=>'Sistema','gicon'=>'fa-gear','items'=>[
                ['icon'=>'fa-file-import',   'url'=>'migrar_estudiantes.php','label'=>'Migrar Estudiantes'],
                ['icon'=>'fa-shield-halved', 'url'=>'audit.php',             'label'=>'Audit Log'],
                ['icon'=>'fa-gear',          'url'=>'configuracion.php',     'label'=>'Configuración'],
            ]],
            ['group'=>'g-cuenta','glabel'=>'Cuenta','gicon'=>'fa-user','items'=>[
                ['icon'=>'fa-lock', 'url'=>BASE_URL.'/auth/cambiar_password.php','label'=>'Contraseña','active'=>true,'abs'=>true],
            ]],
        ],
    ],
    ROL_COORDINADOR => [
        'css'   => 'sidebar-grupos.css',
        'label' => 'Coordinador',
        'home'  => BASE_URL . '/modules/coordinador/dashboard.php',
        'links' => [
            ['icon'=>'fa-gauge','url'=>'dashboard.php','label'=>'Dashboard','rel'=>true],
            ['group'=>'g-practicas','glabel'=>'Prácticas PPP','gicon'=>'fa-briefcase','items'=>[
                ['icon'=>'fa-briefcase',    'url'=>'practicas.php',    'label'=>'Prácticas'],
                ['icon'=>'fa-inbox',        'url'=>'postulaciones.php','label'=>'Postulaciones'],
                ['icon'=>'fa-file-pdf',     'url'=>'fichas_ppp.php',   'label'=>'Fichas PPP'],
                ['icon'=>'fa-folder-open',  'url'=>'expedientes.php',  'label'=>'Expedientes PPP'],
                ['icon'=>'fa-book-open',    'url'=>'bitacoras.php',    'label'=>'Bitácoras'],
            ]],
            ['group'=>'g-vinculacion','glabel'=>'Vinculación','gicon'=>'fa-handshake','items'=>[
                ['icon'=>'fa-handshake','url'=>'vinculacion.php','label'=>'Vinculación'],
            ]],
            ['group'=>'g-titulacion','glabel'=>'Titulación','gicon'=>'fa-graduation-cap','items'=>[
                ['icon'=>'fa-graduation-cap','url'=>'titulacion.php','label'=>'Titulación'],
            ]],
            ['group'=>'g-reportes','glabel'=>'Reportes','gicon'=>'fa-chart-bar','items'=>[
                ['icon'=>'fa-chart-bar','url'=>'reportes.php','label'=>'Reportes CES'],
            ]],
            ['group'=>'g-cuenta','glabel'=>'Cuenta','gicon'=>'fa-user','items'=>[
                ['icon'=>'fa-lock','url'=>BASE_URL.'/auth/cambiar_password.php','label'=>'Contraseña','active'=>true,'abs'=>true],
            ]],
        ],
    ],
    ROL_TUTOR => [
        'css'   => 'sidebar-tutor.css',
        'label' => 'Tutor Académico',
        'home'  => BASE_URL . '/modules/tutor/dashboard.php',
        'links' => [
            ['icon'=>'fa-gauge','url'=>'dashboard.php','label'=>'Dashboard','rel'=>true],
            ['group'=>'g-tutoria','glabel'=>'Tutoría','gicon'=>'fa-graduation-cap','items'=>[
                ['icon'=>'fa-users',    'url'=>'mis_estudiantes.php','label'=>'Mis Estudiantes'],
                ['icon'=>'fa-book-open','url'=>'bitacoras.php',      'label'=>'Validar Bitácoras'],
            ]],
            ['group'=>'g-evaluacion','glabel'=>'Evaluaciones','gicon'=>'fa-star','items'=>[
                ['icon'=>'fa-star','url'=>'evaluaciones.php','label'=>'Evaluaciones'],
            ]],
            ['group'=>'g-cuenta','glabel'=>'Cuenta','gicon'=>'fa-user','items'=>[
                ['icon'=>'fa-lock','url'=>BASE_URL.'/auth/cambiar_password.php','label'=>'Contraseña','active'=>true,'abs'=>true],
            ]],
        ],
    ],
    ROL_SECRETARIA => [
        'css'   => 'sidebar-secretaria.css',
        'label' => 'Secretaria',
        'home'  => BASE_URL . '/modules/secretaria/dashboard.php',
        'links' => [
            ['icon'=>'fa-gauge','url'=>'dashboard.php','label'=>'Dashboard','rel'=>true],
            ['group'=>'g-gestion','glabel'=>'Gestión','gicon'=>'fa-users','items'=>[
                ['icon'=>'fa-users',        'url'=>'dashboard.php',   'label'=>'Estudiantes'],
                ['icon'=>'fa-id-card',      'url'=>'certificados.php','label'=>'Certificados'],
                ['icon'=>'fa-file-lines',   'url'=>'informes.php',    'label'=>'Informes'],
            ]],
            ['group'=>'g-reportes','glabel'=>'Reportes','gicon'=>'fa-chart-bar','items'=>[
                ['icon'=>'fa-chart-bar','url'=>'reportes.php','label'=>'Reportes'],
            ]],
            ['group'=>'g-cuenta','glabel'=>'Cuenta','gicon'=>'fa-user','items'=>[
                ['icon'=>'fa-lock','url'=>BASE_URL.'/auth/cambiar_password.php','label'=>'Contraseña','active'=>true,'abs'=>true],
            ]],
        ],
    ],
    ROL_GESTOR_PPP => [
        'css'   => 'sidebar-gestor-ppp.css',
        'label' => 'Gestor PPP',
        'home'  => BASE_URL . '/modules/gestor_ppp/dashboard.php',
        'links' => [
            ['icon'=>'fa-gauge','url'=>'dashboard.php','label'=>'Dashboard','rel'=>true],
            ['group'=>'g-practicas','glabel'=>'Prácticas','gicon'=>'fa-briefcase','items'=>[
                ['icon'=>'fa-briefcase','url'=>'practicas.php','label'=>'Prácticas'],
                ['icon'=>'fa-book-open','url'=>'bitacoras.php','label'=>'Bitácoras'],
            ]],
            ['group'=>'g-evaluacion','glabel'=>'Evaluación','gicon'=>'fa-star','items'=>[
                ['icon'=>'fa-star','url'=>'calificaciones.php','label'=>'Calificaciones'],
            ]],
            ['group'=>'g-reportes','glabel'=>'Reportes','gicon'=>'fa-chart-bar','items'=>[
                ['icon'=>'fa-chart-bar',    'url'=>'reportes.php',   'label'=>'Reportes'],
                ['icon'=>'fa-file-contract','url'=>'reporte_ces.php','label'=>'Reporte CES'],
            ]],
            ['group'=>'g-cuenta','glabel'=>'Cuenta','gicon'=>'fa-user','items'=>[
                ['icon'=>'fa-lock','url'=>BASE_URL.'/auth/cambiar_password.php','label'=>'Contraseña','active'=>true,'abs'=>true],
            ]],
        ],
    ],
    ROL_TUTOR_EMPRESA => [
        'css'   => 'sidebar-tutor-empresa.css',
        'label' => 'Tutor Empresa',
        'home'  => BASE_URL . '/modules/tutor_empresa/dashboard.php',
        'links' => [
            ['icon'=>'fa-gauge','url'=>'dashboard.php','label'=>'Dashboard','rel'=>true],
            ['group'=>'g-practicas','glabel'=>'Prácticas','gicon'=>'fa-briefcase','items'=>[
                ['icon'=>'fa-users','url'=>'mis_estudiantes.php','label'=>'Mis Estudiantes'],
            ]],
            ['group'=>'g-calificacion','glabel'=>'Calificación','gicon'=>'fa-star','items'=>[
                ['icon'=>'fa-star','url'=>'calificacion.php','label'=>'Calificar'],
            ]],
            ['group'=>'g-cuenta','glabel'=>'Cuenta','gicon'=>'fa-user','items'=>[
                ['icon'=>'fa-lock','url'=>BASE_URL.'/auth/cambiar_password.php','label'=>'Contraseña','active'=>true,'abs'=>true],
            ]],
        ],
    ],
    ROL_AUDITOR => [
        'css'   => 'sidebar-auditor.css',
        'label' => 'Auditor',
        'home'  => BASE_URL . '/modules/auditor/dashboard.php',
        'links' => [
            ['icon'=>'fa-shield-halved','url'=>'dashboard.php','label'=>'Dashboard','rel'=>true],
            ['group'=>'g-auditoria','glabel'=>'Auditoría','gicon'=>'fa-shield-halved','items'=>[
                ['icon'=>'fa-list-check','url'=>'dashboard.php','label'=>'Audit Log'],
            ]],
            ['group'=>'g-reportes','glabel'=>'Reportes','gicon'=>'fa-chart-bar','items'=>[
                ['icon'=>'fa-chart-bar','url'=>'reportes.php','label'=>'Reportes'],
            ]],
            ['group'=>'g-cuenta','glabel'=>'Cuenta','gicon'=>'fa-user','items'=>[
                ['icon'=>'fa-lock','url'=>BASE_URL.'/auth/cambiar_password.php','label'=>'Contraseña','active'=>true,'abs'=>true],
            ]],
        ],
    ],
];

// Estudiante u otro rol sin sidebar → redirect al estilo anterior
if (!isset($sidebarMap[$rol])) {
    header('Location: ' . (ROL_REDIRECT[$rol] ?? BASE_URL . '/auth/login.php'));
    exit;
}

$sb = $sidebarMap[$rol];

// Helper para renderizar links del sidebar
function renderLinks(array $links, string $moduleBase, string $homeUrl): string {
    $html = '';
    foreach ($links as $link) {
        if (isset($link['group'])) {
            $html .= '<div class="sidebar-group ' . $link['group'] . '">';
            $html .= '<span class="sg-label"><i class="fa ' . $link['gicon'] . ' me-1"></i>' . $link['glabel'] . '</span>';
            foreach ($link['items'] as $item) {
                $url    = isset($item['abs']) ? $item['url'] : $moduleBase . '/' . $item['url'];
                $active = isset($item['active']) ? ' class="active"' : '';
                $html  .= '<a href="' . $url . '"' . $active . '><span class="icon"><i class="fa ' . $item['icon'] . '"></i></span> ' . $item['label'] . '</a>';
            }
            $html .= '</div>';
        } else {
            $url    = isset($link['rel']) ? $homeUrl : $link['url'];
            $html  .= '<a href="' . $url . '"><span class="icon"><i class="fa ' . $link['icon'] . '"></i></span> ' . $link['label'] . '</a>';
        }
    }
    return $html;
}

// Base URL del módulo para links relativos
$moduleBase = rtrim(ROL_REDIRECT[$rol] ?? '', '/dashboard.php');
$moduleBase = dirname(ROL_REDIRECT[$rol] ?? '');
?>
<!DOCTYPE html>
<html lang="es">
<head><?php include __DIR__ . '/../includes/head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/<?= $sb['css'] ?>">
</head>
<body>
<?php include __DIR__ . '/../includes/navbar.php'; ?>
<div class="app-shell">
  <aside class="sidebar">
    <div class="sidebar-label"><?= htmlspecialchars($sb['label']) ?></div>
    <?= renderLinks($sb['links'], $moduleBase, $sb['home']) ?>
    <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><i class="fa fa-lock me-2" style="color:#2ea8ff;"></i>Cambiar Contraseña</h4>
      <p>Actualiza tu contraseña de acceso al sistema</p>
    </div>

    <?php if ($error): ?>
    <div class="alert-dark-danger p-3 mb-4">
      <i class="fa fa-circle-exclamation me-2"></i><?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <?= flashHtml() ?>

    <div class="row justify-content-center">
      <div class="col-12 col-md-6 col-lg-5">
        <div class="tbl-wrap p-4">

          <!-- Info del usuario -->
          <div class="d-flex align-items-center gap-3 mb-4 pb-3" style="border-bottom:1px solid var(--border);">
            <div style="width:48px;height:48px;border-radius:50%;background:linear-gradient(135deg,#2ea8ff,#c792ea);display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:700;color:#fff;flex-shrink:0;">
              <?= mb_strtoupper(mb_substr($user['nombre'], 0, 1)) ?>
            </div>
            <div>
              <div style="font-weight:600;font-size:14px;"><?= htmlspecialchars($user['nombre']) ?></div>
              <div style="font-size:12px;color:var(--text-2);"><?= htmlspecialchars($user['email'] ?? '') ?></div>
              <div style="font-size:11px;color:#3dffa0;margin-top:2px;"><i class="fa fa-circle-dot fa-xs me-1"></i><?= htmlspecialchars($user['rol'] ?? '') ?></div>
            </div>
          </div>

          <form method="POST" id="formPass">
            <div class="mb-3">
              <label class="form-label">Contraseña actual</label>
              <div class="input-group">
                <input type="password" name="actual" id="inp-actual" class="form-control" required placeholder="Tu contraseña actual">
                <button type="button" class="btn btn-outline-secondary btn-toggle-pass" data-target="inp-actual">
                  <i class="fa fa-eye"></i>
                </button>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Nueva contraseña</label>
              <div class="input-group">
                <input type="password" name="nueva" id="inp-nueva" class="form-control" required minlength="8" placeholder="Mínimo 8 caracteres">
                <button type="button" class="btn btn-outline-secondary btn-toggle-pass" data-target="inp-nueva">
                  <i class="fa fa-eye"></i>
                </button>
              </div>
              <!-- Barra de fortaleza -->
              <div style="margin-top:6px;height:4px;border-radius:2px;background:var(--border);overflow:hidden;">
                <div id="strength-bar" style="height:4px;width:0%;border-radius:2px;transition:all .3s;"></div>
              </div>
              <div id="strength-label" style="font-size:10px;color:var(--text-2);margin-top:3px;"></div>
            </div>

            <div class="mb-4">
              <label class="form-label">Repetir nueva contraseña</label>
              <div class="input-group">
                <input type="password" name="repite" id="inp-repite" class="form-control" required minlength="8" placeholder="Repite la nueva contraseña">
                <button type="button" class="btn btn-outline-secondary btn-toggle-pass" data-target="inp-repite">
                  <i class="fa fa-eye"></i>
                </button>
              </div>
              <div id="match-label" style="font-size:11px;margin-top:4px;"></div>
            </div>

            <div class="d-flex gap-2">
              <button type="submit" class="btn btn-primary flex-fill" id="btn-guardar">
                <i class="fa fa-floppy-disk me-2"></i>Guardar contraseña
              </button>
              <a href="<?= ROL_REDIRECT[$rol] ?? BASE_URL ?>" class="btn btn-outline-secondary">
                Cancelar
              </a>
            </div>
          </form>

          <div class="mt-4 p-3" style="background:rgba(46,168,255,.06);border:1px solid rgba(46,168,255,.15);border-radius:8px;font-size:12px;color:var(--text-2);">
            <i class="fa fa-circle-info me-2" style="color:#2ea8ff;"></i>
            <strong>Requisitos:</strong> mínimo 8 caracteres. Usa letras, números y símbolos para mayor seguridad.
          </div>

        </div>
      </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>
$(function () {

  // Toggle mostrar/ocultar contraseña
  $(document).on('click', '.btn-toggle-pass', function () {
    var target = $('#' + $(this).data('target'));
    var isPass = target.attr('type') === 'password';
    target.attr('type', isPass ? 'text' : 'password');
    $(this).find('i').toggleClass('fa-eye fa-eye-slash');
  });

  // Barra de fortaleza
  $('#inp-nueva').on('input', function () {
    var v = $(this).val();
    var score = 0;
    if (v.length >= 8)  score++;
    if (v.length >= 12) score++;
    if (/[A-Z]/.test(v)) score++;
    if (/[0-9]/.test(v)) score++;
    if (/[^A-Za-z0-9]/.test(v)) score++;

    var colors  = ['#ff4444','#ff4444','#f7b93e','#2ea8ff','#3dffa0','#3dffa0'];
    var labels  = ['','Muy débil','Débil','Aceptable','Fuerte','Muy fuerte'];
    var pct     = [0, 20, 40, 60, 80, 100];

    $('#strength-bar').css({ width: pct[score] + '%', background: colors[score] });
    $('#strength-label').text(labels[score]).css('color', colors[score]);
    checkMatch();
  });

  // Verificar coincidencia
  function checkMatch() {
    var n = $('#inp-nueva').val();
    var r = $('#inp-repite').val();
    if (!r) { $('#match-label').text(''); return; }
    if (n === r) {
      $('#match-label').html('<i class="fa fa-check me-1" style="color:#3dffa0;"></i><span style="color:#3dffa0;">Las contraseñas coinciden</span>');
    } else {
      $('#match-label').html('<i class="fa fa-xmark me-1" style="color:#ff4444;"></i><span style="color:#ff4444;">No coinciden</span>');
    }
  }
  $('#inp-repite').on('input', checkMatch);

  // Prevenir envío si no coinciden
  $('#formPass').on('submit', function (e) {
    var n = $('#inp-nueva').val();
    var r = $('#inp-repite').val();
    if (n !== r) {
      e.preventDefault();
      alert('Las contraseñas no coinciden. Verifícalas antes de guardar.');
    }
  });

});
</script>
</body>
</html>
