<?php
// modules/tutor_empresa/cambiar_contrasena.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_TUTOR_EMPRESA);

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

$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 {
        $st = $db->prepare("SELECT password_hash FROM usuarios WHERE id_usuario = :id LIMIT 1");
        $st->execute([':id' => $_SESSION['id_usuario'] ?? 0]);
        $row = $st->fetch(PDO::FETCH_ASSOC);

        if (!$row || !password_verify($actual, $row['password_hash'])) {
            $error = 'La contraseña actual es incorrecta.';
        } else {
            $nuevoHash = password_hash($nueva, PASSWORD_BCRYPT);
            $db->prepare("UPDATE usuarios SET password_hash = :hash, cambiar_password = 0 WHERE id_usuario = :id")
               ->execute([':hash' => $nuevoHash, ':id' => $_SESSION['id_usuario']]);
            $success = 'Contraseña actualizada correctamente.';
        }
    }
}
?>
<?php $paginaActual = 'cambiar_contrasena'; ?>
<!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">
<style>
.main-area {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  background: #f4f6fb;
  min-height: calc(100vh - 56px);
  padding: 2.5rem 1.5rem;
}
.pass-card {
  width: 100%;
  max-width: 480px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 32px rgba(0,0,0,.10);
  overflow: hidden;
}
.pass-card-header {
  background: linear-gradient(135deg, #0f1f3d 0%, #ec4899 100%);
  padding: 2rem 2rem 1.5rem;
  text-align: center;
  color: #fff;
}
.pass-card-header .icon-wrap {
  width: 64px; height: 64px;
  background: rgba(255,255,255,.15);
  border-radius: 50%;
  display: flex; align-items: center; justify-content: center;
  margin: 0 auto 1rem;
  font-size: 28px;
}
.pass-card-header h4 { margin:0; font-size:1.35rem; font-weight:700; }
.pass-card-header p  { margin:.3rem 0 0; font-size:.85rem; opacity:.8; }
.pass-card-body { padding: 2rem; }
.pass-card-body .form-label {
  font-size: .78rem; font-weight: 700;
  text-transform: uppercase; letter-spacing: .6px;
  color: #64748b; margin-bottom: .4rem;
}
.pass-card-body .form-control {
  border: 1.5px solid #e2e8f0; border-radius: 8px;
  padding: .6rem .9rem; font-size: .95rem;
  transition: border-color .2s, box-shadow .2s;
}
.pass-card-body .form-control:focus {
  border-color: #ec4899;
  box-shadow: 0 0 0 3px rgba(236,72,153,.15);
}
.pass-card-body .input-group .btn {
  border: 1.5px solid #e2e8f0; border-left: 0;
  border-radius: 0 8px 8px 0;
  color: #94a3b8; background: #f8fafc;
}
.pass-card-body .input-group .btn:hover { color: #ec4899; }
.strength-bar-bg {
  height: 5px; background: #e2e8f0;
  border-radius: 4px; overflow: hidden; margin-top: .4rem;
}
.strength-bar-fill {
  height: 100%; width: 0%;
  border-radius: 4px;
  transition: width .35s, background .35s;
}
.btn-guardar {
  background: linear-gradient(135deg, #0f1f3d, #ec4899);
  border: none; border-radius: 10px;
  padding: .75rem; font-size: 1rem;
  font-weight: 600; color: #fff; width: 100%;
  transition: opacity .2s, transform .1s;
  margin-top: .5rem;
}
.btn-guardar:hover  { opacity: .92; color: #fff; }
.btn-guardar:active { transform: scale(.98); }
</style>
</head>
<body>
<?php include __DIR__ . '/../../includes/navbar.php'; ?>

<div class="app-shell">
  <?php include __DIR__ . '/../../includes/sidebar-tutor-empresa.php'; ?>

  <main class="main-area">
    <div class="pass-card">

      <div class="pass-card-header">
        <div class="icon-wrap"><i class="fa fa-lock"></i></div>
        <h4>Cambiar Contraseña</h4>
        <p>Actualiza tu contraseña de acceso al sistema</p>
      </div>

      <?php if ($error): ?>
        <div class="alert alert-danger d-flex align-items-center gap-2 mx-4 mt-3 mb-0 rounded-3">
          <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 mx-4 mt-3 mb-0 rounded-3">
          <i class="fa fa-circle-check"></i> <?= htmlspecialchars($success) ?>
        </div>
      <?php endif; ?>

      <div class="pass-card-body">
        <form method="POST" autocomplete="off">

          <div class="mb-3">
            <label class="form-label">Contraseña actual</label>
            <div class="input-group">
              <input type="password" name="actual" id="actual"
                     class="form-control" placeholder="Ingresa tu contraseña actual" required>
              <button class="btn toggle-pass" type="button" data-target="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="nueva"
                     class="form-control" placeholder="Mínimo 8 caracteres" required minlength="8">
              <button class="btn toggle-pass" type="button" data-target="nueva">
                <i class="fa fa-eye"></i>
              </button>
            </div>
            <div class="strength-bar-bg">
              <div id="strengthBar" class="strength-bar-fill"></div>
            </div>
            <small id="strengthLabel" style="font-size:.75rem;font-weight:600;"></small>
          </div>

          <div class="mb-3">
            <label class="form-label">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 toggle-pass" type="button" data-target="confirmar">
                <i class="fa fa-eye"></i>
              </button>
            </div>
            <small id="matchLabel" style="font-size:.75rem;font-weight:600;" class="mt-1 d-block"></small>
          </div>

          <button type="submit" class="btn-guardar">
            <i class="fa fa-floppy-disk me-2"></i> Guardar cambios
          </button>

        </form>
      </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>
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 colors = ['transparent','#ef4444','#f97316','#eab308','#22c55e'];
  const labels = ['','Débil','Regular','Buena','Fuerte'];
  strengthBar.style.width      = (score * 25) + '%';
  strengthBar.style.background = colors[score];
  strengthLbl.textContent      = 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 = '✗ No coinciden';
    matchLbl.style.color = '#ef4444';
  }
});
</script>
</body>
</html>