<?php 
session_start();
if(!isset($_SESSION['idUsuario'])){
    header("location:../../");
}
error_reporting(E_ALL);
include '../../conexao/index.php';

$_SESSION['idUsuario'] = $_SESSION['idUsuario'];
$_SESSION['nomeUsuario'] = $_SESSION['nomeUsuario'];
$_SESSION['categoriaUsuario'] = $_SESSION['categoriaUsuario']; 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include 'includes/head.php'; ?>
    <style>
        /* Ajusta a tabela para ocupar toda a largura disponível */
        .table-responsive {
            width: 100%;
            overflow-x: auto;
        }
        table#example {
            width: 100%;
        }
    </style>
</head>

<body>
    <div class="main-wrapper">
        <div class="header">
            <?php include 'includes/header.php' ?>
        </div>
        <div class="sidebar" id="sidebar">
            <?php include 'includes/side_bar.php'; ?>
        </div>
        <div class="page-wrapper">
            <div class="content">
                <div class="row">
                    <div class="col-sm-4 col-3">
                        <h4 class="page-title">Despesas</h4>
                    </div>
                    <div class="col-sm-8 col-9 text-right m-b-20">
                        <a href="nova_despesa.php" class="btn btn-primary btn-rounded float-right"><i class="fa fa-plus"></i> Nova Despesa</a>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="table-responsive">
                            <table id="example" class="display">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Descrição</th>
                                        <th>Categoria</th>
                                        <th>Valor</th>
                                        <th>Data de Vencimento</th>
                                        <th>Status</th>
                                        <th class="text-right">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    
                                    
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div>

    </div>
    <div class="sidebar-overlay" data-reff=""></div>
    <?php include 'includes/footer_plugins.php'; ?>
    <!-- Modal de Edição -->
    <div id="editModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">Alterar Status da Despesa</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <input type="hidden" id="despesa_id" name="id">
                        <div class="form-group">
                            <label for="status">Status</label>
                            <select id="status" name="status" class="form-control">
                                <option value="Pago">Pago</option>
                                <option value="Pendente">Pendente</option>
                                <option value="Cancelado">Cancelado</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
                    <button type="button" class="btn btn-primary" id="saveChanges">Salvar Alterações</button>
                </div>
            </div>
        </div>
    </div>
    <style>
    .status-pago {
        color: white;
        background-color: green;
        padding: 5px;
        border-radius: 5px;
    }
    .status-pendente {
        color: black;
        background-color: yellow;
        padding: 5px;
        border-radius: 5px;
    }
    .status-cancelado {
        color: white;
        background-color: red;
        padding: 5px;
        border-radius: 5px;
    }
</style>
</body>


<link href="../datatables.min.css" rel="stylesheet"/>
    <script src="../datatables.min.js"></script>
    <script type="text/javascript" src="../js/data-table-act.js"></script>
    <script type="text/javascript" src="../js/jquery.dataTables.min.js"></script>
    <script>
        $(function() {
            var table = $('#example').DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": "daos/lista_despesas.php",
                "columns": [
                    { "data": "id" },
                    { "data": "descricao" },
                    { "data": "categoria" },
                    { "data": "valor" },
                    { "data": "data_vencimento" },
                    { 
                        "data": "status",
                        "render": function(data, type, row) {
                            let statusClass = '';
                            if (data === 'Pago') {
                                statusClass = 'status-pago';
                            } else if (data === 'Pendente') {
                                statusClass = 'status-pendente';
                            } else if (data === 'Cancelado') {
                                statusClass = 'status-cancelado';
                            }
                            return '<span class="' + statusClass + '">' + data + '</span>';
                        }
                    },
                    {
                        "data": null,
                        "defaultContent": '<button class="btn btn-primary btn-sm edit-action"><i class="fa fa-pencil"></i></button> <button class="btn btn-danger btn-sm delete-action"><i class="fa fa-trash"></i></button>',
                        "orderable": false
                    }
                ]
            });
        
            $('#example').on('click', '.edit-action', function() {
                var data = table.row($(this).parents('tr')).data();
                $('#despesa_id').val(data.id);
                $('#status').val(data.status);
                $('#editModal').modal('show');
            });
        
            $('#saveChanges').on('click', function() {
                var id = $('#despesa_id').val();
                var status = $('#status').val();
        
                $.ajax({
                    url: 'daos/editar_status_despesa.php',
                    type: 'POST',
                    data: { id: id, status: status },
                    success: function(response) {
                        alert(response.message);
                        $('#editModal').modal('hide');
                        table.ajax.reload();
                    },
                    error: function() {
                        alert('Erro ao atualizar status.');
                    }
                });
            });
            
            $('#example').on('click', '.delete-action', function() {
                var data = $('#example').DataTable().row($(this).parents('tr')).data();
                var id = data.id;
            
                if (confirm('Tem certeza que deseja apagar esta despesa?')) {
                    // Faz a requisição AJAX para deletar
                    $.ajax({
                        url: 'delete_despesa.php',
                        type: 'POST',
                        data: { id: id },
                        success: function(response) {
                            alert(response.message); // Mensagem do servidor
                            $('#example').DataTable().ajax.reload(); // Recarrega a tabela
                        },
                        error: function() {
                            alert('Ocorreu um erro ao tentar apagar a despesa.');
                        }
                    });
                }
            });

        });
    </script>
<!-- doctors23:17-->
</html>