@extends('layout.base')

@section('page_content')
    <div class="ui container">
        <h2 class="ui header">
            Escritura -
            {{$venta->proyecto()->descripcion}} -
            <a href="{{$urls->base}}/venta/{{$venta->id}}">
                {{$venta->propiedad()->summary()}}
            </a>
        </h2>
        <form class="ui form" id="edit_form">
            <div class="three wide field">
                <label for="fecha">Fecha</label>
                <div class="ui calendar" id="fecha">
                    <div class="ui left icon input">
                        <i class="calendar icon"></i>
                        <input type="text" placeholder="Fecha" />
                    </div>
                </div>
            </div>
            <button class="ui button">Guardar</button>
        </form>
    </div>
@endsection

@push('page_scripts')
    <script>
        function editEscritura() {
            const url = '{{$urls->api}}/ventas/escritura/{{$venta->id}}/edit'
            const data = new FormData()
            data.set('venta', {{$venta->id}})
            const fecha = $('#fecha').calendar('get date')
            data.set('fecha', fecha.toISOString())
            return fetchAPI(url, {method: 'post', body: data}).then(response => {
                if (response.ok) {
                    return response.json()
                }
            }).then(json => {
                if (!json.edited) {
                    return
                }
                window.location = '{{$urls->base}}/venta/{{$venta->id}}'
            })
        }
        $(document).ready(() => {
            calendar_date_options.initialDate = new Date({{$venta->currentEstado()->fecha->format('Y, m-1, j')}})
            $('#fecha').calendar(calendar_date_options)
            $('#edit_form').submit(event => {
                event.preventDefault()
                editEscritura()
                return false
            })
        })
    </script>
@endpush
