@extends('proyectos.brokers.base')

@section('brokers_title')
    {{ $broker->name }}
@endsection

@section('brokers_header')
    {{ $broker->name }}
@endsection

@section('brokers_content')
    <div class="ui compact segment">
        <b>RUT:</b> {{ $broker->rutFull() }} <br />
        <b>Razón Social:</b> {{ $broker->data()?->legalName }}
    </div>
    @if ($broker->data()?->representative->name !== null)
        <div class="ui card">
            <div class="content">
                <div class="header">
                    Contacto
                </div>
                <div class="description">
                    Nombre: {{ $broker->data()?->representative?->name }}<br />
                    Email: {{ $broker->data()?->representative?->email }}<br />
                    Teléfono: {{ $broker->data()?->representative?->phone }}<br />
                    Dirección: {{ $broker->data()?->representative?->address }}
                </div>
            </div>
        </div>
    @endif
    <table class="ui table">
        <thead>
        <tr>
            <th>Proyecto</th>
            <th>Comisión</th>
            <th>Fecha Inicio</th>
            <th class="right aligned">
                <button type="button" class="ui small tertiary green icon button" id="add_contract_button">
                    <i class="plus icon"></i>
                </button>
            </th>
        </tr>
        </thead>
        <tbody id="contracts">
        @foreach($broker->contracts() as $contract)
            <tr>
                <td>
                    <a href="{{ $urls->base }}/proyectos/broker/{{ $broker->rut }}/contract/{{ $contract->id }}">
                        {{ $contract->project->descripcion }}
                        <i class="angle right icon"></i>
                    </a>
                </td>
                <td>{{ $format->percent($contract->commission, 2, true) }}</td>
                <td>{{ $contract->current()->date->format('d-m-Y') }}</td>
                <td class="right aligned">
                    <button type="button" class="ui small tertiary red icon button remove_button" data-index="{{$contract->id}}">
                        <i class="remove icon"></i>
                    </button>
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>

    @include('proyectos.brokers.show.add_modal')
@endsection

@include('layout.body.scripts.datatables')

@push('page_scripts')
    <script>
        const brokerHandler = {
            ids: {
                buttons: {
                    add: '',
                    remove: ''
                }
            },
            modals: {
                add: null,
            },
            execute() {
                return {
                    add: data => {
                        const url = '{{ $urls->api }}/proyectos/broker/{{ $broker->rut }}/contracts/add'
                        const method = 'post'
                        const body = new FormData()
                        body.set('contracts[]', JSON.stringify(data))
                        return APIClient.fetch(url, {method, body}).then(response => {
                            if (!response) {
                                console.error(response.errors)
                                alert('No se pudo agregar contrato.')
                                return
                            }
                            return response.json().then(json => {
                                if (!json.success) {
                                    console.error(json.errors)
                                    alert('No se pudo agregar contrato.')
                                    return
                                }
                                window.location.reload()
                            })
                        })
                    },
                    remove: index => {
                        const url = `{{ $urls->api }}/proyectos/brokers/contract/${index}`
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => {
                            if (!response) {
                                console.error(response.errors)
                                alert('No se pudo eliminar contrato.')
                                return
                            }
                            return response.json().then(json => {
                                if (!json.success) {
                                    console.error(json.errors)
                                    alert('No se pudo eliminar contrato.')
                                    return
                                }
                                window.location.reload()
                            })
                        })
                    }
                }
            },
            events() {
                return {
                    add: clickEvent => {
                        clickEvent.preventDefault()
                        brokerHandler.modals.add.show()
                    },
                    remove: clickEvent => {
                        clickEvent.preventDefault()
                        const index = $(clickEvent.currentTarget).data('index')
                        brokerHandler.execute().remove(index)
                    }
                }
            },
            buttonWatch() {
                document.getElementById(brokerHandler.ids.buttons.add).addEventListener('click', brokerHandler.events().add)
                Array.from(document.getElementsByClassName(brokerHandler.ids.buttons.remove)).forEach(button => {
                    button.addEventListener('click', brokerHandler.events().remove)
                })
            },
            setup(ids) {
                brokerHandler.ids = ids
                brokerHandler.buttonWatch()

                this.modals.add = new AddModal(brokerHandler)
                const dto = structuredClone(datatables_defaults)
                dto.order = [[0, 'asc']]
                dto.columnDefs = [
                    {
                        targets: 3,
                        orderable: false
                    }
                ]
                $('#contracts').parent().DataTable(dto)
            }
        }
        $(document).ready(() => {
            brokerHandler.setup({
                buttons: {
                    add: 'add_contract_button',
                    remove: 'remove_button'
                }
            })
        })
    </script>
@endpush
