<?php
// Incluir archivos de conexión y funciones
include("include/conn.php");
include("include/function.php");

// Verificar la sesión del usuario
$login = cekSession();
if ($login != 1) {
    redirect("login.php");
}
?>
<!DOCTYPE html>
<html class="loading" lang="es" data-textdirection="ltr">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title id="title"><?= $brandName ?> | Todas las Licencias</title>
    <link rel="apple-touch-icon" href="assets/images/ico/apple-icon-120.png">
    <link rel="shortcut icon" type="image/x-icon" href="assets/images/ico/favicon.ico">
    <link href="https://fonts.googleapis.com/css?family=Muli:300,300i,400,400i,600,600i,700,700i%7CComfortaa:300,400,700" rel="stylesheet">
    <link href="https://maxcdn.icons8.com/fonts/line-awesome/1.1/css/line-awesome.min.css" rel="stylesheet">
    
    <!-- CSS de Vendedores y Plantilla -->
    <link rel="stylesheet" type="text/css" href="assets/css/vendors.css">
    <link rel="stylesheet" type="text/css" href="assets/css/app-lite.css">
    <link rel="stylesheet" type="text/css" href="assets/css/core/menu/menu-types/vertical-menu.css">
    <link rel="stylesheet" type="text/css" href="assets/css/core/colors/palette-gradient.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

    <!-- DataTables y SweetAlert2 -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">
    
    <style>
        /* Estilos generales para un diseño moderno */
        .content-wrapper {
            background-color: #f3f4f6;
        }

        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
            overflow: hidden; /* Para que el estilo de la tabla no se salga */
        }

        .card-header {
            background-color: transparent;
            border-bottom: 1px solid #e5e7eb;
            padding: 1.5rem;
        }
        
        .card-title {
             font-weight: 600;
             color: #1f2937;
        }

        /* Estilos de la tabla y DataTables */
        .table-responsive {
            padding: 1.5rem;
        }

        #customerTable {
            width: 100% !important;
            border-collapse: collapse;
        }

        #customerTable thead th {
            background-color: #f9fafb;
            color: #4b5563;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 2px solid #e5e7eb;
        }
        
        #customerTable thead th input[type="checkbox"] {
            margin-right: 0.5rem;
        }


        #customerTable tbody tr {
            transition: background-color 0.2s ease;
        }

        #customerTable tbody tr:hover {
            background-color: #f9fafb;
        }

        #customerTable td, #customerTable th {
            vertical-align: middle;
        }

        div.dataTables_wrapper div.dataTables_filter input {
            border-radius: 8px;
            border: 1px solid #d1d5db;
            padding: 0.5rem 0.75rem;
            transition: border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
        }

        div.dataTables_wrapper div.dataTables_filter input:focus {
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.2);
            outline: none;
        }

        .dataTables_length select {
            border-radius: 8px !important;
            border: 1px solid #d1d5db !important;
            padding: 0.375rem 1.75rem 0.375rem 0.75rem !important;
        }

        /* Estilos para estado y acciones */
        .license-status {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-weight: 500;
            font-size: 0.75rem;
        }
        .license-status.text-success { background-color: #d1fae5; color: #065f46; }
        .license-status.text-danger { background-color: #fee2e2; color: #991b1b; }
        .icon-button { background: none; border: none; cursor: pointer; color: #6b7280; transition: color 0.2s; }
        .icon-button:hover { color: #1f2937; }
        
        .hidden { display: none !important; }
        .date-picker, .form-control {
            border-radius: 6px;
            border: 1px solid #d1d5db;
        }
    </style>
</head>

<body class="vertical-layout vertical-menu 2-columns menu-expanded fixed-navbar" data-open="click" data-menu="vertical-menu" data-color="bg-gradient-x-purple-blue" data-col="2-columns">

    <?php include("include/header.php"); ?>
    <?php include("include/sidebar.php"); ?>

    <div class="app-content content">
        <div class="content-wrapper">
            <div class="content-wrapper-before" style="background: none;"></div>
            <div class="content-header row">
                <div class="content-header-left col-md-4 col-12 mb-2">
                    <h3 class="content-header-title" style="color: #1f2937; font-weight: 700;">Licencias de Usuarios</h3>
                </div>
                <div class="content-header-right col-md-8 col-12">
                    <div class="breadcrumbs-top float-md-right">
                        <div class="breadcrumb-wrapper mr-1">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="index.php">Inicio</a></li>
                                <li class="breadcrumb-item active">Todas las Licencias</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            <div class="content-body">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <div class="d-flex justify-content-between align-items-center w-100">
                                    <h4 class="card-title">Gestión de Licencias</h4>
                                    <div class="form-inline">
                                        <label for="status-filter" class="mr-2">Filtrar por Estado:</label>
                                        <select class="form-control form-control-sm" id="status-filter">
                                            <option value="">Todos</option>
                                            <option value="Activa">Activa</option>
                                            <option value="Expirada">Expirada</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                             <div class="card-body">
                                <button id="delete-selected" class="btn btn-danger" style="display: none; margin-bottom: 1rem;">
                                    <i class="la la-trash"></i> Eliminar Seleccionados
                                </button>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover" id="customerTable">
                                     <thead>
                                        <tr>
                                            <th><input type="checkbox" id="select-all"></th>
                                            <th>Cliente</th>
                                            <th>Whatsapp</th>
                                            <th>Email</th>
                                            <th>Contraseña</th>
                                            <th>Activación</th>
                                            <th>Vencimiento</th>
                                            <th>Propietario</th>
                                            <th>Días Rest.</th>
                                            <th>Estado</th>
                                            <th>Acciones</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php
                                        $sql = "SELECT u.id, u.customer_name, u.whatsapp_number, u.email, u.password, u.act_date, u.end_date, u.user_id, u.status, a.username 
                                                FROM `users` AS u
                                                LEFT JOIN `admin` AS a ON u.user_id = a.id
                                                WHERE u.deleted_key != 'yes'";
                                        
                                        $params = [];
                                        $types = '';

                                        if ($_SESSION['user_type'] == 'user') {
                                            $u_id = $_SESSION['id'];
                                            $sql .= " AND (u.user_id = ? OR u.user_id IN (SELECT id FROM admin WHERE admin_id = ? AND user_type != 'user'))";
                                            $params = [$u_id, $u_id];
                                            $types = 'ii';
                                        } elseif ($_SESSION['user_type'] != 'admin') {
                                            $u_id = $_SESSION['id'];
                                            $sql .= " AND u.user_id = ?";
                                            $params = [$u_id];
                                            $types = 'i';
                                        }

                                        $stmt = mysqli_prepare($conn, $sql);
                                        if (!empty($params)) {
                                            mysqli_stmt_bind_param($stmt, $types, ...$params);
                                        }
                                        mysqli_stmt_execute($stmt);
                                        $result = mysqli_stmt_get_result($stmt);
                                        
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            
                                            $act_date_display = !empty($row['act_date']) && $row['act_date'] != '0000-00-00 00:00:00' ? date('d/m/Y', strtotime($row['act_date'])) : '';
                                            $end_date_display = !empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00' ? date('d/m/Y', strtotime($row['end_date'])) : '';
                                            $end_date_input = !empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00' ? date('Y-m-d', strtotime($row['end_date'])) : '';

                                            $remainingDays = 'N/A';
                                            if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
                                                try {
                                                    $endDate = new DateTime($row['end_date']);
                                                    $today = new DateTime();
                                                    $interval = $today->diff($endDate);
                                                    $remainingDays = $interval->format('%r%a');
                                                } catch (Exception $e) { $remainingDays = 'Error'; }
                                            }

                                            echo '<tr>';
                                            echo '<td><input type="checkbox" class="license-checkbox" value="' . $row['id'] . '"></td>';
                                            echo '<td>' . htmlspecialchars($row['customer_name']) . '</td>';
                                            echo '<td>' . htmlspecialchars($row['whatsapp_number']) . '</td>';
                                            echo '<td>' . htmlspecialchars($row['email']) . '</td>';
                                            echo '<td>' . htmlspecialchars($row['password']) . '</td>';
                                            echo '<td>' . $act_date_display . '</td>';

                                            echo '<td>';
                                            echo '<span class="display-date" id="display-end_date-' . $row['id'] . '">' . $end_date_display . '</span>';
                                            echo '<input type="date" class="date-picker hidden" id="input-end_date-' . $row['id'] . '" value="' . $end_date_input . '">';
                                            echo '<button class="icon-button js-show-picker" data-id="' . $row['id'] . '" data-field="end_date"><i class="fas fa-calendar-alt"></i></button>';
                                            echo '</td>';
                                            
                                            echo '<td>' . htmlspecialchars($row['username'] ?? 'N/A') . '</td>';
                                            echo '<td>' . $remainingDays . '</td>';
                                            
                                            $statusClass = $row['status'] == 'true' ? 'text-success' : 'text-danger';
                                            $statusText = $row['status'] == 'true' ? 'Activa' : 'Expirada';
                                            echo '<td><span class="license-status ' . $statusClass . '">' . $statusText . '</span></td>';
                                            
                                            echo '<td>
                                                <div class="btn-group">
                                                    <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Acción</button>
                                                    <div class="dropdown-menu dropdown-menu-right">
                                                        <a class="dropdown-item activate-btn" href="#" data-id="' . $row['id'] . '"><i class="la la-check text-success"></i> Activar</a>
                                                        <a class="dropdown-item deactivate-btn" href="#" data-id="' . $row['id'] . '"><i class="la la-times text-warning"></i> Desactivar</a>
                                                        <div class="dropdown-divider"></div>
                                                        <a class="dropdown-item" href="edit_license.php?id=' . htmlspecialchars($row['id']) . '"><i class="la la-pencil"></i> Editar</a>
                                                        <a class="dropdown-item delete-btn" href="#" data-id="' . $row['id'] . '"><i class="la la-trash text-danger"></i> Eliminar</a>
                                                    </div>
                                                </div>
                                            </td>';
                                            echo '</tr>';
                                        }
                                        mysqli_stmt_close($stmt);
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include("include/footer.php"); ?>
    
    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/core/app-menu-lite.js" type="text/javascript"></script>
    <script src="assets/js/core/app-lite.js" type="text/javascript"></script>

    <script>
    $(document).ready(function () {
        $('#title').html('<?= $brandName ?> | Todas las Licencias');
        $("#sid-all").addClass("active");

        var table = $('#customerTable').DataTable({
            "paging": true, "ordering": true, "searching": true,
            "order": [[8, "asc"]],
            "columnDefs": [
                { "orderable": false, "targets": [0, 10] }
            ],
            "language": { "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/es-ES.json" }
        });

        $('#status-filter').on('change', function(){
           var status = $(this).val();
           table.column(9).search(status ? '^'+status+'$' : '', true, false).draw();
        });

        function toggleDeleteButton() {
            if ($('.license-checkbox:checked').length > 0) {
                $('#delete-selected').show();
            } else {
                $('#delete-selected').hide();
            }
        }

        $('#select-all').on('click', function() {
            var rows = table.rows({ 'search': 'applied' }).nodes();
            $('input[type="checkbox"]', rows).prop('checked', this.checked);
            toggleDeleteButton();
        });

        $('#customerTable tbody').on('change', 'input[type="checkbox"]', function() {
            if (!this.checked) {
                var el = $('#select-all').get(0);
                if (el && el.checked && ('indeterminate' in el)) {
                    el.indeterminate = true;
                }
            }
            toggleDeleteButton();
        });

        $('#delete-selected').on('click', function() {
            var selectedIds = [];
            $('.license-checkbox:checked').each(function() {
                selectedIds.push($(this).val());
            });

            if (selectedIds.length === 0) {
                Swal.fire('Atención', 'Por favor, seleccione al menos una licencia para eliminar.', 'info');
                return;
            }

            Swal.fire({
                title: '¿Estás seguro?',
                text: "¡Vas a eliminar " + selectedIds.length + " licencias! Esta acción no se puede revertir.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Sí, ¡eliminar!',
                cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'delete-license.php',
                        type: 'POST',
                        data: { 'ids': selectedIds },
                        success: function(response) {
                            if (response.trim() === 'success') {
                                Swal.fire('¡Eliminadas!', 'Las licencias seleccionadas han sido eliminadas.', 'success')
                                    .then(() => location.reload());
                            } else {
                                Swal.fire('Error', 'No se pudieron eliminar las licencias. Detalles: ' + response, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Ocurrió un error de conexión.', 'error');
                        }
                    });
                }
            });
        });

        table.on('draw', function() {
            $('#select-all').prop('checked', false);
            toggleDeleteButton();
        });


        $('#customerTable').on('click', '.js-show-picker', function() { showDatePicker($(this).data('id'), $(this).data('field')); });
        
        function showDatePicker(id, field) {
            const input = $(`#input-${field}-${id}`), display = $(`#display-${field}-${id}`);
            display.addClass('hidden'); input.removeClass('hidden').focus();
            
            const handleUpdate = () => {
                if (input.val()) {
                    const now = new Date(), hours = String(now.getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0');
                    const newDateTime = `${input.val()} ${hours}:${minutes}`;
                    const [y, m, d] = input.val().split('-');
                    display.text(`${d}/${m}/${y}`);
                    $.post('update_date.php', { id: id, field: field, value: newDateTime }, (res) => {
                        Swal.fire(res.trim() === 'success' ? '¡Éxito!' : 'Error', `La fecha ha sido ${res.trim() === 'success' ? 'actualizada' : 'no actualizada'}.`, res.trim() === 'success' ? 'success' : 'error');
                    }).fail(() => Swal.fire('Error', 'Ocurrió un error de conexión.', 'error'));
                }
                input.addClass('hidden'); display.removeClass('hidden');
            };

            input.off('change').on('change', handleUpdate);
            input.off('blur').on('blur', () => { if (!input.val()) { input.addClass('hidden'); display.removeClass('hidden'); }});
        }

        $(document).on('click', '.activate-btn, .deactivate-btn', function (e) {
            e.preventDefault();
            updateLicenseStatus($(this).data('id'), $(this).hasClass('activate-btn') ? 'true' : 'false');
        });

        function updateLicenseStatus(id, status) {
            $.post('update-license-status.php', { id: id, status: status }, (res) => {
                Swal.fire(res.trim() === 'success' ? '¡Éxito!' : 'Error', `El estado ha sido ${res.trim() === 'success' ? 'actualizado' : 'no actualizado'}.`, res.trim() === 'success' ? 'success' : 'error').then(() => { if(res.trim() === 'success') location.reload(); });
            }).fail(() => Swal.fire('Error', 'Ocurrió un error de conexión.', 'error'));
        }

        $(document).on('click', '.delete-btn', function () {
            const licenseId = $(this).data('id');
            Swal.fire({ title: '¿Estás seguro?', text: "¡No podrás revertir esto!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Sí, ¡eliminar!', cancelButtonText: 'Cancelar'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('delete-license.php', { id: licenseId }, (res) => {
                        Swal.fire(res.trim() === 'success' ? '¡Eliminado!' : 'Error', `La licencia ha sido ${res.trim() === 'success' ? 'eliminada' : 'no eliminada'}.`, res.trim() === 'success' ? 'success' : 'error').then(() => { if(res.trim() === 'success') location.reload(); });
                    }).fail(() => Swal.fire('Error', 'Ocurrió un error de conexión.', 'error'));
                }
            });
        });
    });
    </script>
</body>
</html>

