<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Sistema Juridica</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="{{ asset('assets/vendors/simple-line-icons/css/simple-line-icons.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/vendors/flag-icon-css/css/flag-icons.min.css') }}">
    <link rel="stylesheet" href="{{ asset('assets/vendors/css/vendor.bundle.base.css') }}">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="{{ asset('assets/css/style.css') }}">
    <!-- End layout styles -->
    <link rel="shortcut icon" href="{{ asset('assets/images/favicon.png') }}" />
  </head>
  <body>
    <div class="container-scroller">
      <div class="container-fluid page-body-wrapper full-page-wrapper">
        <div class="content-wrapper d-flex align-items-center auth">
          <div class="row flex-grow">
            <div class="col-lg-4 mx-auto">
              <div class="auth-form-light text-left p-5">
                <div class="brand-logo d-flex align-items-center justify-content-center">
                  <img src="{{ asset('assets/images/logo.png') }}" class="img-logo">
                </div>
                <h4>Bienvenid@!!!</h4>
                @if ($errors->any())
                    <ul style="list-style: none; " class="alert-danger">
                        @foreach ($errors->all() as $error)
                            <li class="text-danger">{{ $error }}</li>
                        @endforeach
                    </ul>
                @endif
                <h6 class="font-weight-light">Ingrese sus credenciales.</h6>
                <form class="pt-3" action="{{ route('login') }}" method="POST">
                    @csrf
                    <div class="form-group">
                        <input id="username" type="text" class="form-control @error('username') is-invalid @enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
                        @error('username')
                            <span class="invalid-feedback" role="alert">
                                <strong>{{ $message }}</strong>
                            </span>
                        @enderror
                    </div>
                    <div class="form-group">
                        <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
                        @error('password')
                            <span class="invalid-feedback" role="alert">
                                <strong>{{ $message }}</strong>
                            </span>
                        @enderror
                    </div>
                    <div class="form-group">
                        <label>Código de verificación:</label>
                        <div class="captcha-container text-center">
                            <div class="captcha-image-container">
                                <img id="captcha-image" src="{{ captcha_src('default') }}" alt="Captcha" style="height: 80px;  width: 250px;">
                                <button type="button" class="btn btn-dark btn-rounded btn-icon" onclick="refreshCaptcha()" id="refresh-button">
                                    <i class="icon-reload"></i>
                                </button>
                            </div>
                            <div class="captcha-controls">
                                <small class="text-muted">Ingresa el código que ves en la imagen</small>
                                <span id="countdown" class="countdown-text"></span>
                            </div>
                        </div>
                        <input type="text" name="captcha" placeholder="Ingresa el código" class="form-control @error('captcha') is-invalid @enderror" id="captcha">
                    </div>
                  <div class="mt-3 d-flex align-items-center justify-content-center">
                    <button type="submit" class="btn d-grid btn-primary btn-lg font-weight-medium auth-form-btn">INGRESAR</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
        <!-- content-wrapper ends -->
      </div>
      <!-- page-body-wrapper ends -->
    </div>
    <!-- container-scroller -->
    <script src="{{ asset('assets/vendors/js/vendor.bundle.base.js') }}"></script>
    <script src="{{ asset('assets/js/off-canvas.js') }}"></script>
    <script src="{{ asset('assets/js/hoverable-collapse.js') }}"></script>
    <script src="{{ asset('assets/js/misc.js') }}"></script>
    <script src="{{ asset('assets/js/settings.js') }}"></script>
    <script src="{{ asset('assets/js/todolist.js') }}"></script>
    <script>
        const url = "{{ route('refresh-captcha') }}";

        let timeLeft = 60;
        let countdownInterval;

        const captchaImage = document.getElementById('captcha-image');
        const refreshButton = document.getElementById('btn-refresh-captcha');

        startCountdown();

        refreshButton.addEventListener('click', function (e) {
            e.preventDefault();
            refreshCaptcha();
        });

        function startCountdown() {
            clearInterval(countdownInterval);

            countdownInterval = setInterval(() => {
                timeLeft--;

                const minutes = Math.floor(timeLeft / 60);
                const seconds = timeLeft % 60;
                document.getElementById('countdown').textContent =
                    `Se renueva en: ${minutes}:${seconds.toString().padStart(2, '0')}`;

                if (timeLeft <= 0) {
                    autoRefreshCaptcha();
                }
            }, 1000);
        }

        function refreshCaptcha() {
            fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                captchaImage.src = data.captcha + '?' + new Date().getTime(); // evitar caché
                document.querySelector('input[name="captcha"]').value = '';
                timeLeft = 60;
                startCountdown();
            })
            .catch(error => {
                console.error('Error al refrescar manualmente el captcha:', error);
            });
        }

        function autoRefreshCaptcha() {
            fetch(url, {
                method: 'GET',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                captchaImage.src = data.captcha + '?' + new Date().getTime(); // evitar caché
                document.querySelector('input[name="captcha"]').value = '';
                timeLeft = 60;
                startCountdown();
                console.log('Captcha actualizado automáticamente');
            })
            .catch(error => {
                console.error('Error al auto refrescar captcha:', error);
                timeLeft = 60;
                startCountdown(); // reiniciar igual
            });
        }

        window.addEventListener('beforeunload', function () {
            clearInterval(countdownInterval);
        });
    </script>
    <!-- endinject -->
  </body>
</html>