<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 * 
 */

$page_no = '';
include_once "config/database.php";
include_once "resources/manageusers.php";
include_once "resources/EncryptDecrypt.php";

$object = new ManageUsers();

// Validate and sanitize user ID from URL
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $user_id = intval($_GET['id']); // Convert to integer for security
}
$userdetials = $object->UserDetails($user_id);
$companyId = '';
if ($row_user = $userdetials->fetch(PDO::FETCH_ASSOC)) {
    $companyId = $row_user["company_id"];
}
$passwordRules = $object->GetPasswordRules($companyId);
?>
<!DOCTYPE>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <!-- Styles -->
        <link rel="stylesheet" href="assets/css/login/style.css">
        <link rel="stylesheet" href="assets/css/main.php">
        <link rel="stylesheet" href="assets/css/subs.css">
        <link rel="stylesheet" href="assets/css/bootstrap.min.css">
        <!-- Fonts -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <title>Change password | K-nest LMS</title>
        <link rel="shortcut icon" href="assets/images/icon_header.png" />
    </head>

    <body>
        <!-- preloader start -->
        <div class="preloader js-preloader">
            <div class="preloader__bg" style="transform: scale(1, 0);"></div>
        </div>
        <section data-anim-wrap="" class="masthead -type-2 animated">
            <div class="masthead__bg" style="border-radius: 0px;left:0;right:0">
                <div class="bg-image js-lazy loaded" data-ll-status="loaded"
                     style="background-image: url(assets/images/bg/login.jpg);"></div>
            </div>

            <div class="row">
                <div class="col-md-6 left_page">
                    <div class="masthead__content px-20">
                        <h1 data-anim-child="slide-up delay-3" class="masthead__title text-white mt-10 is-in-view">
                            Unlock your potential with our complete learning platform.
                        </h1>
                        <div data-anim-child="slide-up delay-2"
                             class="masthead__subtitle fw-500 text-color-secondary text-20 lh-15 is-in-view">
                            <i>A simple, yet elegant learning platform built for you!</i>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 right_page">
                    <div data-anim-child="slide-up delay-6" class="masthead-form is-in-view">
                        <h4 class="masthead-form__title text-center text-20 lh-15 fw-500 mb-20 uppercase">
                            <?php echo _("US0105"); ?>
                        </h4>
                        <h6><?php echo _("LG0132"); ?></h6>

                        <form method="post">
                            <div class="masthead-form__group mt-20 password_div_form">
                                <label class="uppercase"><?php echo _("LG0143"); ?></label>
                                <input type="password" placeholder="<?php echo _("LG0145"); ?>" required id="password6" autocomplete="on" maxlength="20">
                                <i class="fa fa-eye password_toggle togglePassword" toggle="#password6"></i>
                                <span class="text-red-1 mt-5" id="password6_error" style="display: none;"><?php echo _("LG0504") ?></span>
                            </div>

                            <div class="masthead-form__group mt-20 password_div_form">
                                <label class="uppercase"><?php echo _("LG0144"); ?></label>
                                <input type="password" placeholder="<?php echo _("LG0145"); ?>" required id="password7" autocomplete="on" maxlength="20">
                                <i class="fa fa-eye password_toggle togglePassword" toggle="#password7"></i>
                                <span class="text-red-1 mt-5" id="password7_error"  style="display: none;"><?php echo _("LG0502") ?></span>
                                <span class="text-red-1 mt-5" id="error6" style="display: none;"></span>
                            </div>

                            <div class="col md-6">
                                <div class="d-flex x-gap-20 items-center justify-between pt-20">
                                    <button type="button" name="submit" id="log" onclick="changepassword('<?php echo $_GET['id'] ?>')" class="button -sm px-24 py-20 text-14 bg-color-primary text-white uppercase">
                                        <i class="fa fa-spinner fa-spin" id="small_loader"></i> <?php echo _("LG0146") ?>
                                    </button>
                                </div>
                            </div>

                            <div style="padding-top: 15px;">
                                <a href="javascript:void(0);" onmouseover="togglePasswordPolicy();" class="a-tag" password-policy>
                                    <?php echo _("LG0104"); ?>
                                </a>
                            </div>

                            <div id="password-policy" class="text-16 px-5 text-black-3 forum_rules_tag py-5;" style="margin-top:20px">

                                <ul>
                                    <?php
                                    if (($passwordRules)) {
                                        if (isset($passwordRules['min_length'])) {
                                            echo "<li>Minimum length: " . $passwordRules['min_length'] . " characters</li>";
                                        }
                                        if (isset($passwordRules['max_length'])) {
                                            echo "<li>Maximum length: " . $passwordRules['max_length'] . " characters</li>";
                                        }
                                        if (isset($passwordRules['uppercase']) && $passwordRules['uppercase'] === 'Y') {
                                            echo "<li>Must contain at least one uppercase letter</li>";
                                        }
                                        if (isset($passwordRules['lower_case']) && $passwordRules['lower_case'] === 'Y') {
                                            echo "<li>Must contain at least one lowercase letter</li>";
                                        }
                                        if (isset($passwordRules['numeric']) && $passwordRules['numeric'] === 'Y') {
                                            echo "<li>Must contain at least one number</li>";
                                        }
                                        if (isset($passwordRules['special_char']) && $passwordRules['special_char'] === 'Y') {
                                            echo "<li>Must contain at least one special character</li>";
                                        }
                                    } else {
                                        echo "<li>No specific rules set.</li>";
                                    }
                                    ?>
                                </ul>
                            </div>

                        </form>
                    </div>
                </div>
            </div>
        </section>
        <div class="login_page_footer bg-color-secondary">
            <footer class="footer -type-5 py-20">
                <div class="row text-center">
                    <div class="col-auto">
                        <div class="footer-footer__copyright h-100 text-white">
                            &#169; Copyright 2023. Powered by &nbsp;<a href="https://knestlms.com/" target="_blank" class="text-color-primary footer_company_link">K-nest LMS</a>. All Rights Reserved By
                            &nbsp;<a href="https://4edgeit.com/" target="_blank" class="text-color-primary footer_company_link"> 4Edge IT Solutions.</a>
                        </div>
                    </div>
                </div>
            </footer>
        </div>

        <script src="assets/js/jquery-3.6.3.min.js"></script>
        <script src="assets/js/bootstrap.min.js"></script>
        <script src="assets/js/vendors.js"></script>
        <script src="assets/js/main.js"></script>
        <script>
                                    $('#small_loader').hide();
                                    $(document).on('keydown', function (e) {
                                        if (e.which === 13) {
                                            e.preventDefault();
                                            changepassword('<?php echo $_GET['id'] ?>');
                                        }
                                    });
                                    // Fetch password rules from the server
                                    function fetchPasswordRules(callback) {
                                        $.ajax({
                                            url: "modules/get_password_rules.php",
                                            type: "POST",
                                            data: {
                                                company_id: "<?php echo $companyId; ?>"
                                            },
                                            dataType: "json",
                                            success: function (response) {
                                                if (response.success) {
                                                    callback(response.rules);
                                                }
                                            },
                                            error: function (xhr, status, error) {

                                            }
                                        });
                                    }

                                    // Validate password against company rules
                                    function validatePassword(password, rules) {
                                        if (!rules) {
                                            return false;
                                        }

                                        let regexPattern = "^";

                                        if (rules.lower_case === "Y")
                                            regexPattern += "(?=.*[a-z])";
                                        if (rules.uppercase === "Y")
                                            regexPattern += "(?=.*[A-Z])";
                                        if (rules.numeric === "Y")
                                            regexPattern += "(?=.*\\d)";
                                        if (rules.special_char === "Y")
                                            regexPattern += "(?=.*[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/`~])";                                          

                                        regexPattern += ".{" + (rules.min_length) + "," + (rules.max_length) + "}$";

                                        let passwordRegex = new RegExp(regexPattern);
                                        return passwordRegex.test(password);
                                    }
                                    function changepassword(id) {
                                        // get values
                                        var error_msg = "";
                                        var password1 = $("#password6").val();
                                        //    password1 = password1.trim();
                                        var password2 = $("#password7").val();
                                        //    password2 = password2.trim();
                                        var submit = true;
                                        if (password1 == "") {
                                            $('#password6_error').css({"display": "block"});
                                            submit = false;
                                        } else {
                                            $('#password6_error').hide();
                                        }
                                        if (password2 == "") {
                                            $('#password7_error').css({"display": "block"});
                                            submit = false;
                                        } else {
                                            $('#password7_error').hide();
                                        }
                                        if (submit) {
                                            fetchPasswordRules(function (rules) {
                                                //password criteria match
                                                if (!validatePassword(password1, rules)) {
                                                    $("#error6").text("Password does not meet the required criteria.").show();
                                                    return;
                                                }
                                                //confirm password match
                                                if (password1 !== password2) {
                                                    $("#error6").text("Passwords do not match.").show();
                                                    return;
                                                }

                                                $('#small_loader').show();

                                                // Update password via AJAX
                                                $.post("modules/changepassword.php", {
                                                    id: id,
                                                    password1: password1,
                                                    password2: password2
                                                }, function (response) {
                                                    $('#small_loader').hide();
                                                    try {
                                                        let data = JSON.parse(response.trim());
                                                        if (data.result1 === "failure") {
                                                            $("#error6").text(data.result2).show();
                                                        } else {
                                                            window.location.href = data.result2;
                                                        }
                                                    } catch (e) {
                                                        console.error("Invalid JSON response:", response);
                                                        $("#error6").text("An unexpected error occurred.").show();
                                                    }
                                                });
                                            });

                                        }
                                    }
                                    function togglePasswordPolicy() {
                                        var card = document.getElementById("password-policy");
                                        if (card.style.display === "none" || card.style.display === "") {
                                            card.style.display = "block";
                                        } else {
                                            card.style.display = "none";
                                        }
                                    }
                                    document.addEventListener("DOMContentLoaded", function () {
                                        var card = document.getElementById("password-policy");
                                        var link = document.querySelector("a[password-policy]");

                                        card.style.display = "none"; // Ensure it's hidden on page load

                                        link.addEventListener("mouseover", function () {
                                            card.style.display = "block"; // Show card on hover
                                        });

                                        link.addEventListener("mouseout", function (event) {
                                            // Hide card only if not moving towards the card itself
                                            if (!card.contains(event.relatedTarget)) {
                                                card.style.display = "none";
                                            }
                                        });

                                        card.addEventListener("mouseout", function (event) {
                                            // Hide only if not moving towards the link
                                            if (!link.contains(event.relatedTarget)) {
                                                card.style.display = "none";
                                            }
                                        });
                                    });

                                    $(".togglePassword").unbind('click').bind('click', function (e) {
                                        $(this).toggleClass("fa-eye fa-eye-slash");
                                        var input = $($(this).attr("toggle"));
                                        if (input.attr("type") == "password") {
                                            input.attr("type", "text");
                                        } else {
                                            input.attr("type", "password");
                                        }
                                    });
        </script>
    </body>

</html>