<?php
include("include/conn.php");
include("include/function.php");
$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 ?> | Licencias Inactivas</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">
    
    <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 rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10/dist/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css" />

    <style>
        .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;
        }
        .card-header {
            background-color: transparent;
            border-bottom: 1px solid #e5e7eb;
            padding: 1.5rem;
        }
        .card-title { font-weight: 600; color: #1f2937; }
        .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 tbody tr:hover { background-color: #f9fafb; }
        #customerTable td, #customerTable th { vertical-align: middle; }
        div.dataTables_wrapper div.dataTables_filter input,
        .dataTables_length select {
            border-radius: 8px !important;
            border: 1px solid #d1d5db !important;
            padding: 0.5rem 0.75rem !important;
        }
        .license-status {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-weight: 500;
            font-size: 0.75rem;
            background-color: #fee2e2; 
            color: #991b1b;
        }
        .copy-icon { cursor: pointer; color: #6b7280; }
    </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 Inactivas</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">Licencias Inactivas</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            <div class="content-body">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Gestión de Licencias Inactivas</h4>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover" id="customerTable">
                                    <thead>
                                        <tr>
                                            <th>Cliente</th>
                                            <th>Whatsapp</th>
                                            <th>Clave Licencia</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
                                        if ($_SESSION['user_type'] == 'admin') {
                                            $q = mysqli_query($conn, "SELECT `id`, `customer_name`, `whatsapp_number`, `license_key`, `act_date`, `end_date`, `user_id`, `status` FROM `users` WHERE`status` = 'false'AND `deleted_key` != 'yes'");
                                        } elseif ($_SESSION['user_type'] == 'user') {
                                            $u_id = $_SESSION['id'];
                                            $q = mysqli_query($conn, "
                                                SELECT `id`, `customer_name`, `whatsapp_number`, `license_key`, `act_date`, `end_date`, `user_id`, `status` 
                                                FROM `users` 
                                                WHERE `deleted_key` != 'yes' AND `status` = 'false'
                                                AND (user_id = '$u_id' OR user_id IN (SELECT id FROM admin WHERE admin_id = '$u_id' AND user_type != 'user'))
                                            ");
                                        } else {
                                            $u_id = $_SESSION['id'];
                                            $q = mysqli_query($conn, "SELECT `id`, `customer_name`, `whatsapp_number`, `license_key`, `act_date`, `end_date`, `user_id`, `status` FROM `users` WHERE `user_id` = '$u_id' AND `status` = 'false' AND `deleted_key` != 'yes'");
                                        }

                                        while ($row = mysqli_fetch_assoc($q)) {
                                            echo '<tr>';
                                            echo '<td>' . htmlspecialchars($row['customer_name']) . '</td>';
                                            echo '<td>' . htmlspecialchars($row['whatsapp_number']) . '</td>';
                                            echo '<td>' . htmlspecialchars($row['license_key']) . ' <i class="la la-copy copy-icon" data-key="' . htmlspecialchars($row['license_key']) . '"></i></td>';
                                            echo '<td>' . date('d/m/Y', strtotime($row['act_date'])) . '</td>';
                                            echo '<td>' . date('d/m/Y', strtotime($row['end_date'])) . '</td>';
                                            
                                            $user_id = $row['user_id'];
                                            $admin_query = mysqli_query($conn, "SELECT username FROM admin WHERE id = '$user_id'");
                                            $admin_row = mysqli_fetch_assoc($admin_query);
                                            $username = $admin_row['username'] ?? 'N/A';
                                            echo '<td>' . htmlspecialchars($username) . '</td>';
                                        
                                            $endDate = new DateTime($row['end_date']);
                                            $today = new DateTime();
                                            $remainingDays = $today->diff($endDate)->format('%r%a');
                                            echo '<td>' . $remainingDays . '</td>';
                                            
                                            echo '<td><span class="license-status">Inactiva</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>
                                                        <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>';
                                        }
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <?php include("include/footer.php"); ?>

    <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 ?> | Licencias Inactivas');
            $('#customerTable').DataTable({
                "paging": true,
                "ordering": true,
                "searching": true,
                "order": [[6, "asc"]], // Ordenar por días restantes
                "columnDefs": [{ "orderable": false, "targets": 8 }],
                "language": { "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/es-ES.json" }
            });

            $(document).on('click', '.copy-icon', function() {
                const key = $(this).data('key');
                navigator.clipboard.writeText(key).then(() => {
                    Swal.fire('¡Copiado!', 'Clave de licencia copiada al portapapeles.', 'success');
                });
            });

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

            $(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: '#d33',
                    confirmButtonText: 'Sí, ¡eliminar!', cancelButtonText: 'Cancelar'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.post('delete-license.php', { id: licenseId }, (res) => {
                            if (res.trim() === 'success') {
                                Swal.fire('¡Eliminado!', 'La licencia ha sido eliminada.', 'success').then(() => location.reload());
                            } else {
                                Swal.fire('Error', 'No se pudo eliminar la licencia.', 'error');
                            }
                        }).fail(() => Swal.fire('Error', 'Ocurrió un error de conexión.', 'error'));
                    }
                });
            });
        });

        function updateLicenseStatus(id, status) {
            $.post('update-license-status.php', { id: id, status: status }, (res) => {
                if (res.trim() === 'success') {
                    Swal.fire('¡Actualizado!', 'El estado de la licencia ha cambiado.', 'success').then(() => location.reload());
                } else {
                    Swal.fire('Error', 'No se pudo actualizar el estado.', 'error');
                }
            }).fail(() => Swal.fire('Error', 'Ocurrió un error de conexión.', 'error'));
        }
    </script>
</body>
</html>
