@extends('ventas.promotions.base')

@section('promotions_title')
    {{ $promotion->description }}
@endsection

@section('promotions_header')
    {{ $promotion->description }}
@endsection

@section('promotions_content')
    <div class="ui card">
        <div class="content">
            <div class="description">
                <p>
                    {{ ucwords($promotion->type->name()) }} {{ ($promotion->type === Incoviba\Model\Venta\Promotion\Type::FIXED) ? $format->ufs($promotion->amount) : $format->percent($promotion->amount, 2, true) }}
                </p>
                <p>
                    {{ $promotion->startDate->format('d-m-Y') }} -> {!! $promotion->endDate?->format('d-m-Y') ?? '&infin;' !!}
                </p>
                <p>Válido hasta: {!! $promotion->validUntil?->format('d-m-Y') ?? '&empty;' !!}</p>
            </div>
        </div>
    </div>
    <div class="ui right aligned basic segment">
        <button class="ui green tertiary icon button" id="add_button">
            <i class="plus icon"></i>
        </button>
    </div>
    <div class="ui top attached tabular menu" id="tables_tab_menu">
        <div class="active item" data-tab="projects_table">Proyectos</div>
        <div class="item" data-tab="brokers_table">Operadores</div>
        <div class="item" data-tab="unit-types_table">Tipos</div>
        <div class="item" data-tab="unit-lines_table">Líneas</div>
        <div class="item" data-tab="units_table">Unidades</div>
    </div>
    <div class="ui bottom attached tab fitted segment" data-tab="projects_table"></div>
    <div class="ui bottom attached tab fitted segment" data-tab="brokers_table"></div>
    <div class="ui bottom attached tab fitted segment" data-tab="unit-types_table"></div>
    <div class="ui bottom attached tab fitted segment" data-tab="unit-lines_table"></div>
    <div class="ui bottom attached tab fitted segment" data-tab="units_table"></div>
    @include('ventas.promotions.show.add_modal')
@endsection

