@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">Clave</label>
                <input type="password" id="password" name="password" />
            </div>
            <button class="ui button" id="enter">Ingresar</button>
        </div>
    </div>
@endsection

@push('page_scripts')
    <script type="text/javascript">
        function sendLogin(name, password) {
            const data = new FormData()
            data.append('name', name)
            data.append('password', password)
            return fetch('{{$urls->base}}/login', {
                method: 'post',
                headers: {
                    Accept: 'json'
                },
                body: data
            }).then(response => {
                if (response.ok) {
                    return response.json()
                }
            }).then(data => {
                if (data.login === true) {
                    @if(isset($redirect_uri))
                        window.location = '{{$redirect_uri}}'
                    @else
                        window.location = '{{$urls->base}}'
                    @endif
                }
            })
        }
        $(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
