<?php

  /*
    En ocasiones el usuario puede volver al login
    aun si ya existe una sesion iniciada, lo correcto
    es no mostrar otra ves el login sino redireccionarlo
    a su pagina principal mientras exista una sesion entonces
    creamos un archivo que controle el redireccionamiento
  */

  session_start();

  // isset verifica si existe una variable o eso creo xd
  if(isset($_SESSION['id'])){
    header('location: controller/redirec.php');
  }

?>


<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registro - ISET Sistema de Gestión</title>

    <!-- Importamos los estilos de Bootstrap -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Font Awesome: para los iconos -->
    <link rel="stylesheet" href="css/font-awesome.min.css">
    <!-- Sweet Alert: alertas JavaScript presentables para el usuario (más bonitas que el alert) -->
    <link rel="stylesheet" href="css/sweetalert.css">
    <!-- Estilos personalizados: archivo personalizado 100% real no feik -->
    <link rel="stylesheet" href="css/style.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
      :root {
        --primary-color: #2563eb;
        --primary-dark: #1d4ed8;
        --secondary-color: #64748b;
        --accent-color: #f1f5f9;
        --text-primary: #1e293b;
        --text-secondary: #64748b;
        --border-color: #e2e8f0;
        --success-color: #10b981;
        --error-color: #ef4444;
        --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
        --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
        --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
      }

      * {
        box-sizing: border-box;
      }

      body {
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        min-height: 100vh;
        margin: 0;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--text-primary);
        line-height: 1.6;
      }

      .register-container {
        width: 100%;
        max-width: 480px;
        margin: 0 auto;
        padding: 20px;
      }

      .register-card {
        background: white;
        border-radius: 16px;
        box-shadow: var(--shadow-lg);
        overflow: hidden;
        position: relative;
        animation: slideUp 0.6s ease-out;
      }

      @keyframes slideUp {
        from {
          opacity: 0;
          transform: translateY(30px);
        }
        to {
          opacity: 1;
          transform: translateY(0);
        }
      }

      .register-header {
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
        color: white;
        padding: 40px 32px 32px;
        text-align: center;
        position: relative;
      }

      .register-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.1"/><circle cx="10" cy="60" r="0.5" fill="white" opacity="0.1"/><circle cx="90" cy="40" r="0.5" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
        opacity: 0.3;
      }

      .logo-container {
        position: relative;
        z-index: 1;
        margin-bottom: 16px;
      }

      .logo {
        width: 80px;
        height: 80px;
        background: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 16px;
        box-shadow: var(--shadow-md);
      }

      .logo img {
        width: 60px;
        height: 60px;
        object-fit: contain;
      }

      .register-title {
        font-size: 28px;
        font-weight: 700;
        margin: 0 0 8px;
        position: relative;
        z-index: 1;
      }

      .register-subtitle {
        font-size: 16px;
        font-weight: 400;
        opacity: 0.9;
        margin: 0;
        position: relative;
        z-index: 1;
      }

      .register-body {
        padding: 32px;
      }

      .form-group {
        margin-bottom: 24px;
      }

      .form-label {
        display: block;
        font-size: 14px;
        font-weight: 500;
        color: var(--text-primary);
        margin-bottom: 8px;
      }

      .input-group {
        position: relative;
        display: flex;
        align-items: center;
        background: #f8fafc;
        border: 2px solid transparent;
        border-radius: 12px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        overflow: hidden;
      }

      .input-group:hover {
        background: #f1f5f9;
      }

      .input-group:focus-within {
        background: white;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
      }

      .input-group.focused {
        background: white;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
      }

      .input-group.has-value {
        background: white;
        border-color: var(--border-color);
      }

      .input-group.has-value:focus-within {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
      }

      .input-group.error {
        border-color: var(--error-color);
        background: #fef2f2;
      }

      .input-group.error:focus-within {
        border-color: var(--error-color);
        box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
      }

      .form-control.error {
        color: var(--error-color);
      }

      .input-group.error .input-group-addon i {
        color: var(--error-color);
      }

      /* Password strength indicators */
      .input-group.weak {
        border-color: var(--error-color);
      }

      .input-group.weak:focus-within {
        border-color: var(--error-color);
        box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
      }

      .input-group.medium {
        border-color: #f59e0b;
      }

      .input-group.medium:focus-within {
        border-color: #f59e0b;
        box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
      }

      .input-group.strong {
        border-color: var(--success-color);
      }

      .input-group.strong:focus-within {
        border-color: var(--success-color);
        box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
      }

      .input-group.weak .input-group-addon i {
        color: var(--error-color);
      }

      .input-group.medium .input-group-addon i {
        color: #f59e0b;
      }

      .input-group.strong .input-group-addon i {
        color: var(--success-color);
      }

      .input-group-addon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48px;
        height: 48px;
        background: transparent;
        border: none;
        color: var(--text-secondary);
        font-size: 18px;
      }

      .input-group-addon i {
        transition: color 0.3s ease;
      }

      .input-group:focus-within .input-group-addon i {
        color: var(--primary-color);
      }

      .form-control {
        flex: 1;
        border: none;
        background: transparent;
        padding: 16px 16px 16px 0;
        font-size: 16px;
        font-weight: 400;
        color: var(--text-primary);
        outline: none;
      }

      .form-control::placeholder {
        color: var(--text-secondary);
        opacity: 0.7;
      }

      .form-control:focus {
        outline: none;
      }

      .btn-register {
        width: 100%;
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
        border: none;
        border-radius: 12px;
        padding: 16px 24px;
        font-size: 16px;
        font-weight: 600;
        color: white;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: var(--shadow-md);
        position: relative;
        overflow: hidden;
      }

      .btn-register:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-lg);
        background: linear-gradient(135deg, var(--primary-dark) 0%, #1e40af 100%);
      }

      .btn-register:active {
        transform: translateY(0);
      }

      .btn-register:disabled {
        opacity: 0.6;
        cursor: not-allowed;
        transform: none;
      }

      .btn-register::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
        transition: left 0.5s;
      }

      .btn-register:hover::before {
        left: 100%;
      }

      .btn-register:focus {
        outline: none;
        box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.3);
      }

      .login-link {
        text-align: center;
        margin-top: 24px;
        padding-top: 24px;
        border-top: 1px solid var(--border-color);
      }

      .login-link p {
        margin: 0;
        color: var(--text-secondary);
        font-size: 14px;
      }

      .login-link a {
        color: var(--primary-color);
        text-decoration: none;
        font-weight: 500;
        transition: color 0.3s ease;
      }

      .login-link a:hover {
        color: var(--primary-dark);
        text-decoration: underline;
      }

      .loading-container {
        display: none;
        text-align: center;
        padding: 20px;
      }

      .loading-container.show {
        display: block;
      }

      .spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid var(--primary-color);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 16px;
      }

      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }

      .loading-text {
        color: var(--text-secondary);
        font-size: 14px;
        font-weight: 500;
      }

      /* Responsive Design */
      @media (max-width: 480px) {
        .register-container {
          padding: 16px;
        }

        .register-header {
          padding: 32px 24px 24px;
        }

        .register-body {
          padding: 24px;
        }

        .register-title {
          font-size: 24px;
        }

        .logo {
          width: 64px;
          height: 64px;
        }

        .logo img {
          width: 48px;
          height: 48px;
        }
      }
    </style>
  </head>
  <body>
    <div class="register-container">
      <div class="register-card">
        <!-- Header Section -->
        <div class="register-header">
          <div class="logo-container">
            <div class="logo">
              <img src="view/admin/isettacselogotransparent.png" alt="ISET Logo" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
              <div class="logo-fallback" style="display: none; width: 60px; height: 60px; background: var(--primary-color); border-radius: 50%; align-items: center; justify-content: center; color: white; font-size: 24px; font-weight: bold;">
                ISET
              </div>
            </div>
            <h1 class="register-title">Crear Cuenta</h1>
            <p class="register-subtitle">Únete a ISET</p>
          </div>
        </div>

        <!-- Body Section -->
        <div class="register-body">
          <form id="formulario_registro">
            <!-- Nombre -->
            <div class="form-group">
              <label class="form-label" for="name">Nombre Completo</label>
              <div class="input-group">
                <div class="input-group-addon">
                  <i class="fa fa-user"></i>
                </div>
                <input type="text" class="form-control" id="name" name="name" placeholder="Ingresa tu nombre completo" required>
              </div>
            </div>

            <!-- Email -->
            <div class="form-group">
              <label class="form-label" for="email">Correo Electrónico</label>
              <div class="input-group">
                <div class="input-group-addon">
                  <i class="fa fa-envelope"></i>
                </div>
                <input type="email" class="form-control" id="email" name="email" placeholder="Ingresa tu correo electrónico" required>
              </div>
            </div>

            <!-- Contraseña -->
            <div class="form-group">
              <label class="form-label" for="clave">Contraseña</label>
              <div class="input-group">
                <div class="input-group-addon">
                  <i class="fa fa-lock"></i>
                </div>
                <input type="password" class="form-control" id="clave" name="clave" placeholder="Crea una contraseña" autocomplete="off" required>
              </div>
              <small class="form-text text-muted" style="color: var(--text-secondary); font-size: 12px; margin-top: 4px;">
                Mínimo 6 caracteres. Incluye mayúsculas, minúsculas y números para mayor seguridad.
              </small>
            </div>

            <!-- Verificar Contraseña -->
            <div class="form-group">
              <label class="form-label" for="clave2">Confirmar Contraseña</label>
              <div class="input-group">
                <div class="input-group-addon">
                  <i class="fa fa-lock"></i>
                </div>
                <input type="password" class="form-control" id="clave2" name="clave2" placeholder="Confirma tu contraseña" autocomplete="off" required>
              </div>
            </div>

            <!-- Loading Animation -->
            <div class="loading-container" id="load">
              <div class="spinner"></div>
              <div class="loading-text">Creando tu cuenta...</div>
            </div>

            <!-- Register Button -->
            <button type="button" class="btn-register" id="registro">
              <span class="btn-text">Crear Cuenta</span>
            </button>

            <!-- Login Link -->
            <div class="login-link">
              <p>
                ¿Ya tienes una cuenta? <a href="login.php">Inicia sesión aquí</a>
              </p>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Jquery -->
    <script src="js/jquery.js"></script>
    <!-- Bootstrap js -->
    <script src="js/bootstrap.min.js"></script>
    <!-- SweetAlert js -->
    <script src="js/sweetalert.min.js"></script>
    <!-- Js personalizado -->
    <script src="js/operaciones.js"></script>

    <script>
      // Enhanced registration functionality that works with existing operaciones.js
      $(document).ready(function() {
        const registerBtn = $('#registro');
        const loadContainer = $('#load');
        const btnText = $('.btn-text');

        // Override the existing registration functionality to work with our new design
        $('#registro').off('click').on('click', function(){
          // Traemos los datos de los inputs
          var name = $('#name').val().trim();
          var email = $('#email').val().trim();
          var clave = $('#clave').val().trim();
          var clave2 = $('#clave2').val().trim();

          // Validation
          if (!name || !email || !clave || !clave2) {
            swal('Error', 'Por favor complete todos los campos', 'error');
            return;
          }

          // Email validation
          var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
          if (!emailRegex.test(email)) {
            swal('Error', 'Por favor ingrese un correo electrónico válido', 'warning');
            return;
          }

          // Password validation
          if (clave.length < 6) {
            swal('Error', 'La contraseña debe tener al menos 6 caracteres', 'warning');
            return;
          }

          if (clave !== clave2) {
            swal('Error', 'Las contraseñas no coinciden', 'error');
            return;
          }

          // Show loading state with our new design
          registerBtn.prop('disabled', true);
          btnText.text('Creando cuenta...');
          loadContainer.addClass('show');

          // Envio de datos mediante Ajax
          $.ajax({
            method: 'POST',
            url: 'controller/registroController.php',
            data: {
              name: name,
              email: email,
              clave: clave,
              clave2: clave2
            },
            beforeSend: function(){
              // Loading state is already handled above
            },
            success: function(res){
              // Hide loading state
              registerBtn.prop('disabled', false);
              btnText.text('Crear Cuenta');
              loadContainer.removeClass('show');

              // Validate the response
              if(res == 'error_1'){
                swal('Error', 'Campos obligatorios, por favor llena el email y las claves', 'warning');
              }else if(res == 'error_2'){
                swal('Error', 'Las claves deben ser iguales, por favor intentalo de nuevo', 'error');
              }else if(res == 'error_3'){
                swal('Error', 'El correo que ingresaste ya se encuentra registrado', 'error');
              }else if(res == 'error_4'){
                swal('Error', 'Por favor ingresa un correo valido', 'warning');
              }else{
                // Success - redirect to the specified page
                window.location.href = res;
              }
            },
            error: function() {
              // Handle AJAX errors
              registerBtn.prop('disabled', false);
              btnText.text('Crear Cuenta');
              loadContainer.removeClass('show');
              swal('Error', 'Error de conexión. Por favor intente nuevamente.', 'error');
            }
          });
        });

        // Handle form submission
        $('#formulario_registro').on('submit', function(e) {
          e.preventDefault();
          $('#registro').click();
        });

        // Handle Enter key press
        $('#name, #email, #clave, #clave2').on('keypress', function(e) {
          if (e.which === 13) {
            $('#registro').click();
          }
        });

        // Add focus effects for better UX
        $('.input-group').on('focusin', function() {
          $(this).addClass('focused');
        }).on('focusout', function() {
          $(this).removeClass('focused');
        });

        // Add input validation feedback
        $('.form-control').on('input', function() {
          const $input = $(this);
          const $inputGroup = $input.closest('.input-group');
          
          if ($input.val().trim()) {
            $inputGroup.addClass('has-value');
          } else {
            $inputGroup.removeClass('has-value');
          }
        });

        // Password confirmation validation
        $('#clave2').on('input', function() {
          const clave = $('#clave').val();
          const clave2 = $(this).val();
          const $inputGroup = $(this).closest('.input-group');
          
          if (clave2 && clave !== clave2) {
            $inputGroup.addClass('error');
            $(this).addClass('error');
          } else {
            $inputGroup.removeClass('error');
            $(this).removeClass('error');
          }
        });

        // Password strength validation
        $('#clave').on('input', function() {
          const password = $(this).val();
          const $inputGroup = $(this).closest('.input-group');
          
          // Remove any existing strength classes
          $inputGroup.removeClass('weak medium strong');
          
          if (password.length > 0) {
            let strength = 0;
            
            // Check for length
            if (password.length >= 6) strength++;
            if (password.length >= 8) strength++;
            
            // Check for complexity
            if (/[a-z]/.test(password)) strength++;
            if (/[A-Z]/.test(password)) strength++;
            if (/[0-9]/.test(password)) strength++;
            if (/[^A-Za-z0-9]/.test(password)) strength++;
            
            // Apply strength class
            if (strength >= 4) {
              $inputGroup.addClass('strong');
            } else if (strength >= 2) {
              $inputGroup.addClass('medium');
            } else {
              $inputGroup.addClass('weak');
            }
          }
        });

        // Clear errors when user starts typing
        $('.form-control').on('input', function() {
          const $input = $(this);
          const $inputGroup = $input.closest('.input-group');
          
          // Clear error state when user starts typing
          if ($inputGroup.hasClass('error')) {
            $inputGroup.removeClass('error');
            $input.removeClass('error');
          }
        });
      });
    </script>
  </body>
</html>