@push('page_scripts')
    <script>
        class ConnectionTable {
            table
            constructor(tab) {
                const parent = document.querySelector(`.ui.tab.segment[data-tab="${tab}"]`)
                this.table = document.createElement('table')
                this.table.className = 'ui table'
                this.table.innerHTML = [
                    '<thead>',
                    '<tr>',
                        '<th>Proyecto</th>',
                        '<th>Operador</th>',
                        '<th class="center aligned" colspan="3">Unidad</th>',
                    '</tr>',
                    '<tr>',
                        '<th colspan="2"></th>',
                        '<th>Tipo</th>',
                        '<th>Línea</th>',
                        '<th>#</th>',
                        '<th></th>',
                    '</tr>',
                    '</thead>',
                    '<tbody></tbody>'
                ].join("\n")
                parent.appendChild(this.table)
            }
            static fromProjects(data) {
                const table = new ConnectionTable('projects_table')
                data.forEach(project => {
                    const row = document.createElement('tr')
                    row.innerHTML = [
                        `<td>${project.descripcion}</td>`,
                        '<td>Todos los Operadores</td>',
                        '<td colspan="3">Todas las Unidades</td>',
                        `<td class="right aligned">`,
                            `<button class="ui red icon button remove_button project" data-id="${project.id}">`,
                                '<i class="plus icon"></i>',
                            '</button>',
                        `</td>`
                    ].join("\n")
                    table.table.querySelector('tbody').appendChild(row)
                })
                document.querySelectorAll('.remove_button.project').forEach(button => {
                    button.addEventListener('click', () => {
                        const project_id = button.dataset.id
                        promotion.remove().project(project_id)
                    })
                })
            }
            static fromBrokers(data) {
                const table = new ConnectionTable('brokers_table')
                data.forEach(broker => {
                    const row = document.createElement('tr')
                    row.innerHTML = [
                        `<td>Todos los Proyectos</td>`,
                        `<td>${broker.name}</td>`,
                        '<td colspan="3">Todas las Unidades</td>',
                        `<td class="right aligned">`,
                            `<button class="ui red icon button remove_button broker" data-id="${broker.rut}">`,
                                '<i class="plus icon"></i>',
                            '</button>',
                        `</td>`
                    ].join("\n")
                    table.table.querySelector('tbody').appendChild(row)
                })
                document.querySelectorAll('.remove_button.broker').forEach(button => {
                    button.addEventListener('click', () => {
                        const broker_rut = button.dataset.id
                        promotion.remove().broker(broker_rut)
                    })
                })
            }
            static fromUnitTypes(data) {
                const table = new ConnectionTable('unit-types_table')
                data.forEach(unitType => {
                    const row = document.createElement('tr')
                    const tipo = unitType.unitType.descripcion
                    row.innerHTML = [
                        `<td>${unitType.project.descripcion}</td>`,
                        '<td>Todos los Operadores</td>',
                        `<td colspan="3">Todos l@s ${tipo.charAt(0).toUpperCase() + tipo.slice(1)}s</td>`,
                        `<td class="right aligned">`,
                            `<button class="ui red icon button remove_button unit-type" data-project="${unitType.project.id}" data-id="${unitType.unitType.id}">`,
                                '<i class="plus icon"></i>',
                            '</button>',
                        `</td>`
                    ].join("\n")
                    table.table.querySelector('tbody').appendChild(row)
                })
                document.querySelectorAll('.remove_button.unit-type').forEach(button => {
                    button.addEventListener('click', () => {
                        const project_id = button.dataset.project
                        const unit_type_id = button.dataset.id
                        promotion.remove().unitType(project_id, unit_type_id)
                    })
                })
            }
            static fromUnitLines(data) {
                const table = new ConnectionTable('unit-lines_table')
                data.forEach(unitLine => {
                    const row = document.createElement('tr')
                    const tipo = unitLine.tipo_unidad.descripcion
                    row.innerHTML = [
                        `<td>${unitLine.proyecto.descripcion}</td>`,
                        '<td>Todos los Operadores</td>',
                        `<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
                        `<td colspan="2">Todas las unidades de la línea ${unitLine.nombre} - ${unitLine.tipologia}</td>`,
                        `<td class="right aligned">`,
                            `<button class="ui red icon button remove_button unit-line" data-id="${unitLine.id}">`,
                                '<i class="plus icon"></i>',
                            '</button>',
                        `</td>`
                    ].join("\n")
                    table.table.querySelector('tbody').appendChild(row)
                })
                document.querySelectorAll('.remove_button.unit-line').forEach(button => {
                    button.addEventListener('click', () => {
                        const unit_line_id = button.dataset.id
                        promotion.remove().unitLine(unit_line_id)
                    })
                })
            }
            static fromUnits(data) {
                const table = new ConnectionTable('units_table')
                data.forEach(unit => {
                    const row = document.createElement('tr')
                    const tipo = unit.proyecto_tipo_unidad.tipo_unidad.descripcion
                    row.innerHTML = [
                        `<td>${unit.proyecto_tipo_unidad.proyecto.descripcion}</td>`,
                        `<td>Todos los Operadores</td>`,
                        `<td>${tipo.charAt(0).toUpperCase() + tipo.slice(1)}</td>`,
                        `<td>${unit.proyecto_tipo_unidad.nombre} - ${unit.proyecto_tipo_unidad.tipologia}</td>`,
                        `<td>${unit.descripcion}</td>`,
                        `<td class="right aligned">`,
                            `<button class="ui red icon button remove_button unit" data-id="${unit.id}">`,
                                '<i class="plus icon"></i>',
                            '</button>',
                        `</td>`
                    ].join("\n")
                    table.table.querySelector('tbody').appendChild(row)
                })
                document.querySelectorAll('.remove_button.unit').forEach(button => {
                    button.addEventListener('click', () => {
                        const unit_id = button.dataset.id
                        promotion.remove().unit(unit_id)
                    })
                })
            }
        }
        const promotion = {
            ids: {
                table: '',
                button: {
                    add: ''
                }
            },
            handlers: {
                add: null
            },
            watch() {
                return {
                    add: () => {
                        document.getElementById(promotion.ids.button.add).addEventListener('click', clickEvent => {
                            clickEvent.preventDefault()
                            promotion.handlers.add.show()
                        })
                    }
                }
            },
            remove() {
                return {
                    project: project_id => {
                        const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/project/${project_id}`
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
                            if (json.success) {
                                window.location.reload()
                            }
                        })
                    },
                    broker: broker_rut => {
                        const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/broker/${broker_rut}`
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
                            if (json.success) {
                                window.location.reload()
                            }
                        })
                    },
                    unitType: (project_id, unit_type_id) => {
                        const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/unit-type/${project_id}/${unit_type_id}`
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
                            if (json.success) {
                                window.location.reload()
                            }
                        })
                    },
                    unitLine: unit_line_id => {
                        const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/unit-line/${unit_line_id}`
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
                            if (json.success) {
                                window.location.reload()
                            }
                        })
                    },
                    unit: unit_id => {
                        const url = `{{$urls->api}}/ventas/promotion/{{ $promotion->id }}/connections/unit/${unit_id}`
                        const method = 'delete'
                        return APIClient.fetch(url, {method}).then(response => response.json()).then(json => {
                            if (json.success) {
                                window.location.reload()
                            }
                        })
                    }
                }
            },
            execute() {},
            setup(ids) {
                this.ids = ids

                this.handlers.add = new AddModal()
                $(`#${this.ids.menu} .item`).tab()

                this.watch().add()

                @if (count($promotion->projects()) > 0)
                    ConnectionTable.fromProjects({!! json_encode($promotion->projects()) !!})
                @else
                    ConnectionTable.fromProjects([])
                @endif
                @if (count($promotion->brokers()) > 0)
                    ConnectionTable.fromBrokers({!! json_encode($promotion->brokers()) !!})
                @else
                    ConnectionTable.fromBrokers([])
                @endif
                @if (count($promotion->unitTypes()) > 0)
                    ConnectionTable.fromUnitTypes({!! json_encode($promotion->unitTypes()) !!})
                @else
                    ConnectionTable.fromUnitTypes([])
                @endif
                @if (count($promotion->unitLines()) > 0)
                    ConnectionTable.fromUnitLines({!! json_encode($promotion->unitLines()) !!})
                @else
                    ConnectionTable.fromUnitLines([])
                @endif
                @if (count($promotion->units()) > 0)
                    ConnectionTable.fromUnits({!! json_encode($promotion->units()) !!})
                @else
                    ConnectionTable.fromUnits([])
                @endif
            }
        }
        $(document).ready(() => {
            promotion.setup({
                menu: 'tables_tab_menu',
                table: 'connections',
                button: {
                    add: 'add_button'
                }
            })
        })
    </script>
@endpush
