@extends('ventas.base')

@section('venta_subtitle')
    Escriturar
@endsection

@section('venta_content')
    <div class="ui basic segment">
        <div class="ui four columns grid">
            <div class="column">Faltante</div>
            <div class="column">{{$format->pesos($venta->saldo('pesos'))}}</div>
            <div class="column">{{$format->ufs($venta->saldo())}}</div>
        </div>
    </div>
    <div class="ui divider"></div>
    <form class="ui form" id="escriturar_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" name="fecha" />
                </div>
            </div>
        </div>
        @if ($venta->formaPago()->pie !== null)
            @if ($venta->formaPago()->pie->reajuste === null)
                <h4 class="ui header optional" data-name="reajuste">Reajuste <i class="small plus icon"></i></h4>
                <div class="fields optional" id="reajuste">
                    <div class="field">
                        <label for="valor_reajuste">Valor [$]</label>
                        <div class="ui left labeled input">
                            <div class="ui basic label">$</div>
                            <input type="text" name="valor_reajuste" id="valor_reajuste" />
                        </div>
                    </div>
                    <div class="field">
                        <label for="fecha_reajuste">Fecha</label>
                        <div class="ui calendar" id="fecha_reajuste">
                            <div class="ui left icon input">
                                <i class="calendar icon"></i>
                                <input type="text" name="fecha_reajuste" />
                            </div>
                        </div>
                    </div>
                </div>
            @else
                <h4 class="ui header" data-name="reajuste">Reajuste</h4>
                <div class="fields" id="reajuste">
                    <div class="field">
                        <label for="valor_reajuste">Valor [$]</label>
                        <div class="ui left labeled disabled input">
                            <div class="ui basic label">$</div>
                            <input type="text" value="{{$format->number($venta->formaPago()->pie->reajuste->valor)}}" />
                        </div>
                    </div>
                    <div class="field">
                        <label for="fecha_reajuste">Fecha</label>
                        <div class="ui disabled input">
                            <input type="text" value="{{$venta->formaPago()->pie->reajuste->fecha->format('d-m-Y')}}" />
                        </div>
                    </div>
                </div>
            @endif
        @endif
        @if (!isset($venta->formaPago()->escritura))
            <h4 class="ui header optional" data-name="pago">Pago en Escritura <i class="small plus icon"></i></h4>
            <div class="fields optional" id="pago">
                <div class="field">
                    <label for="valor_pago_pesos">Valor [$]</label>
                    <div class="ui left labeled input">
                        <div class="ui basic label">$</div>
                        <input type="text" name="valor_pago_pesos" id="valor_pago_pesos" />
                    </div>
                </div>
                <div class="field">
                    <label for="valor_pago_ufs">(Valor [UF])</label>
                    <div class="ui right labeled input">
                        <input type="text" name="valor_pago_ufs" id="valor_pago_ufs" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
                <div class="field">
                    <label for="fecha_pago">Fecha</label>
                    <div class="ui calendar" id="fecha_pago">
                        <div class="ui left icon input">
                            <i class="calendar icon"></i>
                            <input type="text" name="fecha_pago" />
                        </div>
                    </div>
                </div>
            </div>
        @else
            <h4 class="ui header" data-name="pago">Pago en Escritura</h4>
            <div class="fields" id="pago">
                <div class="field">
                    <label for="valor_pago_pesos">Valor [$]</label>
                    <div class="ui left labeled disabled input">
                        <div class="ui basic label">$</div>
                        <input type="text" value="{{$format->number($venta->formaPago()->escritura->pago->valor)}}" />
                    </div>
                </div>
                <div class="field">
                    <label for="valor_pago_ufs">(Valor [UF])</label>
                    <div class="ui right labeled disabled input">
                        <input type="text" value="{{$format->number($venta->formaPago()->escritura->pago->valor(),2)}}" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
                <div class="field">
                    <label for="fecha_pago">Fecha</label>
                    <div class="ui disabled input">
                        <input type="text" value="{{$venta->formaPago()->escritura->pago->fecha->format('d-m-Y')}}">
                    </div>
                </div>
            </div>
        @endif
        @if (!isset($venta->formaPago()->subsidio))
            <h4 class="ui header optional" data-name="subsidio">Subsidio <i class="small plus icon"></i></h4>
            <div class="fields optional" id="subsidio">
                <div class="field">
                    <label for="valor_ahorro">Valor Ahorrado [UF]</label>
                    <div class="ui right labeled input">
                        <input type="text" name="valor_ahorro" id="valor_ahorro" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
                <div class="field">
                    <label for="valor_subsidio">Valor Subsidio [UF]</label>
                    <div class="ui right labeled input">
                        <input type="text" name="valor_subsidio" id="valor_subsidio" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
                <div class="field">
                    <label for="total_subsidio">Total</label>
                    <div class="ui right labeled disabled input">
                        <input type="text" id="total_subsidio" value="0,00" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
            </div>
        @else
            <h4 class="ui header" data-name="subsidio">Subsidio</h4>
            <div class="fields">
                <div class="field">
                    <label for="valor_ahorro">Valor Ahorrado</label>
                    <div class="ui right labeled disabled input">
                        <input type="text" value="{{$venta->formaPago()->subsidio->ahorro->valor()}}" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
                <div class="field">
                    <label for="valor_subsidio">Valor Subsidio</label>
                    <div class="ui right labeled disabled input">
                        <input type="text" value="{{$venta->formaPago()->subidio->pago->valor()}}" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
            </div>
        @endif
        @if (!isset($venta->formaPago()->credito) or $venta->formaPago()->credito->pago->banco === null)
            <h4 class="ui header">Crédito</h4>
            <div class="fields">
                <div class="field">
                    <label for="valor_credito">Valor [UF]</label>
                    <div class="ui right labeled input">
                        <input type="text" id="valor_credito" name="valor_credito" value="{{$venta->formaPago()->credito?->pago->valor() ?? ''}}" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
                <div class="four wide field">
                    <label for="banco_credito">Banco</label>
                    <div class="ui selection dropdown" id="banco_credito">
                        <input type="hidden" name="banco_credito" />
                        <div class="default text">Banco</div>
                        <i class="dropdown icon"></i>
                        <div class="menu">
                            @foreach ($bancos as $banco)
                                <div class="item" data-value="{{$banco->id}}">{{$banco->nombre}}</div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        @else
            <h4 class="ui header">Crédito</h4>
            <div class="fields">
                <div class="field">
                    <label for="valor_credito">Valor [UF]</label>
                    <div class="ui right labeled disabled input">
                        <input type="text" value="{{$format->number($venta->formaPago()->credito->pago->valor(), 2)}}" />
                        <div class="ui basic label">UF</div>
                    </div>
                </div>
                <div class="four wide field">
                    <label for="banco_credito">Banco</label>
                    <div class="ui disabled input">
                        <input type="text" value="{{$venta->formaPago()->credito->pago->banco->nombre}}" />
                    </div>
                </div>
            </div>
        @endif
        <button class="ui button">Escriturar</button>
    </form>
