@extends('ventas.promotions.base')

@section('promotions_content')
    <table class="ui table" id="promotions">
        <thead>
        <tr>
            <th>Promoción</th>
            <th>Tipo</th>
            <th>Valor</th>
            <th>Fecha Inicio</th>
            <th>Fecha Término</th>
            <th>Válido Hasta</th>
            <th>Contratos</th>
            <th class="right aligned">
                <button type="button" class="ui small tertiary green icon button" id="add_button">
                    <i class="plus icon"></i>
                </button>
            </th>
        </tr>
        </thead>
        <tbody>
        @foreach($promotions as $promotion)
            <tr>
                <td>
                    <a href="{{ $urls->base }}/ventas/promotion/{{ $promotion->id }}">
                        {{ $promotion->description }}
                        <i class="angle right icon"></i>
                    </a>
                </td>
                <td>{{ ucwords($promotion->type->name()) }}</td>
                <td>{{ ($promotion->type === Incoviba\Model\Venta\Promotion\Type::FIXED) ? $format->ufs($promotion->amount) : $format->percent($promotion->amount, 2, true) }}</td>
                <td>{{ $promotion->startDate->format('d-m-Y') }}</td>
                <td>{{ $promotion->endDate?->format('d-m-Y') }}</td>
                <td>{{ $promotion->validUntil?->format('d-m-Y') }}</td>
                <td>
                    Proyectos: {{ count($promotion->projects()) +
                count(array_unique(array_map(function($unitType) {return $unitType->project;},$promotion->unitTypes()))) +
                count(array_unique(array_map(function($unitLine) {return $unitLine->proyecto;},$promotion->unitLines()))) +
                count($promotion->units()) }} <br />
                    Operadores: {{ count($promotion->brokers()) }}
                </td>
                <td class="right aligned">
                    <button type="button" class="ui small tertiary icon button edit_button" data-id="{{ $promotion->id }}">
                        <i class="edit icon"></i>
                    </button>
                    <button type="button" class="ui red small tertiary icon button remove_button" data-id="{{ $promotion->id }}">
                        <i class="trash icon"></i>
                    </button>
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>
    @include('ventas.promotions.add_modal')
    @include('ventas.promotions.edit_modal')
@endsection

@push('page_scripts')
    <script>
        const promotions = {
            ids: {
                buttons: {
                    add: '',
                    edit: '',
                    remove: ''
                },
            },
            handlers: {
                add: null,
                edit: null,
            },
            data: JSON.parse('{!! json_encode($promotions) !!}'),
            execute() {
                return {
                    add: data => {
                        const url = '{{$urls->api}}/ventas/promotions/add'
                        const method = 'post'
                        const body = new FormData()
                        body.set('promotions[]', JSON.stringify(data))
                        return APIClient.fetch(url, {method, body}).then(response => {
                            if (!response) {
                                console.error(response.errors)
                                alert('No se pudo agregar promoción.')
                                return
                            }
                            return response.json().then(json => {
                                if (!json.success) {
                                    console.error(json.errors)
                                    alert('No se pudo agregar promoción.')
                                    return
                                }
                                window.location.reload()
                            })
                        })
                    },
                    edit: data => {
                        const url = '{{$urls->api}}/ventas/promotions/edit'
                        const method = 'post'
                        const body = new FormData()
                        body.set('promotions[]', JSON.stringify(data))
                        return APIClient.fetch(url, {method, body}).then(response => {
                            if (!response) {
                                console.error(response.errors)
                                alert('No se pudo editar promoción.')
                                return
                            }
                            return response.json().then(json => {
                                if (!json.success) {
                                    console.error(json.errors)
                                    alert('No se pudo editar promoción.')
                                    return
                                }
                                window.location.reload()
                            })
                        })
                    },
                    remove: promotion_id => {
                        const url = `{{$urls->api}}/ventas/promotion/${promotion_id}/remove`
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => {
                            if (!response) {
                                console.error(response.errors)
                                alert('No se pudo eliminar promoción.')
                                return
                            }
                            return response.json().then(json => {
                                if (!json.success) {
                                    console.error(json.errors)
                                    alert('No se pudo eliminar promoción.')
                                    return
                                }
                                window.location.reload()
                            })
                        })
                    }
                }
            },
            watch() {
                document.getElementById(promotions.ids.buttons.add).addEventListener('click', clickEvent => {
                    clickEvent.preventDefault()
                    promotions.handlers.add.show()
                })
                Array.from(document.getElementsByClassName(promotions.ids.buttons.edit)).forEach(button => {
                    button.addEventListener('click', clickEvent => {
                        const id = clickEvent.currentTarget.dataset.id
                        promotions.handlers.edit.load(id)
                    })
                })
                Array.from(document.getElementsByClassName(promotions.ids.buttons.remove)).forEach(button => {
                    button.addEventListener('click', clickEvent => {
                        clickEvent.preventDefault()
                        const id = clickEvent.currentTarget.dataset.id
                        promotions.execute().remove(id)
                    })
                })
            },
            setup(ids) {
                promotions.ids = ids

                promotions.handlers.add = new AddModal()
                promotions.handlers.edit = new EditModal(promotions.data)

                promotions.watch()
            }
        }
        $(document).ready(() => {
            promotions.setup({
                buttons: {
                    add: 'add_button',
                    edit: 'edit_button',
                    remove: 'remove_button'
                }
            })
        })
    </script>
@endpush
