@extends('ventas.base')

@section('venta_subtitle')
    Editar Venta
@endsection

@section('venta_content')
    <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>
@endsection

@push('page_scripts')
    <script type="text/javascript">
        const editVenta = {
            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
            },
            redirect() {
                window.location = '{{$urls->base}}/venta/{{$venta->id}}'
            },
            edit() {
                const uri = '{{$urls->api}}/venta/{{$venta->id}}'
                const data = new FormData()
                data.set('valor', $('#valor').val())
                data.set('fecha', $('#fecha_calendar').calendar('get date').toISOString())
                return fetchAPI(uri, {method: 'post', body: data}).then(response => {
                    if (response.ok) {
                        return response.json()
                    }
                }).then(json => {
                    if (!json.edited) {
                        return
                    }
                    this.redirect()
                })
            },
            setup() {
                $('#fecha_calendar').calendar({
                    type: 'date',
                    initialDate: '{{$venta->fecha->format('Y-m-d')}}',
                    text: {
                        months: this.getMonthsList()
                    }
                })
                $('#edit_form').submit(event => {
                    event.preventDefault()
                    this.edit()
                    return false
                })
            }
        }
        $(document).ready(() => {
            editVenta.setup()
        })
    </script>
@endpush
