<?php
// modules/admin/cambiar_password.php
// ─────────────────────────────────────────────────────────────
// Versión del módulo Admin — incluye sidebar de administración.
// ─────────────────────────────────────────────────────────────
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_ADMIN);

$user = currentUser();
if (!$user) {
    header('Location: ' . BASE_URL . '/auth/login.php'); exit;
}

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

$errores = [];

// ── POST: procesar el cambio ──────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $actual    = $_POST['password_actual']    ?? '';
    $nueva     = $_POST['password_nueva']     ?? '';
    $confirmar = $_POST['password_confirmar'] ?? '';

    if (empty($actual)) {
        $errores[] = 'Ingresa tu contraseña actual.';
    }
    if (strlen($nueva) < 8) {
        $errores[] = 'La nueva contraseña debe tener al menos 8 caracteres.';
    }
    if ($nueva !== $confirmar) {
        $errores[] = 'La nueva contraseña y la confirmación no coinciden.';
    }

    if (empty($errores)) {
        $stUser = $db->prepare(
            "SELECT password_hash FROM usuarios WHERE id_usuario = :id LIMIT 1"
        );
        $stUser->execute([':id' => $user['id']]);
        $row = $stUser->fetch();

        if (!$row || !password_verify($actual, $row['password_hash'])) {
            $errores[] = 'La contraseña actual es incorrecta.';
        } else {
            $hash = password_hash($nueva, PASSWORD_DEFAULT);
            $db->prepare("
                UPDATE usuarios
                SET    password_hash    = :pwd,
                       cambiar_password = 0,
                       updated_at       = NOW()
                WHERE  id_usuario = :id
            ")->execute([':pwd' => $hash, ':id' => $user['id']]);

            flashSet('ok', '¡Contraseña actualizada correctamente!');
            header('Location: cambiar_password.php'); exit;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<?php include __DIR__ . '/../../includes/head.php'; ?>
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-admin.css">
<style>
.pw-wrap {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 16px;
  flex: 1;
}

.pw-card {
  background: #fff;
  border: 1px solid #e2e8f0;
  border-radius: 18px;
  padding: 2.5rem 2.75rem;
  width: 100%;
  max-width: 480px;
  box-shadow: 0 4px 24px rgba(0,0,0,.07);
}

/* Encabezado */
.pw-head {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 6px;
}
.pw-head h2 {
  font-size: 20px;
  font-weight: 800;
  color: #0f172a;
  margin: 0;
}
.pw-sub {
  font-size: 13px;
  color: #64748b;
  margin-bottom: 22px;
}

/* Chip de usuario */
.pw-user-chip {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 10px;
  padding: 10px 14px;
  margin-bottom: 24px;
}
.pw-user-chip .nombre  { font-size: 14px; font-weight: 700; color: #0f172a; flex: 1; }
.pw-user-chip .rol-tag {
  font-size: 10px; font-weight: 800; letter-spacing: .5px;
  text-transform: uppercase; background: #059669; color: #fff;
  border-radius: 20px; padding: 3px 10px;
}
.pw-user-chip .inst-tag {
  font-size: 11px; color: #64748b; background: #f1f5f9;
  border: 1px solid #e2e8f0; border-radius: 6px; padding: 2px 8px;
}

/* Campos */
.field-label { font-size: 12px; font-weight: 700; color: #475569; margin-bottom: 5px; display: block; }
.field-wrap  { position: relative; margin-bottom: 18px; }
.field-wrap input[type="password"],
.field-wrap input[type="text"] {
  width: 100%; border: 1.5px solid #e2e8f0; border-radius: 9px;
  padding: 10px 42px 10px 13px; font-size: 14px; color: #0f172a;
  background: #f8fafc; outline: none;
  transition: border-color .15s, box-shadow .15s; box-sizing: border-box;
}
.field-wrap input:focus {
  border-color: #059669; box-shadow: 0 0 0 3px rgba(5,150,105,.13); background: #fff;
}

/* Ojo */
.toggle-pwd {
  position: absolute; right: 11px; top: 50%; transform: translateY(-50%);
  background: none; border: none; cursor: pointer; color: #94a3b8;
  font-size: 14px; padding: 3px; transition: color .13s; line-height: 1;
}
.toggle-pwd:hover { color: #059669; }

/* Fortaleza */
.pwd-strength     { height: 4px; border-radius: 4px; margin-top: 7px; background: #e2e8f0; overflow: hidden; }
.pwd-strength-bar { height: 100%; border-radius: 4px; width: 0; transition: width .25s, background .25s; }
.pwd-strength-txt { font-size: 11px; margin-top: 4px; font-weight: 600; }
.match-msg        { font-size: 11px; margin-top: 4px; font-weight: 600; min-height: 16px; }

/* Botón */
.btn-guardar {
  background: #059669; color: #fff; border: none; border-radius: 9px;
  padding: 12px 28px; font-size: 14px; font-weight: 700; cursor: pointer;
  transition: background .15s; width: 100%; margin-top: 4px;
}
.btn-guardar:hover { background: #047857; }

/* Errores */
.err-list { background: #fef2f2; border: 1px solid #fecaca; border-radius: 10px; padding: 12px 16px; margin-bottom: 18px; }
.err-list li { font-size: 13px; color: #991b1b; list-style: none; padding: 2px 0; }
.err-list li::before { content: '⚠ '; }

/* Tips */
.tips { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 10px; padding: 12px 16px; margin-top: 18px; }
.tips li { font-size: 12px; color: #065f46; list-style: none; padding: 2px 0; }
.tips li::before { content: '✓ '; font-weight: 700; }

/* Volver */
.btn-volver {
  display: inline-flex; align-items: center; gap: 6px;
  font-size: 13px; color: #64748b; text-decoration: none;
  margin-top: 18px; transition: color .13s;
}
.btn-volver:hover { color: #0f172a; }
</style>
</head>
<body>
<?php include __DIR__ . '/../../includes/navbar.php'; ?>
<div class="app-shell">
  <?php $sbActivo = 'cuenta'; include __DIR__ . '/../../includes/sidebar_admin.php'; ?>
  <main class="main-area">
    <div class="pw-wrap">
      <div class="pw-card">

        <!-- Encabezado -->
        <div class="pw-head">
          <i class="fa fa-lock" style="color:#059669;font-size:22px;"></i>
          <h2>Cambiar Contraseña</h2>
        </div>
        <p class="pw-sub">Actualiza tu contraseña de acceso al sistema</p>

        <!-- Chip: usuario + rol + instituto -->
        <?php
          $instNombre = '';
          if (!empty($user['id_instituto'])) {
              $stI = $db->prepare("SELECT nombre FROM institutos WHERE id_instituto = :id LIMIT 1");
              $stI->execute([':id' => $user['id_instituto']]);
              $instNombre = $stI->fetchColumn() ?: '';
          }
        ?>
        <div class="pw-user-chip">
          <i class="fa fa-user-circle" style="color:#059669;font-size:20px;flex-shrink:0;"></i>
          <div class="nombre"><?= htmlspecialchars($user['nombre'] ?? ($user['nombres'] . ' ' . $user['apellidos'])) ?></div>
          <span class="rol-tag"><?= htmlspecialchars($user['rol'] ?? '') ?></span>
          <?php if ($instNombre): ?>
            <span class="inst-tag"><i class="fa fa-building me-1"></i><?= htmlspecialchars($instNombre) ?></span>
          <?php endif; ?>
        </div>

        <?= flashHtml() ?>

        <!-- Errores -->
        <?php if (!empty($errores)): ?>
          <ul class="err-list">
            <?php foreach ($errores as $e): ?>
              <li><?= htmlspecialchars($e) ?></li>
            <?php endforeach; ?>
          </ul>
        <?php endif; ?>

        <form method="POST" autocomplete="off">

          <label class="field-label">Contraseña actual</label>
          <div class="field-wrap">
            <input type="password" name="password_actual" id="f-actual"
                   placeholder="••••••••" autocomplete="current-password" required>
            <button type="button" class="toggle-pwd" onclick="toggleVer('f-actual',this)">
              <i class="fa fa-eye"></i>
            </button>
          </div>

          <label class="field-label">Nueva contraseña</label>
          <div class="field-wrap">
            <input type="password" name="password_nueva" id="f-nueva"
                   placeholder="Mínimo 8 caracteres" autocomplete="new-password"
                   oninput="calcFuerza(this.value)" required>
            <button type="button" class="toggle-pwd" onclick="toggleVer('f-nueva',this)">
              <i class="fa fa-eye"></i>
            </button>
            <div class="pwd-strength"><div class="pwd-strength-bar" id="str-bar"></div></div>
            <div class="pwd-strength-txt" id="str-txt" style="color:#94a3b8;">Ingresa una contraseña</div>
          </div>

          <label class="field-label">Confirmar nueva contraseña</label>
          <div class="field-wrap">
            <input type="password" name="password_confirmar" id="f-conf"
                   placeholder="Repite la contraseña" autocomplete="new-password"
                   oninput="checkMatch()" required>
            <button type="button" class="toggle-pwd" onclick="toggleVer('f-conf',this)">
              <i class="fa fa-eye"></i>
            </button>
            <div class="match-msg" id="match-msg"></div>
          </div>

          <button type="submit" class="btn-guardar">
            <i class="fa fa-save me-2"></i>Guardar nueva contraseña
          </button>
        </form>

        <ul class="tips">
          <li>Usa al menos 8 caracteres</li>
          <li>Combina letras mayúsculas, minúsculas y números</li>
          <li>Evita datos personales como tu nombre o fecha de nacimiento</li>
        </ul>

        <a href="dashboard.php" class="btn-volver">
          <i class="fa fa-arrow-left"></i> Volver al Dashboard
        </a>

      </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 ?>';</script>
<script src="<?= BASE_URL ?>/assets/js/sigvp.js"></script>
<script>
function toggleVer(id, btn) {
  var inp = document.getElementById(id);
  var ico = btn.querySelector('i');
  inp.type = (inp.type === 'password') ? 'text' : 'password';
  ico.className = (inp.type === 'text') ? 'fa fa-eye-slash' : 'fa fa-eye';
}

function calcFuerza(val) {
  var score = 0;
  if (val.length >= 8)           score++;
  if (val.length >= 12)          score++;
  if (/[A-Z]/.test(val))         score++;
  if (/[0-9]/.test(val))         score++;
  if (/[^A-Za-z0-9]/.test(val)) score++;
  var cfgs = [
    {w:'0%',   bg:'#e2e8f0', t:'Ingresa una contraseña', c:'#94a3b8'},
    {w:'20%',  bg:'#ef4444', t:'Muy débil',               c:'#ef4444'},
    {w:'40%',  bg:'#f97316', t:'Débil',                   c:'#f97316'},
    {w:'60%',  bg:'#eab308', t:'Moderada',                c:'#ca8a04'},
    {w:'80%',  bg:'#22c55e', t:'Fuerte',                  c:'#16a34a'},
    {w:'100%', bg:'#059669', t:'Muy fuerte',              c:'#047857'},
  ];
  var c = cfgs[score] || cfgs[0];
  document.getElementById('str-bar').style.width      = c.w;
  document.getElementById('str-bar').style.background = c.bg;
  document.getElementById('str-txt').textContent      = c.t;
  document.getElementById('str-txt').style.color      = c.c;
  checkMatch();
}

function checkMatch() {
  var n = document.getElementById('f-nueva').value;
  var c = document.getElementById('f-conf').value;
  var m = document.getElementById('match-msg');
  if (!c) { m.textContent = ''; return; }
  m.textContent = (n === c) ? '✓ Las contraseñas coinciden' : '✗ No coinciden';
  m.style.color  = (n === c) ? '#059669' : '#ef4444';
}
</script>
</body>
</html>