<?php
// start session 
session_start();
if (!isset($_SESSION['uid'])) {
    header("Location: index.php");
} else {
// connect to database
    include 'config/database.php';
    include_once 'config/properties.php';
    include_once "resources/manageusers.php";
    include_once "resources/EncryptDecrypt.php";
    include_once "resources/offering.php";

// initialize objects
    $users = new ManageUsers();
    $offering = new Offering();

// set page title
    $page_no = 12;
    $user_id = $_SESSION['uid'];

    if ($user_id > 0) {
        $userdetials = $users->UserDetails($user_id);
        $companyId = '';
        if ($row_user = $userdetials->fetch(PDO::FETCH_ASSOC)) {
            $companyId = $row_user["company_id"];
        }
        $passwordRules = $users->GetPasswordRules($companyId);
    } else {
        $passwordRules = [];
    }

    $stmt = $users->getUserImageSize($_SESSION['uid']);
    if ($stmt->rowCount() > 0) {
        if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $user_image_size = $row['user_image_size'];
            $user_image_height = $row['user_image_height'];
            $user_image_width = $row['user_image_width'];
        }
    }
    ?>
    <html>
        <head>
            <?php include "./head.php" ?>
            <title>
                <?php echo _("LB0113"); ?>
            </title>
            <link rel="stylesheet" href="assets/css/profile/style.css">
            <link rel='stylesheet' href='assets/css/profile/jquery.Jcrop.min.css' type='text/css' media='all' />
        </head>
        <body>
            <?php include "./menu_primary.php";
            ?>
            <input type="hidden" id="max_filesize" value="<?php echo $user_image_size; ?>">
            <input type="hidden" id="height" value="<?php echo $user_image_height; ?>">
            <input type="hidden" id="width" value="<?php echo $user_image_width; ?>">
            <input type="hidden" id="profile_image_name" value="<?php echo $fl_name; ?>">
            <div class="container py-30 x-gap-50 bg-primary-opacity-1 rounded-16 mb-50">
                <div class="row px-10">
                    <div class="col-xl-3 col-lg-3 col-md-3 text-center profile-left">
                        <div class="bg-color-primary rounded-8 py-20">
                            <div class="d-flex x-gap-30 justify-center items-center">
                                <div class="user-heading">
                                    <img class="object-cover rounded-full size-180" src="<?php echo $filepath; ?>"
                                         alt="image">
                                </div>
                            </div>
                            <div class="d-flex justify-center items-center flex-wrap py-15">
                                <div style="cursor:pointer;" title="<?php echo _("US0123") ?>" onclick="changePic()">
                                    <div class="d-flex justify-center items-center size-40 rounded-8 bg-light-3">
                                        <div class="fa fa-upload text-16"></div>
                                    </div>
                                </div>
                                <?php if ($fl_name != "") { ?>

                                    <div class="ml-10" style="cursor:pointer;" title="<?php echo _("FR0117") ?>" id="delete_image">
                                        <div class="d-flex justify-center items-center size-40 rounded-8 bg-light-3">
                                            <div class="fa fa-trash text-16"></div>
                                        </div>
                                    </div>
                                <?php } ?>
                            </div>
                            <h1 class="text-24 fw-500 text-white mb-5"><?php echo $first_name; ?></h1>
                            <p class="text-12 text-white mb-20"><?php echo $name; ?></p>
                            <a href="summary_report.php" class="text-13 lh-1 text-white"><u><i class="fa fa-file text-13 mr-5"></i><?php echo _("HM0136"); ?></u></a>
                        </div>
                    </div>

                    <div class="col-xl-9 col-lg-9 col-md-9 pl-0 mb-50 profile-right">
                        <div class="tabs -active-purple-2 js-tabs rounded-8">

                            <div class="tabs__controls d-flex js-tabs-controls bg-white rounded-top-8">
                                <button class="tabs__button js-tabs-button text-16 py-15 px-30 is-active-tab"
                                        data-tab-target=".-tab-item-1" type="button">
                                            <?php echo _("US0101") ?>
                                </button>
                                <?php
                                $stmt_assgnd_groups = $users->AssignedGroups($uid);
                                if ($stmt_assgnd_groups->rowCount() > 0) {
                                    ?>
                                    <button class="tabs__button js-tabs-button text-16 py-15 px-25" data-tab-target=".-tab-item-2"
                                            type="button">
                                                <?php echo _("US0103") ?>
                                    </button>
                                    <?php
                                }
                                $stmt_assgnd_roles = $users->AssignedRoles($uid);
                                if ($stmt_assgnd_roles->rowCount() > 0) {
                                    ?>
                                    <button class="tabs__button js-tabs-button text-16 py-15 px-30" data-tab-target=".-tab-item-3"
                                            type="button">
                                                <?php echo _("US0104") ?>
                                    </button>
                                <?php } ?>
                                <button class="tabs__button js-tabs-button text-16 py-15 px-20" data-tab-target=".-tab-item-4"
                                        type="button">
                                            <?php echo _("US0105") ?>
                                </button>
                                <button class="tabs__button js-tabs-button text-16 py-15 px-20" data-tab-target=".-tab-item-5"
                                        type="button" name="languages_tab">
                                            <?php echo _("US0106") ?>
                                </button>
                            </div>

                            <div class="tabs__content js-tabs-content bg-white pt-20 col-md-12 pb-50 px-30">

                                <div class="tabs__pane -tab-item-1 is-active-tab">
                                    <div class="row py-10 border-bottom-light">
                                        <h2 class="text-17 lh-1 fw-500"> <?php echo _("US0107") ?></h2>
                                        <p><?php echo _("US0108") ?></p>
                                    </div>
                                    <?php if ($login_id != null) { ?>
                                        <div class="row py-10 border-bottom-light">
                                            <p class="text-12 mb-5"><?php echo _("US0109") ?></p>
                                            <h2 class="text-24 lh-1 fw-500"><?php echo $login_id ?></h2>
                                            <p><?php echo _("US0110") ?></p>
                                        </div>
                                    <?php } ?>

                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-user text-16 "></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0153") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $first_name ?> <?php echo $last_name ?></div>
                                        </div>
                                    </div>
                                    <?php
                                    $mobile_no_user = "---";
                                    $email_id_user = "---";
                                    $designation = "---";
                                    $dept_name = "---";
                                    $location = "---";
                                    $project = "---";
                                    $grade = "---";

                                    $stmt_user = $users->UserDetails($_SESSION['uid']);
                                    if ($row_user = $stmt_user->fetch(PDO::FETCH_ASSOC)) {
                                        if ($row_user["email_id"] != "") {
                                            $email_id_user = $row_user["email_id"];
                                        }
                                        if ($row_user["mobile_no"] != null) {
                                            $mobile_no_user = $row_user["mobile_no"];
                                        }
                                        if ($row_user["designation"] != null) {
                                            $designation = $row_user["designation"];
                                        }
                                        if ($row_user["dept_name"] != null) {
                                            $dept_name = $row_user["dept_name"];
                                        }
                                        if ($row_user["location"] != null) {
                                            $location = $row_user["location"];
                                        }
                                        if ($row_user["project"] != null) {
                                            $project = $row_user["project"];
                                        }
                                        if ($row_user["grade"] != null) {
                                            $grade = $row_user["grade"];
                                        }
                                    }
                                    ?>

                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-envelope text-16"></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0114") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $email_id_user ?></div>
                                        </div>
                                    </div>

                                    <?php ?>
                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-phone text-16"></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0113") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $mobile_no_user ?></div>
                                        </div>
                                    </div>


                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-cloud text-16"></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0115") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $designation ?></div>
                                        </div>
                                    </div>

                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-building text-16"></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0152") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $dept_name ?></div>
                                        </div>
                                    </div>

                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-graduation-cap text-16"></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0116") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $grade ?></div>
                                        </div>
                                    </div>

                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-book text-16"></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0118") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $project ?></div>
                                        </div>
                                    </div>

                                    <div class="d-flex items-center py-10 col-md-6">
                                        <div class="d-flex justify-center items-center size-40 rounded-full bg-primary-opacity-1">
                                            <div class="fa fa-map-marker text-16"></div>
                                        </div>
                                        <div class="ml-12">
                                            <h4 class="text-15 lh-1 fw-500"><?php echo _("US0119") ?></h4>
                                            <div class="text-13 lh-1 mt-10"><?php echo $location ?></div>
                                        </div>
                                    </div>
                                </div>
                                <?php
                                if ($stmt_assgnd_groups->rowCount() > 0) {
                                    ?>   
                                    <div class="tabs__pane -tab-item-2">
                                        <div class="row py-10 border-bottom-light">
                                            <h2 class="text-17 lh-1 fw-500">  <?php echo _("US0124") ?></h2>
                                        </div>
                                        <div class="table-responsive mt-40 mb-40">
                                            <table class="table_profile w-1/1">
                                                <colgroup>
                                                    <col style="width:50%">
                                                    <col style="width:20%">
                                                </colgroup>
                                                <thead>
                                                    <tr>
                                                        <th><?php echo _("US0125") ?></th>
                                                        <th><?php echo _("US0126") ?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    while ($row_assgnd_groups = $stmt_assgnd_groups->fetch(PDO::FETCH_ASSOC)) {
                                                        ?>
                                                        <tr class="bg-white shadow-1 rounded-8 border-light">
                                                            <td><?php echo htmlentities($row_assgnd_groups['group_name']); ?></td>
                                                            <td><?php echo htmlentities($row_assgnd_groups['status']); ?></td>
                                                        </tr>

                                                    <?php } ?>

                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                                <?php } if ($stmt_assgnd_roles->rowCount() > 0) { ?>

                                    <div class="tabs__pane -tab-item-3">
                                        <div class="row py-10 border-bottom-light">
                                            <h2 class="text-17 lh-1 fw-500"> <?php echo _("US0127") ?></h2>
                                        </div>
                                        <div class="table-responsive mt-40 mb-40">
                                            <table class="table_profile w-1/1">
                                                <colgroup>
                                                    <col style="width:50%">
                                                    <col style="width:20%">
                                                </colgroup>
                                                <thead>
                                                    <tr>
                                                        <th><?php echo _("US0128") ?></th>
                                                        <th><?php echo _("US0126") ?></th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                    while ($row_assgnd_roles = $stmt_assgnd_roles->fetch(PDO::FETCH_ASSOC)) {
                                                        ?>
                                                        <tr class="bg-white shadow-1 rounded-8 border-light">
                                                            <td><?php echo htmlentities($row_assgnd_roles['role_name']); ?></td>
                                                            <td><?php echo $row_assgnd_roles['status']; ?></td>
                                                        </tr>
                                                    <?php }
                                                    ?>
        <!--                                                <tr class="bg-white shadow-1 rounded-8 border-light">
        <td colspan="2" class="text-center">No Roles</td>
        </tr>-->
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                <?php } ?>

                                <div class="tabs__pane -tab-item-4">

                                    <div class="row py-10 border-bottom-light">
                                        <h2 class="text-17 lh-1 fw-500"><?php echo _("US0129"); ?></h2>

                                    </div>
                                    <div class="row">
                                        <div class="col-md-8">
                                            <form class="contact-form row y-gap-30">
                                                <div class="password_div_form">
                                                    <div class="text-red-1 none" id="error-code"></div>
                                                </div>
                                                <div class="col-md-8 password_div_form mr-5">
                                                    <label class="text-16 lh-1 fw-500 text-dark-1 mb-10"><?php echo _("US0130"); ?></label>
                                                    <input type="password" id="old_password" placeholder="<?php echo _("US0131"); ?>" class="mb-5">
                                                    <i class="fa fa-eye password_toggle" id="togglePassword"></i>
                                                    <div class="text-red-1 none" id="old-password-status"><?php echo _("US0511"); ?></div>
                                                </div>
                                                <div class="col-md-8 password_div_form mr-5">
                                                    <label class="text-16 lh-1 fw-500 text-dark-1 mb-10"><?php echo _("US0132"); ?></label>
                                                    <input type="password" id="new_password" placeholder="<?php echo _("US0133"); ?>" class="mb-5">
                                                    <i class="fa fa-eye password_toggle" id="togglePassword"></i>
                                                    <div class="text-red-1 none" id="new-password-status1"><?php echo _("LG0504") ?></div>
                                                    <div class="text-red-1 none" id="new-password-status2"><?php echo _("LG0103") ?></div>
                                                </div>
                                                <div class="col-md-8 password_div_form mr-5">
                                                    <label class="text-16 lh-1 fw-500 text-dark-1 mb-10"><?php echo _("US0134"); ?></label>
                                                    <input type="password" id="confirm_password" placeholder="<?php echo _("US0135"); ?>" class="mb-5">
                                                    <i class="fa fa-eye password_toggle" id="togglePassword"></i>
                                                    <div class="text-red-1 none" id="confirm-password-status1"><?php echo _("LG0505") ?></div>
                                                    <div class="text-red-1 none" id="confirm-password-status2"><?php echo _("LG0103") ?></div>
                                                    <div class="text-red-1 none" id="confirm-password-status3"><?php echo _("US0512") ?></div>
                                                </div>
                                                <div class="col-12">
                                                    <button class="button -icon bg-color-primary text-white" id="save_pass">
                                                        <i class="fa fa-check text-13 mr-5"></i><?php echo _("US0136"); ?></button>
                                                </div>
                                            </form>
                                        </div>
                                        <div class="col-md-4">
                                            <a onmouseover="togglePasswordPolicy();" class="ppl" id="pph"><?php echo _("LG0104"); ?></a> 
                                            <div class="col-md-12">

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

                                <div class="tabs__pane -tab-item-5">
                                    <div class="row py-10 border-bottom-light">
                                        <h2 class="text-17 lh-1 fw-500"><?php echo _("US0138"); ?></h2>
                                    </div>

                                    <div class="pt-5">
                                        <?php
                                        $slan = "";
                                        $stmt_slan = $offering->language_check($uid);
                                        if ($stmt_slan->rowCount() > 0) {
                                            if ($row_slan = $stmt_slan->fetch(PDO::FETCH_ASSOC)) {
                                                extract($row_slan);
                                                $slan = $row_slan['pref_lang_id'];
                                            }
                                        }
                                        $stmt_lan = $offering->getLanguages();
                                        if ($stmt_lan->rowCount() > 0) {
                                            while ($row_lan = $stmt_lan->fetch(PDO::FETCH_ASSOC)) {
                                                extract($row_lan);
                                                ?>
                                                <div class="form-radio d-flex items-center mt-5">
                                                    <div class="radio">
                                                        <input type="radio" name="language" value="<?php echo $row_lan['lang_id'] ?>" <?php if ($row_lan['lang_id'] == $slan) { ?>checked=""<?php } ?>>
                                                        <div class="radio__mark">
                                                            <div class="radio__icon"></div>
                                                        </div>
                                                    </div>
                                                    <div class="text-16 fw-500 ml-12"><?php echo $row_lan['lang_name'] ?></div>
                                                </div>
                                                <?php
                                            }
                                        }
                                        ?>

                                        <button class="button -icon bg-color-primary text-white mt-20" onclick="savelanguage();" id="save_language">
                                            <i class="fa fa-check text-13 mr-5"></i><?php echo _("US0136"); ?></button>

                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- Modal -->
            <div class="modal fade" id="profile_pic_modal" tabindex="-1" role="dialog">
                <div class="modal-dialog modal-lg" role="document">
                    <div class="modal-content">
                        <form id="form">
                            <div class="modal-header">
                                <div class="d-flex justify-between items-center">
                                    <h2 class="modal-title text-17 lh-1 fw-500"><?php echo _("US0145"); ?></h2>
                                    <button type="button" class="close" id="close_span" data-dismiss="modal"
                                            aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                            </div>
                            <div class="modal-body  bg-primary-opacity-1">
                                <input id="file" type="file" required="" accept="image/*" />

                                <p><i><?php echo _("US0146"); ?> <?php echo $row['user_image_width']; ?> * <?php echo $row['user_image_height']; ?> of size not exceeding <?php echo $row['user_image_size']; ?> KB.</i></p> 
                                <center>
                                    <div id="action_buttons" style="display:none;"><br/>
                                        <button id="cropbutton" class="action_buttons_inside" type="button"><?php echo _("US0147"); ?></button>
                                        <button id="rotatebutton" class="action_buttons_inside" type="button"><?php echo _("US0148"); ?></button>
                                        <button id="hflipbutton" class="action_buttons_inside" type="button"><?php echo _("US0149"); ?></button>
                                        <button id="vflipbutton" class="action_buttons_inside" type="button"><?php echo _("US0150"); ?></button>
                                    </div>
                                    <br>
                                    <div id="views"></div>
                                </center>
                            </div>
                            <div class="modal-footer">
                                <div class="d-flex justify-center">
                                    <button
                                        class="text-16 button -icon px-50 py-0 bg-color-primary text-white" id="save_crop" >
                                            <?php echo _("US0136") ?>
                                    </button>
                                    &nbsp;
                                    <button
                                        class="text-16 button -icon px-50 py-0 -secondary-1 text-white"
                                        data-dismiss="modal"><?php echo _("AS0156"); ?></button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php include "./footer_primary.php" ?>
            <script type='text/javascript' src='assets/js/profile/jquery.Jcrop.min.js'></script>
           <script>
            function togglePasswordPolicy() {
                var card = document.getElementById("password-policy");
                card.style.display = (card.style.display === "none" || card.style.display === "") ? "block" : "none";
            }

            document.addEventListener("DOMContentLoaded", function() {
                var link = document.getElementById("pph"); // Correct selector for the link
                var card = document.getElementById("password-policy"); // Correct selector for the card

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

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

                // Hide card when mouse leaves the link
                link.addEventListener("mouseout", function(event) {
                    if (!card.contains(event.relatedTarget)) {
                        card.style.display = "none";
                    }
                });

                // Hide card when mouse leaves the card
                card.addEventListener("mouseout", function(event) {
                    if (!link.contains(event.relatedTarget)) {
                        card.style.display = "none";
                    }
                });
            });
        </script>
            <script>
                $(document).ready(function () {
                    let passwordRules = <?php echo json_encode($passwordRules); ?>;

                    $('#save_pass').click(function (e) {
                        e.preventDefault();
                        let valid = true;

                        let old_password = $('#old_password').val().trim();
                        let new_password = $('#new_password').val().trim();
                        let confirm_password = $('#confirm_password').val().trim();

                        // Old Password Validation
                        if (old_password === "") {
                            $("#old-password-status").show();
                            valid = false;
                        } else {
                            $("#old-password-status").hide();
                        }

                        // New Password Validation
                        if (new_password === "") {
                            $("#new-password-status1").show();
                            valid = false;
                        } else if (!validatePassword(new_password, passwordRules)) {
                            $("#new-password-status1").hide();
                            $("#new-password-status2").show();
                            valid = false;
                        } else {
                            $("#new-password-status1").hide();
                            $("#new-password-status2").hide();
                        }

                        // Confirm Password Validation
                        if (confirm_password !== new_password) {
                            $("#confirm-password-status3").show();
                            valid = false;
                        } else {
                            $("#confirm-password-status3").hide();
                        }

                        if (valid) {
                            $.ajax({
                                url: 'modules/change_pass.php',
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    "mode": "change",
                                    "old": old_password,
                                    "new": new_password
                                },
                                success: function (response) {
                                    if (!response || typeof response !== 'object') {
                                        return;
                                    }

                                    if (response.result1 === "not_match") {
                                        $("#error-code").css({
                                            "color": "red",
                                            "display": "block"
                                        }).html(response.result2);
                                    } else if (response.result1 === "same") {
                                        $("#error-code").css({
                                            "color": "red",
                                            "display": "block"
                                        }).html(response.result2);
                                    } else if (response.result1 === "success") {
                                        $("#error-code").css({
                                            "color": "green",
                                            "display": "block"
                                        }).html(response.result2);
                                        $('#old_password, #new_password, #confirm_password').val('');
                                    }
                                },
                                error: function () {
                                }
                            });
                        }
                    });

                    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 || 6) + "," + (rules.max_length || 20) + "}$";

                        let passwordRegex = new RegExp(regexPattern);
                        return passwordRegex.test(password);
                    }
                });
            </script>
            <script>

                $(window).on('hashchange', function (e) {
                    var url = document.location.toString();
                    if (url.match('#')) {
                        $('.tabs__controls button').removeClass('is-active-tab');
                        $('.tabs__controls button[name="languages_tab"]').addClass('is-active-tab');
                        var target = ($('.tabs__controls button[name="languages_tab"]').attr('data-tab-target')).split(".")[1];
                        $('.tabs__content div').removeClass('is-active-tab');
                        $('.tabs__content div[class="tabs__pane ' + target + '"]').addClass('is-active-tab');
                    }
                });
                $(document).ready(function () {
                    //hide all display messages
                    $('.none').hide();
                    var url = document.location.toString();
                    if (url.match('#')) {
                        $('.tabs__controls button').removeClass('is-active-tab');
                        $('.tabs__controls button[name="languages_tab"]').addClass('is-active-tab');
                        var target = ($('.tabs__controls button[name="languages_tab"]').attr('data-tab-target')).split(".")[1];
                        $('.tabs__content div').removeClass('is-active-tab');
                        $('.tabs__content div[class="tabs__pane ' + target + '"]').addClass('is-active-tab');
                    }
                });

                function changePic() {
                    jQuery('#profile_pic_modal').modal("show");
                }

                $(".password_toggle").unbind('click').bind('click', function (e) {
                    $(this).toggleClass("fa-eye fa-eye-slash");
                    var type = $(this).prev().attr('type');
                    if (type == "password") {
                        $(this).prev().attr("type", "text");
                    } else {
                        $(this).prev().attr("type", "password");
                    }
                });
                function savelanguage() {
                    var language = $('input[name="language"]:checked').val();
                    jQuery.ajax({
                        url: 'modules/languages.php',
                        data: {"mode": "change", "language": language},
                        type: 'POST',
                        success: function (data) {
                            alert("<?php echo _("US0202") ?>");
                            location.reload();
                        },
                        error: function () {
                            alert("<?php echo _("GN0401") ?>");
                        }
                    });
                }
                //enter
                $(document).on('keydown', function (e) {
                    if (e.which === 13) {
                        e.preventDefault();
                        if ($('#s').val() == "") {
                            $tab_val = $('.is-active-tab').attr('data-tab-target');
                            if ($tab_val === '.-tab-item-4') {
                                if ($("#save_pass").length) {
                                    $('#save_pass').trigger('click');
                                }
                            } else if ($tab_val === '.-tab-item-5') {
                                if ($("#save_language").length) {
                                    $('#save_language').trigger('click');
                                }
                            } else if ($tab_val === '.-tab-item-1') {
                                if ($('#profile_pic_modal').css('display') === 'block') {
                                    if ($("#form").length) {
                                        $('#save_crop').trigger('click');
                                    }
                                }
                            }
                        } else {
                            window.location = "search.php?s=" + $('#s').val() + "";
                        }
                    }
                });
                var crop_max_width = 400;
                var crop_max_height = 400;
                var jcrop_api;
                var canvas;
                var context;
                var image;
                var prefsize;
                var fileName;
                $(document).ready(function () {
                    var img;
                    jQuery('#file').change(function () {
                        var file = $(this)[0].files[0];
                        fileName = $(this).val();
                        if (fileName.length > 0) {
                            img = new Image();
                            var max_filesize = $('#max_filesize').val();
                            var maxheight = $('#height').val();
                            var maxwidth = $('#width').val();
                            var maxFileSize = ~~max_filesize * 1024;
                            if (file.size > maxFileSize) {
                                jQuery('#file').val('');
                                jQuery("#views").empty();
                                jQuery('#action_buttons').css({"display": "none"});
                                alert('File size exceeds ' + max_filesize + ' KB');
                                return false;
                            }
                            var reader = new FileReader();
                            canvas = null;
                            //Read the contents of Image File.
                            reader.readAsDataURL(this.files[0]);
                            reader.onload = function (e) {
                                //Initiate the JavaScript Image object.
                                var image1 = new Image();
                                //Set the Base64 string return from FileReader as source.
                                image1.src = e.target.result;
                                image1.onload = function () {
                                    //Determine the Height and Width.
                                    var height = this.height;
                                    var width = this.width;
                                    if (height > maxheight || width > maxwidth) {
                                        $('#file').val('');
                                        $("#views").empty();
                                        $('#action_buttons').css({"display": "none"});
                                        alert("Height and Width must not exceed " + maxwidth + " * " + maxheight + "pixels.");
                                        return false;
                                    }
                                    image = new Image();
                                    image.onload = validateImage;
                                    image.src = e.target.result;
                                    $('#action_buttons').css({"display": "block"});
                                };
                            }
                        } else {
                            jQuery('#file').val('');
                            jQuery("#views").empty();
                            jQuery('#action_buttons').css({"display": "none"});
                        }
                    });
                });
                jQuery('#profile_pic_modal').on('hidden.bs.modal', function () {
                    jQuery('#file').val('');
                    jQuery("#views").empty();
                    jQuery('#action_buttons').css({"display": "none"});
                });
                function dataURLtoBlob(dataURL) {
                    var BASE64_MARKER = ';base64,';
                    if (dataURL.indexOf(BASE64_MARKER) == -1) {
                        var parts = dataURL.split(',');
                        var contentType = parts[0].split(':')[1];
                        var raw = decodeURIComponent(parts[1]);
                        return new Blob([raw], {
                            type: contentType
                        });
                    }
                    var parts = dataURL.split(BASE64_MARKER);
                    var contentType = parts[0].split(':')[1];
                    var raw = window.atob(parts[1]);
                    var rawLength = raw.length;
                    var uInt8Array = new Uint8Array(rawLength);
                    for (var i = 0; i < rawLength; ++i) {
                        uInt8Array[i] = raw.charCodeAt(i);
                    }

                    return new Blob([uInt8Array], {
                        type: contentType
                    });
                }

                function validateImage() {
                    if (canvas != null) {
                        image = new Image();
                        image.onload = restartJcrop;
                        image.src = canvas.toDataURL('image/jpg');
                    } else
                        restartJcrop();
                }

                function restartJcrop() {
                    if (jcrop_api != null) {
                        jcrop_api.destroy();
                    }
                    jQuery("#views").empty();
                    jQuery("#views").append("<canvas id=\"canvas\">");
                    canvas = $("#canvas")[0];
                    context = canvas.getContext("2d");
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context.drawImage(image, 0, 0);
                    jQuery("#canvas").Jcrop({
                        onSelect: selectcanvas,
                        onRelease: clearcanvas,
                        bgColor: 'white',
                        aspectRatio: 1,
                        fillColor: '#fff',
                        boxWidth: crop_max_width,
                        boxHeight: crop_max_height
                    }, function () {
                        jcrop_api = this;
                    });
                    clearcanvas();
                }

                function clearcanvas() {
                    prefsize = {
                        x: 0,
                        y: 0,
                        w: canvas.width,
                        h: canvas.height,
                    };
                }

                function selectcanvas(coords) {
                    prefsize = {
                        x: Math.round(coords.x),
                        y: Math.round(coords.y),
                        w: Math.round(coords.w),
                        h: Math.round(coords.h)
                    };
                }

                function applyCrop() {
                    canvas.width = prefsize.w;
                    canvas.height = prefsize.h;
                    context.drawImage(image, prefsize.x, prefsize.y, prefsize.w, prefsize.h, 0, 0, canvas.width, canvas.height);
                    validateImage();
                }

                function applyRotate() {
                    canvas.width = image.height;
                    canvas.height = image.width;
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    context.translate(image.height / 2, image.width / 2);
                    context.rotate(Math.PI / 2);
                    context.drawImage(image, -image.width / 2, -image.height / 2);
                    validateImage();
                }

                function applyHflip() {
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    context.translate(image.width, 0);
                    context.scale(-1, 1);
                    context.drawImage(image, 0, 0);
                    validateImage();
                }

                function applyVflip() {
                    context.clearRect(0, 0, canvas.width, canvas.height);
                    context.translate(0, image.height);
                    context.scale(1, -1);
                    context.drawImage(image, 0, 0);
                    validateImage();
                }

                $("#cropbutton").click(function (e) {
                    applyCrop();
                });
                $("#rotatebutton").click(function (e) {
                    applyRotate();
                });
                $("#hflipbutton").click(function (e) {
                    applyHflip();
                });
                $("#vflipbutton").click(function (e) {
                    applyVflip();
                });
                jQuery("#form").submit(function (e) {
                    e.preventDefault();
                    var profile_image_name = fileName;
                    formData = new FormData($(this)[0]);
                    var blob = dataURLtoBlob(canvas.toDataURL('image/jpg'));
                    //---Add file blob to the form data
                    formData.append("user_id", '<?php echo $_SESSION['uid'] ?>');
                    formData.append("cropped_image", blob);
                    $.ajax({
                        url: "<?php echo ADMIN_HTTP_PATH ?>ClientUserProfile",
                        type: "POST",
                        data: formData,
                        contentType: false,
                        cache: false,
                        processData: false,
                        success: function (data) {
                            if (typeof data === 'string') {
                                data = data.trim();
                            }
                            if (data) {
                                alert("Error");
                            } else {
                                location.reload();
                            }
                        },
                        error: function (data) {
                            alert("Error");
                        },
                        complete: function (data) {}
                    });
                });
                $('#delete_image').on('click', function (e) {
                    if (confirm("Are you sure want to delete?")) {
                        e.preventDefault();
                        var profile_image_name = $('#profile_image_name').val();
                        $.ajax({
                            url: "<?php echo ADMIN_HTTP_PATH ?>ClientUserProfile",
                            type: "GET",
                            data: {"user_id":<?php echo $_SESSION['uid'] ?>, "mode": "delete", "file_name": profile_image_name},
                            success: function (data) {
                                if (typeof data === 'string') {
                                    data = data.trim();
                                }
                                if (data) {
                                    alert("Error");
                                } else {
                                    location.reload();
                                }
                            },
                            error: function (data) {
                                alert("Error");
                            },
                            complete: function (data) {}
                        });
                    }
                });
            </script>
        </body>
    </html>
<?php } ?>
