@extends('Templates/templateAdmin')

@section('Main-content')
    <div class="row justify-content-center">
        <div class="col-12">
            <div class="row justify-content-center">
                <div class="card-body">
                    <!-- Progressbar -->
                    <ul id="progressbar" class="nav nav-pills d-flex flex-sm-row justify-content-center">
                        <li class="@if ($step == 1) active @endif flex-sm-fill"></li>
                        {{-- Project details --}}
                        <li class="@if ($step == 2) active @endif flex-sm-fill"></li>
                        {{-- Articulated --}}
                        <li class="@if ($step == 3) active @endif flex-sm-fill"></li>
                        {{-- Workstation --}}
                    </ul>
                </div>
            </div>

            <fieldset class="content">
                <div class="container-fluid">
                    <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"
                                            value="{{ $projects->company_project_description }}">
                                    </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;"
                                            value="{{ $projects->project_ispt_number }}">
                                    </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;"
                                            value="{{ $projects->project_ispt_number }}">
                                    </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;"
                                            value="{{ $projects->project_company_responsible }}">
                                    </div>
                                </div>

                                <div class="row">

                                    <div class="form-group col-sm-6" id="companyField">
                                        <label>Empresa Obra</label>
                                        {{-- <input type="text" name="user_id" class="form-control" value="{{$projects->user-}}" readonly> --}}

                                    </div>

                                    <div class="form-group col-sm-6" id="">
                                        <label>Instalação Obra</label>
                                        <input type="text" name="plant_id_present" class="form-control"
                                            value="{{ $projects->plant_id }}" readonly>
                                    </div>

                                </div>


                                <div class="row">

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

                                    <div class="form-group col-sm-6" id="installationField" hidden>
                                        <label>Instalação Nova</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 empresa">
                                    </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 Empresa</label>
                                        <input type="number" name="project_company_number" class="form-control"
                                            placeholder="Nº. de obra cliente&hellip;"
                                            value="{{ $projects->project_company_number }}">
                                    </div>

                                    <!-- Date -->
                                    <div class="form-group col-sm-6">
                                        <label>Data inicio obra:</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 type="text"
                                                value="{{ \Carbon\Carbon::parse($projects->date_started)->format('d/m/Y') }}"
                                                readonly>
                                            <input type="hidden" name="date_started_present"
                                                value="{{ $projects->date_started }}">
                                        </div>
                                    </div>

                                    <div class="form-group col-sm-6">
                                        <label>Nova data inicio obra:</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>
                </div>
                {{-- /.card card-primary --}}
                <a href="{{ route('test2', ['id' => $projects]) }}" class="btn btn-primary next float-right">Seguinte</a>

            </fieldset>

        </div>
    </div>


    <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.plant_id +
                            '">' +
                            installation.plant_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.plant_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
                        .plant_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
