<?php
// modules/coordinador/cambiar_contrasena.php
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/flash.php';
requireRol(ROL_COORDINADOR);

$paginaActual   = 'cambiar_contrasena';
$sidebarBaseUrl = BASE_URL . '/modules/coordinador';
$db             = getDB();

$error   = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $actual    = trim($_POST['actual']    ?? '');
    $nueva     = trim($_POST['nueva']     ?? '');
    $confirmar = trim($_POST['confirmar'] ?? '');

    if ($actual === '' || $nueva === '' || $confirmar === '') {
        $error = 'Todos los campos son obligatorios.';
    } elseif (strlen($nueva) < 8) {
        $error = 'La nueva contraseña debe tener al menos 8 caracteres.';
    } elseif ($nueva !== $confirmar) {
        $error = 'La nueva contraseña y su confirmación no coinciden.';
    } else {
        $hashActual = hash('sha256', $actual);

        $st = $db->prepare("SELECT id FROM usuarios WHERE id = :id AND contrasena = :hash LIMIT 1");
        $st->execute([':id' => $_SESSION['id_usuario'] ?? 0, ':hash' => $hashActual]);

        if (!$st->fetch()) {
            $error = 'La contraseña actual es incorrecta.';
        } else {
            $hashNueva = hash('sha256', $nueva);
            $upd = $db->prepare("UPDATE usuarios SET contrasena = :hash WHERE id = :id");
            $upd->execute([':hash' => $hashNueva, ':id' => $_SESSION['id_usuario']]);
            $success = 'Contraseña actualizada correctamente.';
        }
    }
}

$user      = currentUser();
$pageTitle = 'Cambiar Contraseña';
?>
<!DOCTYPE html>
<html lang="es">
<?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-coordinador.css">

<style>
/* Scroll en el sidebar igual que las demás páginas */
.sidebar {
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: thin;
  scrollbar-color: rgba(255,255,255,.2) transparent;
}
.sidebar::-webkit-scrollbar        { width: 4px; }
.sidebar::-webkit-scrollbar-track  { background: transparent; }
.sidebar::-webkit-scrollbar-thumb  { background: rgba(255,255,255,.25); border-radius: 4px; }
</style>

<body>
<?php include __DIR__ . '/../../includes/navbar.php'; ?>

<div class="wrapper d-flex">
  <?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'sidebar-coordinador.php'; ?>

  <div class="main-content flex-grow-1 p-4">
    <div style="max-width:520px;">

      <h4 class="mb-4"><i class="fa fa-key me-2 text-primary"></i>Cambiar Contraseña</h4>

      <?php if ($error): ?>
        <div class="alert alert-danger d-flex align-items-center gap-2">
          <i class="fa fa-circle-xmark"></i> <?= htmlspecialchars($error) ?>
        </div>
      <?php endif; ?>
      <?php if ($success): ?>
        <div class="alert alert-success d-flex align-items-center gap-2">
          <i class="fa fa-circle-check"></i> <?= htmlspecialchars($success) ?>
        </div>
      <?php endif; ?>

      <div class="card shadow-sm border-0">
        <div class="card-body p-4">
          <form method="POST" autocomplete="off">

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

            <div class="mb-3">
              <label class="form-label fw-semibold">Nueva contraseña</label>
              <div class="input-group">
                <input type="password" name="nueva" id="nueva"
                       class="form-control" placeholder="Mínimo 8 caracteres" required minlength="8">
                <button class="btn btn-outline-secondary toggle-pass" type="button" data-target="nueva">
                  <i class="fa fa-eye"></i>
                </button>
              </div>
              <div class="progress mt-2" style="height:5px;">
                <div id="strengthBar" class="progress-bar" role="progressbar" style="width:0%;transition:width .3s"></div>
              </div>
              <small id="strengthLabel" class="text-muted"></small>
            </div>

            <div class="mb-4">
              <label class="form-label fw-semibold">Confirmar nueva contraseña</label>
              <div class="input-group">
                <input type="password" name="confirmar" id="confirmar"
                       class="form-control" placeholder="Repite la nueva contraseña" required>
                <button class="btn btn-outline-secondary toggle-pass" type="button" data-target="confirmar">
                  <i class="fa fa-eye"></i>
                </button>
              </div>
              <small id="matchLabel" class="mt-1 d-block"></small>
            </div>

            <div class="d-grid">
              <button type="submit" class="btn btn-primary">
                <i class="fa fa-floppy-disk me-1"></i> Guardar cambios
              </button>
            </div>

          </form>
        </div>
      </div>

    </div>
  </div>
</div>

<script>
document.querySelectorAll('.toggle-pass').forEach(btn => {
  btn.addEventListener('click', () => {
    const input = document.getElementById(btn.dataset.target);
    const isPass = input.type === 'password';
    input.type = isPass ? 'text' : 'password';
    btn.querySelector('i').className = isPass ? 'fa fa-eye-slash' : 'fa fa-eye';
  });
});

const nuevaInput  = document.getElementById('nueva');
const strengthBar = document.getElementById('strengthBar');
const strengthLbl = document.getElementById('strengthLabel');

nuevaInput.addEventListener('input', () => {
  const v = nuevaInput.value;
  let score = 0;
  if (v.length >= 8)           score++;
  if (/[A-Z]/.test(v))        score++;
  if (/[0-9]/.test(v))        score++;
  if (/[^A-Za-z0-9]/.test(v)) score++;
  const pct    = score * 25;
  const colors = ['', '#ef4444', '#f97316', '#eab308', '#22c55e'];
  const labels = ['', 'Débil', 'Regular', 'Buena', 'Fuerte'];
  strengthBar.style.width      = pct + '%';
  strengthBar.style.background = colors[score] || 'transparent';
  strengthLbl.textContent      = score > 0 ? labels[score] : '';
  strengthLbl.style.color      = colors[score] || '';
});

const confirmarInput = document.getElementById('confirmar');
const matchLbl       = document.getElementById('matchLabel');
confirmarInput.addEventListener('input', () => {
  if (!confirmarInput.value) { matchLbl.textContent = ''; return; }
  if (confirmarInput.value === nuevaInput.value) {
    matchLbl.textContent = '✓ Las contraseñas coinciden';
    matchLbl.style.color = '#22c55e';
  } else {
    matchLbl.textContent = '✗ Las contraseñas no coinciden';
    matchLbl.style.color = '#ef4444';
  }
});
</script>
<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>
</body>
</html>