@extends('proyectos.brokers.base')

@section('brokers_content')
    <table id="brokers" class="ui table">
        <thead>
        <tr>
            <th>RUT</th>
            <th>Nombre</th>
            <th>Contacto</th>
            <th>Contratos</th>
            <th class="right aligned">
                <button class="ui small tertiary green icon button" id="add_button">
                    <i class="plus icon"></i>
                </button>
            </th>
        </tr>
        </thead>
        @foreach($brokers as $broker)
            <tr>
                <td class="top aligned">
                    <span
                            @if ($broker->data()?->legalName !== '')
                                data-tooltip="{{ $broker->data()?->legalName }}" data-position="right center"
                    @endif
                    >
                        {{$broker->rutFull()}}
                    </span>
                </td>
                <td class="top aligned">
                    <a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}">
                        {{$broker->name}}
                        <i class="angle right icon"></i>
                    </a>
                </td>
                <td class="top aligned">
                    <span
                    @if ($broker->data()?->representative?->email !== '' || $broker->data()?->representative?->phone !== '')
                            data-tooltip="{{ ($broker->data()?->representative?->email !== '') ? "Email: " . $broker->data()?->representative?->email : '' }}{{ ($broker->data()?->representative?->phone !== '') ? ' Teléfono: ' . $broker->data()?->representative?->phone : '' }}" data-position="right center"
                    @endif
                    >
                        {{ $broker->data()?->representative?->name }}
                    </span>
                </td>
                <td class="top aligned">
                    <div class="ui list">
                        @foreach($broker->contracts() as $contract)
                            <div class="item">
                                <a href="{{$urls->base}}/proyectos/broker/{{$broker->rut}}/contract/{{$contract->id}}" data-tooltip="{{$contract->current()->date->format('d-m-Y')}}" data-position="right center">
                                    {{$contract->project->descripcion}} ({{$format->percent($contract->commission, 2, true)}})
                                </a>
                            </div>
                        @endforeach
                    </div>
                </td>
                <td class="top aligned right aligned">
                    <button class="ui small tertiary icon button edit_button" data-index="{{$broker->rut}}">
                        <i class="edit icon"></i>
                    </button>
                    <button class="ui small tertiary red icon button remove_button" data-index="{{$broker->rut}}">
                        <i class="remove icon"></i>
                    </button>
                </td>
            </tr>
        @endforeach
    </table>
    @include('proyectos.brokers.add_modal')
    @include('proyectos.brokers.edit_modal')
@endsection

@push('page_scripts')
    <script>
        function storeBrokers() {
            localStorage.setItem('brokers',  '{!! json_encode(array_map(function($broker) {
                                                        $arr = json_decode(json_encode($broker), true);
                                                        array_walk_recursive($arr, function(&$val, $key) {
                                                            if ($val === null) {
                                                                $val = '';
                                                            }
                                                        });
                                                        $arr['contracts'] = $broker->contracts();
                                                        return $arr;
                                                }, $brokers)) !!}')
        }
        const brokersHandler = {
            ids: {
                buttons: {
                    add: 'add_button',
                    edit: 'edit_button',
                    remove: 'remove_button'
                },
                modals: {
                    add: '',
                    edit: ''
                },
                forms: {
                    add: '',
                    edit: ''
                }
            },
            modals: {
                add: null,
                edit: null
            },
            events() {
                return {
                    add: clickEvent => {
                        clickEvent.preventDefault()
                        brokersHandler.actions().add()
                    },
                    edit: clickEvent => {
                        clickEvent.preventDefault()
                        const broker_rut = parseInt(clickEvent.currentTarget.dataset.index)
                        brokersHandler.actions().edit(broker_rut)
                    },
                    delete: clickEvent => {
                        clickEvent.preventDefault()
                        const broker_rut = clickEvent.currentTarget.dataset.index
                        brokersHandler.actions().delete(broker_rut)
                    }
                }
            },
            buttonWatch() {
                document.getElementById(brokersHandler.ids.buttons.add).addEventListener('click', brokersHandler.events().add)
                Array.from(document.getElementsByClassName(brokersHandler.ids.buttons.edit)).forEach(button => {
                    button.addEventListener('click', brokersHandler.events().edit)
                })
                Array.from(document.getElementsByClassName(brokersHandler.ids.buttons.remove)).forEach(button => {
                    button.addEventListener('click', brokersHandler.events().delete)
                })
            },
            actions() {
                return {
                    add: () => {
                        this.modals.add.show()
                    },
                    edit: broker_rut => {
                        const localData = JSON.parse(localStorage.getItem('brokers'))
                        const broker = localData.find(broker => broker.rut === broker_rut)
                        const data = {
                            rut: broker_rut,
                            name: broker.name,
                            legal_name: broker.data?.legal_name || '',
                            contact: broker.data?.representative?.name || '',
                            email: broker.data?.representative?.email || '',
                            phone: broker.data?.representative?.phone || '',
                            address: broker.data?.representative?.address || '',
                            contracts: broker.contracts
                        }
                        this.modals.edit.load(data)
                    },
                    delete: broker_rut => {
                        brokersHandler.execute().delete(broker_rut)
                    }
                }
            },
            execute() {
                return {
                    add: data => {
                        const url = '{{$urls->api}}/proyectos/brokers/add'
                        const method = 'post'
                        const body = new FormData()
                        body.append('brokers[]', JSON.stringify(data))
                        return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
                            if (!json.success) {
                                console.error(json.errors)
                                alert('No se pudo agregar operador.')
                                return
                            }
                            window.location.reload()
                        })
                    },
                    edit: data => {
                        const url = '{{$urls->api}}/proyectos/brokers/edit'
                        const method = 'post'
                        const body = new FormData()
                        body.append('brokers[]', JSON.stringify(data))
                        return APIClient.fetch(url, {method, body}).then(response => response.json()).then(json => {
                            if (!json.success) {
                                console.error(json.errors)
                                alert('No se pudo editar operador.')
                                return
                            }
                            window.location.reload()
                        })
                    },
                    delete: broker_rut => {
                        const url = '{{$urls->api}}/proyectos/broker/' + broker_rut
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
                            if (!json.success) {
                                console.error(json.errors)
                                alert('No se pudo eliminar operador.')
                                return
                            }
                            window.location.reload()
                        })
                    }
                }
            },
            setup(ids) {
                brokersHandler.ids = ids
                brokersHandler.buttonWatch()

                this.modals.add = new AddModal(brokersHandler)
                this.modals.edit = new EditModal(brokersHandler)
            }
        }
        $(document).ready(() => {
            storeBrokers()
            brokersHandler.setup({
                buttons: {
                    add: 'add_button',
                    edit: 'edit_button',
                    remove: 'remove_button',
                },
            })
        })
    </script>
@endpush
