<?php

session_start();
include_once '../config/database.php';
include_once '../security/csrf.php';
include_once '../config/properties.php';
include_once "../resources/EncryptDecrypt.php";
include_once "../resources/password.php";
$csrf_token = $_POST['csrf_token'];
validate_csrf_request($csrf_token);

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_regenerate_id(true);
                        $_SESSION['uid'] = $user_id;
                        $_SESSION['LAST_ACTIVITY'] = time(); // Update last activity timestamp
                        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")));
    }
}
?>

