<?php

session_start();
include_once '../config/properties.php';
include_once "../resources/EncryptDecrypt.php";
include_once '../config/database.php';
include_once "../resources/password.php";
if (isset($_POST['password1']) && isset($_POST['password2'])) {
    require("../resources/manageusers.php");

    $user_id = $_POST['id'];
    $password1 = $_POST['password1'];
    $password2 = $_POST['password2'];
    if ($password1 == $password2) {
        $object = new ManageUsers();

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

        if ($passwordRules) {
            $min_length = $passwordRules['min_length'];
            $max_length = $passwordRules['max_length'];
            $uppercase = $passwordRules['uppercase'];
            $lowercase = $passwordRules['lower_case'];
            $numeric = $passwordRules['numeric'];
            $special_char = $passwordRules['special_char'];

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

            if (preg_match($password_regex, $password1)) {
                $login_flag = '1';               
                    $val = $object->ChangePassword($login_flag, $password1, $date_time, $user_id);
                    if ($val) {
                        $_SESSION['uid'] = $user_id;
                        echo json_encode(array("success" => "failure", "result2" => "home.php"));
                    } else {
                        echo json_encode(array("result1" => "failure", "result2" => _("GN0401")));
                    }                
            } else {
                echo json_encode(["result1" => "failure", "result2" => _("LG0103")]); // Password does not meet criteria           
            }
        }
    } else {
        echo json_encode(array("result1" => "failure", "result2" => _("LG0110")));
    }
}
?>

