@extends('Templates/templateAdmin')

@section('Main-content')
    @if (session('success'))
        <div class="alert alert-success" role="alert">
            {{ session('success') }}
        </div>
    @endif

    <div class="row justify-content-center">

        <!-- Multiplos FieldSet -->
        <div class="col-12" id="msform">

            <div class="row justify-content-center">
                <div class="card-body">
                    <!-- Progressbar -->
                    <ul id="progressbar" class="nav nav-pills  flex-sm-row">
                        <li class="active flex-sm-fill">Detalhes do projecto</li>
                        <li class="flex-sm-fill">Articulado</li>
                        <li class="flex-sm-fill">Postos de Trabalho</li>
                    </ul>
                </div>
            </div>

            <!-- Card details project -->
            <fieldset>
                <div class="card card-primary" id="CardDetalhes">
                    <div class="card-header bg-primary text-white">
                        <h3 class="card-title mb-0">Detalhes da Obra</h3>
                    </div>

                    <div class="card-body">

                        <form method="POST" action="{{ route('processStep1') }}" id="idDoFormulario">
                            @csrf

                            <div class="row">
                                <div class="form-group col-sm-6">
                                    <label>Descrição da obra</label>
                                    <input type="text" name="description_project" class="form-control"
                                        placeholder="Descrição da obra;">
                                </div>
                                <div class="form-group col-sm-6">
                                    <label>Nº. obra ISPT</label>
                                    <input type="number" name="n_project_ispt" class="form-control"
                                        placeholder="Nº. obra ISPT&hellip;">
                                </div>
                            </div>
                            <div class="row">
                                <div class="form-group col-sm-6">
                                    <label>Responsável obra ISPT</label>
                                    <input type="text" name="responsible_project_ispt" class="form-control"
                                        placeholder="Responsável obra ISPT&hellip;">
                                </div>
                                <div class="form-group col-sm-6">
                                    <label>Responsável obra Empresa</label>
                                    <input type="text" name="responsible_project_company" class="form-control"
                                        placeholder="Responsável obra cliente&hellip;">
                                </div>
                            </div>
                            <div class="row">

                                <div class="form-group col-sm-6" id="companyField">
                                    <label>Empresa</label>
                                    <select class="form-control" name="user_id" id="company_select">
                                        <option value="#">Selecione uma Empresa...</option>
                                        @foreach ($companies as $company)
                                            <option value="{{ $company->id }}">{{ $company->name }}</option>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="form-group col-sm-6" id="installationField" hidden>
                                    <label>Instalação</label>
                                    <select class="form-control" name="installation_id" id="installationSelect">

                                        <!-- As opções de instalação serão preenchidas dinamicamente -->
                                    </select>
                                </div>

                            </div>

                            <div class="row" id="new_company_div">

                                <div class="form-group col-sm-6">
                                    <label>Nova Instalação :</label>
                                    <input type="text" id="new_company_name" class="form-control" name="new_company_name"
                                        placeholder="Digite o nome da nova Instalação">
                                </div>

                                <div class="form-group col-sm-6">
                                    <label>Nova Localização</label>
                                    <input type="text" class="form-control" name="new_company_address"
                                        placeholder="Localização...">
                                </div>
                            </div>


                            <div class="form-group" id="localization_installation_client">
                                <label>Localização</label>
                                <input type="text" class="form-control" placeholder="Localização" readonly>
                            </div>


                            <div class="row">
                                <div class="form-group col-sm-6">
                                    <label>Nº. de obra cliente</label>
                                    <input type="number" name="" class="form-control"
                                        placeholder="Nº. de obra cliente&hellip;">
                                </div>

                                <!-- Date -->
                                <div class="form-group col-sm-6">
                                    <label>Datas:</label>
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">
                                                <i class="far fa-calendar-alt"></i>
                                            </span>
                                        </div>
                                        <input name="date_started" type="datetime-local" class="form-control float-right">
                                    </div>
                                    <!-- /.input group -->
                                </div>

                            </div>
                            <!-- /.card-body -->

                            <div class="card-footer">
                                <div class="float-right">
                                    <button type="submit" class="btn btn-primary">Guardar</button>
                                </div>
                            </div>
                        </form>

                    </div>
                    {{-- /.card-body --}}

                </div>
                <input type="button" name="next" class="btn btn-primary next float-right" value="Próximo" />
                {{-- /.card card-primary --}}
            </fieldset>

            <fieldset>
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Articulado</h3>
                    </div>
                    <!-- ./Card-header -->

                    <div class="card-body">
                        <div class="container">
                            <div class="card card-success collapsed-card">
                                <div class="card-header">
                                    <h3 class="card-title">Criar Equipamentos Manualmente</h3>

                                    <div class="card-tools">
                                        <button type="button" class="btn btn-tool" data-card-widget="collapse"><i
                                                class="fas fa-plus"></i>
                                        </button>
                                    </div>
                                    <!-- /.card-tools -->
                                </div>
                                <!-- /.card-header -->
                                <div class="card-body">
                                    <div class="row">
                                        <div class="form-group col-sm-6">
                                            <label>Nº ISPT</label>
                                            <input type="text" class="form-control" placeholder="Nº ISPT...">
                                        </div>
                                        <div class="form-group col-sm-6">
                                            <label>TAG</label>
                                            <input type="text" class="form-control" placeholder="TAG equipamento...">
                                        </div>
                                    </div>
                                </div>

                            </div>
                            {{-- card card-success collapsed-card --}}



                            {{-- <form action="{{ route('createEquipamentProject') }}" method="post"
                                enctype="multipart/form-data">
                                @csrf
                                <div class="form-group">
                                    <label for="inputDocumento">Selecione um documento:</label>
                                    <input type="file" class="form-control-file" id="inputDocumento" name="documento"
                                        accept=".xlsx, .xls">
                                </div>
                            </form> --}}

                            <form action="{{ route('createEquipamentProject') }}" method="post"
                                enctype="multipart/form-data">
                                @csrf

                                <div class="row">
                                    <div class="form-group col-sm-6">
                                        <label for="exampleInputFile">Import Articulated</label>
                                        <div class="input-group">
                                            <div class="custom-file">
                                                <input type="file" class="custom-file-input" id="exampleInputFile"
                                                    name="documento" accept=".xlsx, .xls">
                                                <label class="custom-file-label" for="exampleInputFile">Choose
                                                    File</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <button type="submit" class="btn btn-primary">Enviar</button>
                                    </div>
                                </div>
                                {{-- ./row --}}

                            </form>
                            <div class="row">
                                <div class="col-sm-6"></div>
                                <div class="col-sm-6"><a id="btn-download-template" href="{{ route('download') }}"
                                        class="btn btn-info">Baixar
                                        Template</a></div>

                                <a href='#' data-toggle='modal' data-target='#modal-pedingEquipments'>
                                    <button class="btn btn-warning">Pendentes </button>
                                </a>

                            </div>


                        </div>

                        <div class="table-responsive">
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Fabrica</th>
                                        <th>Tipo de Equipamento</th>
                                        <th>Tag</th>
                                        <th>Descrição Equipamento</th>
                                        <th>Número de Serie</th>
                                        <th>Marca</th>
                                        <th>Modelo</th>
                                        <th>Editar</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if (Session::has('listValves'))
                                        @foreach (Session::get('listValves') as $valve)
                                            <tr>
                                                <td>{{ $valve->equipment_id }}</td>
                                                <td>{{ $valve->unit_id }}</td>
                                                <td>{{ $valve->equipment_type_id }}</td>
                                                <td>{{ $valve->equipment_tag }}</td>
                                                <td>{{ $valve->equipment_description }}</td>
                                                <td>{{ $valve->equipment_serial_number }}</td>
                                                <td>{{ $valve->equipment_brand }}</td>
                                                <td>{{ $valve->equipment_model }}</td>
                                                <td>Botoes Editar</td>
                                            </tr>
                                        @endforeach
                                    @endif
                                </tbody>
                            </table>
                        </div>


                    </div>
                    <!-- /.card-body -->
                    <div class="card-footer">
                        <div class="float-right">
                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </div>
                <!-- ./Card card-Primary  -->

                <input type="button" name="previous" class="btn btn-primary previous float-left" value="Previous" />
                <input type="button" name="next" class="btn btn-primary next float-right" value="Próximo" />

            </fieldset>

            <fieldset>
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Project Details</h3>
                    </div>
                    <!-- ./Card-header -->

                    <div class="card-body">

                    </div>
                    <!-- /.card-body -->
                    <div class="card-footer">
                        <div class="float-right">
                            <button type="submit" class="btn btn-primary">Save</button>
                        </div>
                    </div>
                </div>
                <!-- ./Card card-Primary  -->

                <input type="button" name="previous" class="btn btn-primary previous float-left" value="Previous" />
                <input type="button" name="next" class="btn btn-primary next float-right" value="Próximo" />
            </fieldset>

        </div>
        {{-- /.Multiplos FieldSet --}}
    </div>
    <!-- /.row justify-content-center -->

    <div class="modal fade" id="modal-pedingEquipments">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">

                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>equipment_id</th>
                                <th>unit_id</th>
                                <th>Tipo de Equipamento</th>
                                <th>Tag</th>
                                <th>Descrição Equipamento</th>
                                <th>Número de Serie</th>
                                <th>Marca</th>
                                <th>Modelo</th>
                                <th>Editar</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if (Session::has('pendingEquipments'))
                            @foreach (Session::get('pendingEquipments') as $pendingEquipment)
                                <tr>
                                    <td>{{ $pendingEquipment->pending_equipment_id }}</td>
                                    <td>{{ $pendingEquipment->pending_equipment_unit_id }}</td>
                                    <td>{{ $pendingEquipment->pending_equipment_type_id }}</td>
                                    <td>{{ $pendingEquipment->pending_equipment_tag }}</td>
                                    <td>{{ $pendingEquipment->pending_equipment_description }}</td>
                                    <td>{{ $pendingEquipment->pending_equipment_serial_number }}</td>
                                    <td>{{ $pendingEquipment->pending_equipment_brand }}</td>
                                    <td>{{ $pendingEquipment->pending_equipment_model }}</td>
                                    <td>Botoes Editar</td>
                                </tr>
                            @endforeach
                        @endif
                        
                        </tbody>
                    </table>
                </div>
                {{-- ./table-responsive --}}
                
            </div>
            {{-- ./modal-content --}}
        </div>
        
    </div>

    <script>
        @if (Session::has('pendingEquipments'))
            $(function() {
                $('#model-pedingEquipments').modal('show');
            });
        @endif
    </script>
   


    <script>
        $(document).ready(function() {

            var installationsData; // Esta variável irá armazenar as informações das instalações
            $('#company_select').change(function() {
                var user_id = $(this).val();

                if (user_id == '#') {
                    $('#installationField').attr('hidden', 'hidden');
                    $('#localization_installation_client').hide();
                    $('#new_company_div').hide();
                    return;
                }

                $.get('/api/installations?user_id=' + user_id, function(data) {

                    var select = $('#installationSelect');
                    select.empty();

                    // Adicione as opções fixas aqui
                    select.append('<option value="#">Selecione uma instalação...</option>');
                    select.append(
                        '<option value="new_install">Criar uma nova Instalação ?</option>');

                    // Agora você pode adicionar suas opções dinâmicas.
                    $.each(data, function(index, installation) {

                        select.append('<option value="' + installation.installation_id +
                            '">' +
                            installation.installation_name + '</option>');
                    });
                    // Armazene os dados em installationsData
                    installationsData = data;

                    $('#installationField').removeAttr('hidden');
                });
            });
            // Adicione este código para lidar com a mudança na seleção da instalação
            $('#installationSelect').change(function() {
                if (this.value == 'new_install') {
                    $('#new_company_div').show();
                    $('#localization_installation_client').hide();
                    return;
                }
                $('#new_company_div').hide();
                $('#localization_installation_client').show();

                if (this.value == '#') {
                    $('#new_company_div').hide();
                    $('#localization_installation_client').hide();
                    return;
                }

                // Verifique se installationsData está definido
                if (installationsData) {
                    // Encontre a instalação selecionada nos dados da instalação
                    var selectedInstallation = installationsData.find(function(installation) {
                        return installation.installation_id == this.value;
                    }.bind(this));

                    if (selectedInstallation) {
                        // Preencha o valor do campo de endereço com o endereço da instalação selecionada
                        $('#localization_installation_client input').val(selectedInstallation.address);
                    }
                }
            });

            $('#localization_installation_client').hide();
            $('#new_company_div').hide();
        });
    </script>

    <script>
        // Atribua a URL ao atributo formaction do botão
        document.getElementById('btn-download-template').setAttribute('formaction', downloadUrl);

        (function() {
            const tabelaExcel1 = document.getElementById('tabelaExcel1');

            function handleFormSubmit(event) {
                event.preventDefault(); // Previne o comportamento padrão do formulário
                const inputFile = document.getElementById('inputDocumento').files[0];
                const reader = new FileReader();
                reader.readAsBinaryString(inputFile);
                reader.onload = function() {
                    const fileData = reader.result;
                    const workbook = XLSX.read(fileData, {
                        type: 'binary'
                    });
                    const worksheet1 = workbook.Sheets[workbook.SheetNames[0]];
                    const tableData1 = XLSX.utils.sheet_to_json(worksheet1);
                    const tabelaHtml1 = criarTabelaHtml(tableData1);
                    const tabelaExcel1 = document.getElementById('tabelaExcel1');
                    if (tabelaExcel1 !== null) {
                        tabelaExcel1.innerHTML = tabelaHtml1;
                    }
                };
            }

            function criarTabelaHtml(dados) {

                const colunasObj = dados[2];
                const colunasheader = Object.keys(colunasObj).map(key =>
                    colunasObj[key]);

                console.log(dados);

                const colunasHtml = colunasheader.map(coluna => `<th>${coluna}</th>`).join('');

                const colunas = Object.keys(dados[2]);

                const linhasHtml = dados
                    .slice(3)
                    .map(linha => {
                        const celulasHtml = colunas.map(coluna => {
                            const valor = linha[coluna] !== undefined ? linha[coluna] : 'NULL';
                            return `<td>${valor}</td>`;
                        }).join('');
                        return `<tr>${celulasHtml}</tr>`;
                    })
                    .join('');

                // console.log()
                return `
                    <table class="table table-bordered">
                    <thead>
                        <tr>${colunasHtml}</tr>
                    </thead>
                    <tbody>
                        ${linhasHtml}
                    </tbody>
                    </table>
                `;
            }

            const form = document.querySelector('form');
            form.addEventListener('submit', handleFormSubmit);
        })();
    </script>

@endsection

{{-- Script ProgressBar --}}
@section('scripts')
    <script>
        //jQuery time
        var current_fs, next_fs, previous_fs; //fieldsets
        var left, opacity, scale; //fieldset properties which we will animate
        var animating; //flag to prevent quick multi-click glitches

        $(".next").click(function() {
            if (animating) return false;
            animating = true;

            current_fs = $(this).parent();
            next_fs = $(this).parent().next();

            $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

            current_fs.animate({
                opacity: 0
            }, 800, function() {
                current_fs.hide();
                next_fs.show();
                next_fs.css({
                    'opacity': 1
                });
                animating = false;
            });
        });

        $(".previous").click(function() {
            if (animating) return false;
            animating = true;

            current_fs = $(this).parent();
            previous_fs = $(this).parent().prev();

            $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

            current_fs.animate({
                opacity: 0
            }, 800, function() {
                current_fs.hide();
                previous_fs.show();
                previous_fs.css({
                    'opacity': 1
                });
                animating = false;
            });
        });
    </script>
@endsection