@endsection

@push('page_scripts')
    <script>
        const subsidio = {
            watchIds: [
                '#valor_ahorro',
                '#valor_subsidio'
            ],
            values: [0, 0],
            watch() {
                this.watchIds.forEach((id, idx) => {
                    $(id).change(event => {
                        let val = parseFloat($(event.currentTarget).val())
                        if (isNaN(val)) {
                            val = 0
                        }
                        this.values[idx] = val
                        this.update()
                    })
                })
            },
            update() {
                const total = this.values.reduce((sum, val) => sum + val, 0)
                $('#total_subsidio').val(total.toLocaleString('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2}))
            }
        }
        $(document).ready(() => {
            $('#fecha').calendar(calendar_date_options)
            $('#banco_credito').dropdown()
            $('.header.optional').click(event => {
                const elem = $(event.currentTarget)
                const name = elem.data('name')
                const icon = elem.find('.icon')
                const status = Array.from(icon[0].classList).includes('plus')
                const fields = $('#' + name)
                if (status) {
                    icon.removeClass('plus').addClass('minus')
                    fields.show()
                    return
                }
                icon.removeClass('minus').addClass('plus')
                fields.hide()
            })
            $('.fields.optional').hide()
            subsidio.watch()
            $('#escriturar_form').submit(event => {
                event.preventDefault()
                $('.ui.button').addClass('loading')
                const url = '{{$urls->api}}/venta/{{$venta->id}}/escriturar'
                const body = new FormData(event.currentTarget)
                const fecha = $('#fecha').calendar('get date')
                body.set('fecha', [fecha.getFullYear(), fecha.getMonth()+1, fecha.getDate()].join('-'))
                const $fechaPago = $('#fecha_pago')
                if ($fechaPago.length > 0) {
                    const fechaPago = $fechaPago.calendar('get date')
                    if (fechaPago !== null) {
                        body.set('fecha_pago', [fechaPago.getFullYear(), fechaPago.getMonth()+1, fechaPago.getDate()].join('-'))
                    }
                }
                const $fechaReajuste = $('#fecha_reajuste')
                if ($fechaReajuste.length > 0) {
                    const fechaReajuste = $fechaReajuste.calendar('get date')
                    if (fechaReajuste !== null) {
                        body.set('fecha_reajuste', [fechaReajuste.getFullYear(), fechaReajuste.getMonth()+1, fechaReajuste.getDate()].join('-'))
                    }
                }
                fetchAPI(url, {method: 'post', body}).then(response => {
                    $('.ui.button').removeClass('loading')
                    if (response.ok) {
                        return response.json()
                    }
                }).then(json => {
                    if (json.status) {
                        window.location = '{{$urls->base}}/venta/{{$venta->id}}'
                    }
                })
                return false
            })
            $('#fecha_pago').calendar(calendar_date_options)
            $('#fecha_reajuste').calendar(calendar_date_options)
        })
    </script>
@endpush
