@extends('layout.base')

@section('page_content')
    <div class="ui container">
        <div class="ui form" id="login_form">
            <div class="six wide field">
                <label for="name">Nombre</label>
                <input type="text" id="name" name="name" />
            </div>
            <div class="six wide field">
                <label for="password">Contraseña</label>
                <input type="password" id="password" name="password" />
            </div>
            <button class="ui button" id="enter">Ingresar</button>
        </div>
    </div>
@endsection

@include('layout.body.scripts.cryptojs')

@push('page_scripts')
    <script type="text/javascript">
        function encryptPassword(password) {
            const passphrase = Math.floor(Math.random() * Date.now()).toString()
            const encrypted = CryptoJS.AES.encrypt(password, passphrase)
            return [passphrase, encrypted.toString()].join('')
        }
        function sendLogin(name, password) {
            const method = 'post'
            const headers = {
                Accept: 'json'
            }
            const body = new FormData()
            body.append('name', name)
            body.append('password', encryptPassword(password))
            return fetch('{{$urls->base}}/login', {method, headers, body}).then(response => {
                if (response.ok) {
                    return response.json()
                }
            }).then(data => {
                if (data.login === true) {
                    window.location = '{{(isset($redirect_uri)) ? $redirect_uri : $urls->base}}'
                }
            })
        }
        $(document).ready(() => {
            $('#login_form').find('input').keypress(event => {
                if (event.which !== 13) {
                    return
                }
                $('#enter').click()
            })
            $('#enter').click(event => {
                const form = $('#login_form')
                const name = form.find('#name').val()
                const password = form.find('#password').val()
                sendLogin(name, password)
            })
        })
    </script>
@endpush
