<?php
$api_url = 'http://localhost/jps-service/backend/routers/contrato_maquina.php';
$data = json_decode(file_get_contents($api_url), true);

// Função para formatar valores se necessário
function formatValue($value) {
    if (is_numeric($value)) {
        return number_format(floatval($value), 2, ',', '.');
    }
    return $value;
}
?>
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestão de Contrato Maquina</title>
    <link rel="stylesheet" type="text/css"
        href="https://cdn.datatables.net/v/bs5/jq-3.6.0/dt-1.11.5/datatables.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
    .btn-action {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
        line-height: 1.5;
    }

    .modal-lg-custom {
        max-width: 800px;
    }
    </style>
</head>

<body>
    <div class="container-fluid mt-4">
        <h1 class="mb-4">Gestão de Contrato Maquina</h1>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Lista de Contrato Maquina</h5>
                <div>
                    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#cadastrarModal">
                        <i class="fas fa-plus me-1"></i> Novo Registro
                    </button>
                </div>
            </div>
            <div class="card-body">
                <table id="dataTable" class="table table-striped table-bordered nowrap" style="width:100%">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Modelo</th>
                            <th>Equipamento</th>
                            <th>Serie</th>
                            <th>Cidade</th>
                            <th>Uf</th>
                            <th>Setor Area</th>
                            <th>Situacao</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($data as $item): ?>
                        <tr>
                            <td><?= formatValue($item["id"]) ?></td>
                            <td><?= formatValue($item["modelo"]) ?></td>
                            <td><?= formatValue($item["equipamento"]) ?></td>
                            <td><?= formatValue($item["serie"]) ?></td>
                            <td><?= formatValue($item["cidade"]) ?></td>
                            <td><?= formatValue($item["uf"]) ?></td>
                            <td><?= formatValue($item["setor_area"]) ?></td>
                            <td><?= formatValue($item["situacao"]) ?></td>
                            <td>
                                <button class="btn btn-info btn-action btn-view" data-id="<?= $item["id"] ?>">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-warning btn-action btn-edit" data-id="<?= $item["id"] ?>">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-danger btn-action btn-delete" data-id="<?= $item["id"] ?>">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal Visualizar -->
    <div class="modal fade" id="viewModal" tabindex="-1" aria-labelledby="viewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-lg-custom">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewModalLabel">Detalhes</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewModalBody">
                    <!-- Conteúdo será preenchido via AJAX -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Editar -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-lg-custom">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">Editar</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="editForm" method="POST">
                    <div class="modal-body" id="editModalBody">
                        <!-- Conteúdo será preenchido via AJAX -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">Salvar Alterações</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Excluir -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">Confirmar Exclusão</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Você tem certeza que deseja excluir este registro? Esta ação não pode ser desfeita.</p>
                    <input type="hidden" id="deleteId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="button" class="btn btn-danger" id="confirmDelete">Excluir</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Cadastrar -->
    <div class="modal fade" id="cadastrarModal" tabindex="-1" aria-labelledby="cadastrarModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-lg-custom">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="cadastrarModalLabel">Cadastrar Novo</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="cadastrarForm" method="POST">
                    <div class="modal-body">
                        <div class="row g-3">

                            <div class="col-md-6">
                                <label for="fk_contrato" class="form-label">Fk Contrato</label>
                                <input type="text" class="form-control" id="fk_contrato" name="fk_contrato" required>
                            </div>

                            <div class="col-md-6">
                                <label for="fk_matriz" class="form-label">Fk Matriz</label>
                                <input type="text" class="form-control" id="fk_matriz" name="fk_matriz" required>
                            </div>

                            <div class="col-md-6">
                                <label for="fk_nome_matriz" class="form-label">Fk Nome Matriz</label>
                                <input type="text" class="form-control" id="fk_nome_matriz" name="fk_nome_matriz"
                                    required>
                            </div>

                            <div class="col-md-6">
                                <label for="site_filial" class="form-label">Site Filial</label>
                                <input type="text" class="form-control" id="site_filial" name="site_filial" required>
                            </div>

                            <div class="col-md-6">
                                <label for="modelo" class="form-label">Modelo</label>
                                <input type="text" class="form-control" id="modelo" name="modelo" required>
                            </div>

                            <div class="col-md-6">
                                <label for="equipamento" class="form-label">Equipamento</label>
                                <input type="text" class="form-control" id="equipamento" name="equipamento" required>
                            </div>

                            <div class="col-md-6">
                                <label for="serie" class="form-label">Serie</label>
                                <input type="text" class="form-control" id="serie" name="serie" required>
                            </div>

                            <div class="col-md-6">
                                <label for="endereco" class="form-label">Endereco</label>
                                <input type="text" class="form-control" id="endereco" name="endereco" required>
                            </div>

                            <div class="col-md-6">
                                <label for="numero" class="form-label">Numero</label>
                                <input type="text" class="form-control" id="numero" name="numero" required>
                            </div>

                            <div class="col-md-6">
                                <label for="bairro" class="form-label">Bairro</label>
                                <input type="text" class="form-control" id="bairro" name="bairro" required>
                            </div>

                            <div class="col-md-6">
                                <label for="cidade" class="form-label">Cidade</label>
                                <input type="text" class="form-control" id="cidade" name="cidade" required>
                            </div>

                            <div class="col-md-6">
                                <label for="uf" class="form-label">Uf</label>
                                <input type="text" class="form-control" id="uf" name="uf" required>
                            </div>

                            <div class="col-md-6">
                                <label for="setor_area" class="form-label">Setor Area</label>
                                <input type="text" class="form-control" id="setor_area" name="setor_area" required>
                            </div>

                            <div class="col-md-6">
                                <label for="ip_number" class="form-label">Ip Number</label>
                                <input type="text" class="form-control" id="ip_number" name="ip_number" required>
                            </div>

                            <div class="col-md-6">
                                <label for="situacao" class="form-label">Situacao</label>
                                <input type="text" class="form-control" id="situacao" name="situacao" required>
                            </div>

                            <div class="col-md-6">
                                <label for="obs" class="form-label">Obs</label>
                                <input type="text" class="form-control" id="obs" name="obs" required>
                            </div>

                            <div class="col-md-6">
                                <label for="googlemaps_point" class="form-label">Googlemaps Point</label>
                                <input type="text" class="form-control" id="googlemaps_point" name="googlemaps_point"
                                    required>
                            </div>

                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">Cadastrar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- jQuery, Bootstrap e DataTables JS -->
    <script type="text/javascript" src="https://cdn.datatables.net/v/bs5/jq-3.6.0/dt-1.11.5/datatables.min.js"></script>
    <!-- Excel export -->
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.html5.min.js"></script>

    <script>
    $(document).ready(function() {
        // Inicialização do DataTable com botão de exportação
        var table = $('#dataTable').DataTable({
            responsive: true,
            dom: 'Bfrtip',
            buttons: [{
                extend: 'excel',
                text: '<i class="fas fa-file-excel me-1"></i> Exportar Excel',
                className: 'btn btn-success btn-sm',
                title: 'Contrato Maquina',
                exportOptions: {
                    columns: ':not(:last-child)' // Exclui a coluna de ações
                }
            }],
            language: {
                url: 'https://cdn.datatables.net/plug-ins/1.11.5/i18n/pt-BR.json'
            }
        });

        // Visualizar registro
        $(document).on('click', '.btn-view', function() {
            var id = $(this).data('id');
            $.ajax({
                url: '<?= $api_url ?>?id=' + id,
                type: 'GET',
                dataType: 'json',
                success: function(item) {
                    var html = '<div class="row">';
                    html += `
                            <div class="col-md-6">
                                <p><strong>Id:</strong> ${item['id'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Fk Contrato:</strong> ${item['fk_contrato'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Fk Matriz:</strong> ${item['fk_matriz'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Fk Nome Matriz:</strong> ${item['fk_nome_matriz'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Site Filial:</strong> ${item['site_filial'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Modelo:</strong> ${item['modelo'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Equipamento:</strong> ${item['equipamento'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Serie:</strong> ${item['serie'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Endereco:</strong> ${item['endereco'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Numero:</strong> ${item['numero'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Bairro:</strong> ${item['bairro'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Cidade:</strong> ${item['cidade'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Uf:</strong> ${item['uf'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Setor Area:</strong> ${item['setor_area'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Ip Number:</strong> ${item['ip_number'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Situacao:</strong> ${item['situacao'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Obs:</strong> ${item['obs'] || 'N/A'}</p>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <p><strong>Googlemaps Point:</strong> ${item['googlemaps_point'] || 'N/A'}</p>
                            </div>
                        `;
                    html += '</div>';
                    $('#viewModalBody').html(html);
                    $('#viewModal').modal('show');
                },
                error: function(xhr, status, error) {
                    alert('Erro ao carregar registro: ' + error);
                }
            });
        });

        // Editar registro - Abrir modal
        $(document).on('click', '.btn-edit', function() {
            var id = $(this).data('id');
            $.ajax({
                url: '<?= $api_url ?>?id=' + id,
                type: 'GET',
                dataType: 'json',
                success: function(item) {
                    var html = '<input type="hidden" name="id" value="' + item.id + '">';
                    html += '<div class="row g-3">';
                    html += `
                            <div class="col-md-6">
                                <label for="edit_fk_contrato" class="form-label">Fk Contrato</label>
                                <input type="text" class="form-control" id="edit_fk_contrato" name="fk_contrato" value="${item['fk_contrato'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_fk_matriz" class="form-label">Fk Matriz</label>
                                <input type="text" class="form-control" id="edit_fk_matriz" name="fk_matriz" value="${item['fk_matriz'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_fk_nome_matriz" class="form-label">Fk Nome Matriz</label>
                                <input type="text" class="form-control" id="edit_fk_nome_matriz" name="fk_nome_matriz" value="${item['fk_nome_matriz'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_site_filial" class="form-label">Site Filial</label>
                                <input type="text" class="form-control" id="edit_site_filial" name="site_filial" value="${item['site_filial'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_modelo" class="form-label">Modelo</label>
                                <input type="text" class="form-control" id="edit_modelo" name="modelo" value="${item['modelo'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_equipamento" class="form-label">Equipamento</label>
                                <input type="text" class="form-control" id="edit_equipamento" name="equipamento" value="${item['equipamento'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_serie" class="form-label">Serie</label>
                                <input type="text" class="form-control" id="edit_serie" name="serie" value="${item['serie'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_endereco" class="form-label">Endereco</label>
                                <input type="text" class="form-control" id="edit_endereco" name="endereco" value="${item['endereco'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_numero" class="form-label">Numero</label>
                                <input type="text" class="form-control" id="edit_numero" name="numero" value="${item['numero'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_bairro" class="form-label">Bairro</label>
                                <input type="text" class="form-control" id="edit_bairro" name="bairro" value="${item['bairro'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_cidade" class="form-label">Cidade</label>
                                <input type="text" class="form-control" id="edit_cidade" name="cidade" value="${item['cidade'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_uf" class="form-label">Uf</label>
                                <input type="text" class="form-control" id="edit_uf" name="uf" value="${item['uf'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_setor_area" class="form-label">Setor Area</label>
                                <input type="text" class="form-control" id="edit_setor_area" name="setor_area" value="${item['setor_area'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_ip_number" class="form-label">Ip Number</label>
                                <input type="text" class="form-control" id="edit_ip_number" name="ip_number" value="${item['ip_number'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_situacao" class="form-label">Situacao</label>
                                <input type="text" class="form-control" id="edit_situacao" name="situacao" value="${item['situacao'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_obs" class="form-label">Obs</label>
                                <input type="text" class="form-control" id="edit_obs" name="obs" value="${item['obs'] || ''}" required>
                            </div>
                        `;
                    html += `
                            <div class="col-md-6">
                                <label for="edit_googlemaps_point" class="form-label">Googlemaps Point</label>
                                <input type="text" class="form-control" id="edit_googlemaps_point" name="googlemaps_point" value="${item['googlemaps_point'] || ''}" required>
                            </div>
                        `;
                    html += '</div>';
                    $('#editModalBody').html(html);
                    $('#editModal').modal('show');
                },
                error: function(xhr, status, error) {
                    alert('Erro ao carregar registro para edição: ' + error);
                }
            });
        });

        // Submit do formulário de edição
        $('#editForm').submit(function(e) {
            e.preventDefault();
            var id = $('input[name="id"]').val();
            var formData = {
                "fk_contrato": $("#edit_fk_contrato").val(),
                "fk_matriz": $("#edit_fk_matriz").val(),
                "fk_nome_matriz": $("#edit_fk_nome_matriz").val(),
                "site_filial": $("#edit_site_filial").val(),
                "modelo": $("#edit_modelo").val(),
                "equipamento": $("#edit_equipamento").val(),
                "serie": $("#edit_serie").val(),
                "endereco": $("#edit_endereco").val(),
                "numero": $("#edit_numero").val(),
                "bairro": $("#edit_bairro").val(),
                "cidade": $("#edit_cidade").val(),
                "uf": $("#edit_uf").val(),
                "setor_area": $("#edit_setor_area").val(),
                "ip_number": $("#edit_ip_number").val(),
                "situacao": $("#edit_situacao").val(),
                "obs": $("#edit_obs").val(),
                "googlemaps_point": $("#edit_googlemaps_point").val()
            };

            $.ajax({
                url: '<?= $api_url ?>?id=' + id,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    alert('Registro atualizado com sucesso!');
                    $('#editModal').modal('hide');
                    location.reload();
                },
                error: function(xhr, status, error) {
                    alert('Erro ao atualizar o registro: ' + (xhr.responseJSON?.error ||
                        error));
                }
            });
        });

        // Excluir registro
        $(document).on('click', '.btn-delete', function() {
            var id = $(this).data('id');
            $('#deleteId').val(id);
            $('#deleteModal').modal('show');
        });

        // Confirmar exclusão
        $('#confirmDelete').click(function() {
            var id = $('#deleteId').val();

            $.ajax({
                url: '<?= $api_url ?>?id=' + id,
                type: 'DELETE',
                success: function(response) {
                    alert('Registro excluído com sucesso!');
                    $('#deleteModal').modal('hide');
                    location.reload();
                },
                error: function(xhr, status, error) {
                    alert('Erro ao excluir o registro: ' + (xhr.responseJSON?.error ||
                        error));
                }
            });
        });

        // Submit do formulário de cadastro
        $('#cadastrarForm').submit(function(e) {
            e.preventDefault();
            var formData = {
                "fk_contrato": $("#fk_contrato").val(),
                "fk_matriz": $("#fk_matriz").val(),
                "fk_nome_matriz": $("#fk_nome_matriz").val(),
                "site_filial": $("#site_filial").val(),
                "modelo": $("#modelo").val(),
                "equipamento": $("#equipamento").val(),
                "serie": $("#serie").val(),
                "endereco": $("#endereco").val(),
                "numero": $("#numero").val(),
                "bairro": $("#bairro").val(),
                "cidade": $("#cidade").val(),
                "uf": $("#uf").val(),
                "setor_area": $("#setor_area").val(),
                "ip_number": $("#ip_number").val(),
                "situacao": $("#situacao").val(),
                "obs": $("#obs").val(),
                "googlemaps_point": $("#googlemaps_point").val()
            };

            $.ajax({
                url: '<?= $api_url ?>',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(response) {
                    alert('Registro cadastrado com sucesso!');
                    $('#cadastrarModal').modal('hide');
                    location.reload();
                },
                error: function(xhr, status, error) {
                    alert('Erro ao cadastrar o registro: ' + (xhr.responseJSON?.error ||
                        error));
                }
            });
        });
    });
    </script>
</body>

</html>