@extends('Templates/templateAdmin')

@section('Main-content')

<br>
   

      <table class="table table-bordered">
        <thead>
            <tr>
                <th>Equipment ID</th>
                <th>Factory ID</th>
                <th>Equipament Type ID</th>
                <th>Tag</th>
                <th>equipment_description</th>
                <th>Serial Number</th>
                <th>Brand</th>
                <th>Model</th>
                <th>Is Active</th>
                <th>Attribute Description</th>
                <th>Attribute Value</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($equipments as $equipment)
                <tr>
                    <td>{{ $equipment->equipment_id }}</td>
                    <td>{{ $equipment->factory_id }}</td>
                    <td>{{ $equipment->equipament_type_id }}</td>
                    <td>{{ $equipment->tag }}</td>
                    <td>{{ $equipment->equipment_description }}</td>
                    <td>{{ $equipment->serial_number }}</td>
                    <td>{{ $equipment->brand }}</td>
                    <td>{{ $equipment->model }}</td>
                    <td>{{ $equipment->Is_active }}</td>
                    @if (isset($equipment->specific_attributes))
                        @foreach ($equipment->specific_attributes as $attribute)
                            @if ($loop->first)
                                <td>{{ $attribute['description'] }}</td>
                                <td>{{ $attribute['value'] }}</td>
                            @else
                                </tr><tr>
                                <td colspan="9"></td>
                                <td>{{ $attribute['description'] }}</td>
                                <td>{{ $attribute['value'] }}</td>
                            @endif
                        @endforeach
                    @else
                        <td colspan="2"></td>
                    @endif
                </tr>
            @endforeach
        </tbody>
    </table>

@endsection





















@extends('Templates/templateAdmin')

@section('Main-content')
    <!-- Content Header (Page header) -->
    <!-- /.content-header -->

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

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <br><br>


    <div class="card">
        <div class="card-body">
            <div class="container mt-5">
                <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>
                    <button type="submit" class="btn btn-primary">Enviar</button>
                </form>
                

                <br><br>
                <a id="btn-download-template" href="{{ route('download') }}" class="btn btn-warning">Baixar Template</a>

            </div>
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Equipment ID</th>
                        <th>Factory ID</th>
                        <th>Equipament Type ID</th>
                        <th>Tag</th>
                        <th>equipment_description</th>
                        <th>Serial Number</th>
                        <th>Brand</th>
                        <th>Model</th>
                        <th>Is Active</th>
                    </tr>
                </thead>
                <tbody>
                    @if(Session::has('listValves'))
                        @foreach(Session::get('listValves') as $valve)
                            <tr>
                                <td>{{ $valve->equipment_id }}</td>
                                <td>{{ $valve->factory_id }}</td>
                                <td>{{ $valve->equipament_type_id }}</td>
                                <td>{{ $valve->tag }}</td>
                                <td>{{ $valve->equipment_description }}</td>
                                <td>{{ $valve->serial_number }}</td>
                                <td>{{ $valve->brand }}</td>
                                <td>{{ $valve->model }}</td>
                                <td>{{ $valve->Is_active }}</td>
                            </tr>
                        @endforeach
                    @endif
                </tbody>
            </table>
        
        </div>
    </div>

    @endsection





    {{-- Create Project --}}



    {{-- @extends('Templates/templateAdmin')

@section('Main-content')
    <!-- Content Header (Page header) -->
    <!-- /.content-header -->
    @if (session('success'))
        <div class="alert alert-success" role="alert">
            {{ session('success') }}
        </div>
    @endif

    <div class="row justify-content-center">
        <div class="card-body">
            <!-- progressbar -->
            <ul id="progressbar" class="nav nav-pills  flex-sm-row" style=" text-align: center;">
                <li class="active flex-sm-fill">Project details</li>
                <li class="flex-sm-fill">Articulated</li>
                <li class="flex-sm-fill">Workstation</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('createProject1') }}" 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 Instalacao :</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 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> --}}
        {{-- /.card card-primary --}}
    {{-- </fieldset> --}}



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


                <!-- Table articulado da obra -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Tasks</h3>
                    </div>
                    <!-- /.card-header -->
                    <div class="card-body">
                        <div class="container mt-5">
                            <form>
                                <div class="form-group">
                                    <label for="inputDocumento">Selecione um documento:</label>
                                    <input type="file" class="form-control-file" id="inputDocumento"
                                        accept=".xlsx, .xls">
                                </div>
                                <button type="submit" class="btn btn-primary">Enviar</button>
                            </form>

                            <br><br>
                            <button id="btn-download-template" type="submit" class="btn btn-warning">Baixar
                                Template</button>

                            <div id="tabelaExcel" class="mt-5"></div>
                        </div>

                        <div id="tabelaExcel" class="mt-5"></div>
                        <div id="tabelaExcel1" class="mt-5"></div>
                        <div id="tabelaExcel2" class="mt-5"></div>


                    </div>
                    <!-- /.card-body -->
                </div>
                <!-- /. Table articulado da obra-->


            </div>
            <!-- ./Card-body -->
        </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> --}}

    {{-- <br>
    </section>

    </div>
    <!-- /.content-wrapper -->

    <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 Instalacao ?</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>
        $('#new_company_div').hide();

        $('#idDoFormulario').on('submit', function(e) {
            e.preventDefault();

            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: $(this).serialize(),
                success: function(response) {
                    if (response.success) {
                        moveToNextFieldset
                            (); // Mover para o próximo fieldset se a solicitação for bem-sucedida
                    } else {
                        // Trate o caso em que a resposta foi bem-sucedida, mas o conteúdo da resposta indica um erro.
                        // Por exemplo, você pode mostrar uma mensagem de erro.
                    }
                },
                error: function(response) {
                    // Trate o caso em que a própria solicitação falhou.
                    // Por exemplo, você pode mostrar uma mensagem de erro.
                }
            });
        });

        function moveToNextFieldset() {
            if (animating) return;

            animating = true;
            current_fs = $('.active').parent();
            next_fs = $('.active').parent().next();

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

            next_fs.show();
            current_fs.animate({
                opacity: 0
            }, {
                step: function(now, mx) {
                    scale = 1 - (1 - now) * 0.2;
                    left = (now * 50) + "%";
                    opacity = 1 - now;
                    current_fs.css({
                        'transform': 'scale(' + scale + ')',
                        'position': 'absolute'
                    });
                    next_fs.css({
                        'left': left,
                        'opacity': opacity
                    });
                },
                duration: 800,
                complete: function() {
                    current_fs.hide();
                    animating = false;
                },
                easing: 'easeInOutBack'
            });
        }
    </script> --}}

    {{-- Script Articlado --}}

    {{-- <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 --}}
