<?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 ?> | Añadir Licencia</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">
    <!-- BEGIN VENDOR CSS-->
    <link rel="stylesheet" type="text/css" href="assets/css/vendors.css">
    <!-- END VENDOR CSS-->
    <!-- BEGIN CHAMELEON  CSS-->
    <link rel="stylesheet" type="text/css" href="assets/css/app-lite.css">
    <!-- END CHAMELEON  CSS-->
    <!-- BEGIN Page Level 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">
    <!-- END Page Level CSS-->
    <style>
        /* Estilos personalizados 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);
        }

        .card-header {
            background-color: transparent;
            border-bottom: 1px solid #e5e7eb;
        }

        .card-title {
            font-weight: 600;
            color: #1f2937;
        }

        .form-group h6 {
            font-weight: 500;
            color: #4b5563;
            margin-bottom: 0.5rem;
        }

        .form-control {
            border-radius: 8px;
            border: 1px solid #d1d5db;
            padding: 0.75rem 1rem;
            transition: border-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
        }

        .form-control:focus {
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.2);
        }

        .btn-info {
            background-color: #4f46e5;
            border-color: #4f46e5;
            border-radius: 8px;
            padding: 0.75rem 1.5rem;
            font-weight: 600;
            transition: background-color 0.2s ease-in-out, border-color 0.2s ease-in-out;
        }

        .btn-info:hover {
            background-color: #4338ca;
            border-color: #4338ca;
        }
        
        #response-message {
            text-align: center;
            padding: 1rem;
            border-radius: 8px;
            margin-top: 1.5rem;
            font-size: 1rem;
            font-weight: 500;
            display: none; /* Oculto por defecto */
        }

        #response-message.success {
            background-color: #d1fae5;
            color: #065f46;
            border: 1px solid #6ee7b7;
            display: block;
        }

        #response-message.error {
            background-color: #fee2e2;
            color: #991b1b;
            border: 1px solid #fca5a5;
            display: block;
        }

        .password-wrapper {
            position: relative;
        }

        #toggle-password {
            position: absolute;
            top: 50%;
            right: 1rem;
            transform: translateY(-50%);
            background: transparent;
            border: none;
            cursor: pointer;
            color: #6b7280;
            padding: 0;
        }
        
        #toggle-password i {
            font-size: 1.25rem;
        }
    </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");
    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;">Crear Licencia para Usuario</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">Añadir Licencia</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            <div class="content-body">
                <div class="row justify-content-center">
                    <div class="col-xl-8 col-lg-10 col-md-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Detalles de la Licencia</h4>
                            </div>
                            <div class="card-block">
                                <div class="card-body">
                                    <form id="generate" onsubmit="return false;">
                                        <fieldset class="form-group">
                                            <h6 class="card-title">Número de Whatsapp (Con código de país)</h6>
                                            <input type="number" class="form-control" id="wnumber" name="wnumber" placeholder="Ej: 593991234567" required>
                                        </fieldset>
                                        <fieldset class="form-group">
                                            <h6 class="card-title">Nombre del Cliente</h6>
                                            <input type="text" class="form-control" id="cname" name="cname" placeholder="Ej: John Doe" required>
                                        </fieldset>
                                        <fieldset class="form-group">
                                            <h6 class="card-title">Correo Electrónico</h6>
                                            <input type="email" class="form-control" id="email" name="email" placeholder="Ej: usuario@ejemplo.com" required>
                                        </fieldset>
                                        <fieldset class="form-group">
                                            <h6 class="card-title">Contraseña</h6>
                                            <div class="password-wrapper">
                                                <input type="password" class="form-control" id="password" name="password" placeholder="Ingrese una contraseña segura" required>
                                                <button type="button" id="toggle-password">
                                                    <i class="la la-eye"></i>
                                                </button>
                                            </div>
                                        </fieldset>
                                        <fieldset class="form-group">
                                            <h6 class="card-title">Fecha de Vencimiento</h6>
                                            <input type="date" class="form-control" id="end-date" name="end-date" required>
                                        </fieldset>
                                        <fieldset class="form-group text-center mt-2">
                                            <button type="button" id="generate-license" class="btn btn-info btn-min-width mr-1 mb-1">Generar Licencia</button>
                                        </fieldset>
                                    </form>
                                    <div id="response-message"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- ////////////////////////////////////////////////////////////////////////////-->

    <?php include("include/footer.php"); ?>
    <!-- BEGIN VENDOR JS-->
    <script src="assets/vendors/js/vendors.min.js" type="text/javascript"></script>
    <!-- BEGIN VENDOR JS-->
    <!-- BEGIN CHAMELEON  JS-->
    <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>
    <!-- END CHAMELEON  JS-->

    <script>
        $(document).ready(function() {
            $('#title').html('Añadir Licencia');
            
            $('#toggle-password').click(function() {
                var passwordInput = $('#password');
                var icon = $(this).find('i');
                if (passwordInput.attr('type') === 'password') {
                    passwordInput.attr('type', 'text');
                    icon.removeClass('la-eye').addClass('la-eye-slash');
                } else {
                    passwordInput.attr('type', 'password');
                    icon.removeClass('la-eye-slash').addClass('la-eye');
                }
            });

            $('#generate-license').click(function() {
                var wnumber = $('#wnumber').val();
                var endDate = $('#end-date').val();
                var cname = $('#cname').val();
                var email = $('#email').val();
                var password = $('#password').val();
                var responseDiv = $('#response-message');

                responseDiv.removeClass('success error').empty().hide();

                if (!wnumber || !endDate || !cname || !email || !password) {
                    responseDiv.html("Por favor, rellene todos los campos obligatorios.").addClass('error').show();
                    return;
                }

                var today = new Date();
                today.setHours(0,0,0,0);
                var endDateObj = new Date(endDate);

                if(endDateObj < today){
                    responseDiv.html("La fecha de vencimiento no puede ser anterior a la fecha actual.").addClass('error').show();
                    return;
                }
                
                var validity = Math.ceil((endDateObj - today) / (1000 * 60 * 60 * 24)) + 1;

                $.ajax({
                    type: 'POST',
                    url: 'function/generate-license.php',
                    dataType: 'json',
                    data: {
                        wnumber: wnumber,
                        validity: validity,
                        cname: cname,
                        email: email,
                        password: password,
                        endDate: endDate // send exact date
                    },
                    success: function(response) {
                        if (response.status === true) {
                            responseDiv.html('LICENCIA CREADA CORRECTAMENTE').addClass('success').show();
                            $('#generate')[0].reset(); // Limpia el formulario
                        } else {
                            var errorMessage = response.message || 'Error al crear la licencia.';
                            responseDiv.html(errorMessage).addClass('error').show();
                        }
                    },
                    error: function() {
                        responseDiv.html('Ocurrió un error al procesar su solicitud.').addClass('error').show();
                    }
                });
            });
        });
    </script>

</body>
</html>

