@extends('layout.base')

@section('page_content')
    <div class="ui container">
        <h2 class="ui header">Editar Venta</h2>
        <form class="ui form" id="edit_form">
            <div class="inline field">
                <label for="valor">Valor</label>
                <div class="ui right labeled input">
                    <input type="text" id="valor" name="valor" value="{{$venta->valor}}" />
                    <div class="ui label">UF</div>
                </div>
            </div>
            <div class="inline field">
                <label for="fecha">Fecha Promesa</label>
                <div class="ui calendar" id="fecha_calendar">
                    <div class="ui icon input">
                        <input type="text" name="fecha" id="fecha" />
                        <i class="calendar icon"></i>
                    </div>
                </div>
            </div>
            <button class="ui button">
                Guardar
            </button>
        </form>
    </div>
@endsection

@push('page_scripts')
    <script type="text/javascript">
        function getMonthsList() {
            const formatter = new Intl.DateTimeFormat('es-CL', {month: 'long'})
            const months = []
            let m = ''
            for (let i = 0; i < 12; i ++) {
                m = formatter.format((new Date()).setMonth(i))
                months.push(m.charAt(0).toUpperCase() + m.slice(1))
            }
            return months
        }
        function redirect() {
            const uri = '{{$urls->base}}/venta/{{$venta->id}}'
            window.location = uri
        }
        function editVenta() {
            const original = {
                valor: {{$venta->valor}},
                fecha: new Date('{{$venta->fecha->format('Y-m-d')}}T00:00:00')
            }
            const collator = new Intl.Collator('es-CL')
            const data = {}
            Object.keys(original).forEach(name => {
                let val = $("[name='" + name + "']").val()
                if (name === 'fecha') {
                    val = $('#fecha_calendar').calendar('get date')
                    if (val.getTime() !== original[name].getTime()) {
                        data[name] = [val.getFullYear(), (''+(val.getMonth()+1)).padStart(2, '0'), (''+val.getDate()).padStart(2, '0')].join('-')
                    }
                    return
                }
                if (collator.compare(val, original[name]) !== 0) {
                    data[name] = val
                }
            })
            if (Object.keys(data).length === 0) {
                redirect()
                return
            }
            const uri = '{{$urls->api}}/venta/{{$venta->id}}'
            return fetch(uri,
                {method: 'put', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)}
            ).then(response => {
                if (response.ok) {
                    redirect()
                }
            })
        }
        $(document).ready(() => {
            $('#fecha_calendar').calendar({
                type: 'date',
                initialDate: '{{$venta->fecha->format('Y-m-d')}}',
                text: {
                    months: getMonthsList()
                }
            })
            $('#edit_form').submit(event => {
                event.preventDefault()
                editVenta()
                return false
            })
        })
    </script>
@endpush
