<?php

class User
{
    public function __construct()
    {
    }

    public function user_authentication($usr_auth_id): array
    {
        $item_details = new ItemDetails();
        $beautify_arr = new ItemBeautify();

        $user_auth_data = $item_details->details_item_user("authorize_token='$usr_auth_id' AND status='true'");
        $usr_data = [];
        if (count($user_auth_data) == 1) {
            foreach ($user_auth_data as $single_auth_data) {

                if ($single_auth_data["type"] == "manager") {
                    $tmp_usr_type = false;
                } else {
                    $tmp_usr_type = true;
                }
                $usr_data = ["status" => $single_auth_data["status"], "id" => $single_auth_data["id"], "type" => $tmp_usr_type];
                $beautify_arr->beautify($single_auth_data, ["authorize_token", "first_name", "last_name", "mail", "password", "reset_code", "reset_time", "verification_code", "verification_status", "status", "date_time"]);
            }
        } else {
            $usr_data = ["status" => false];
        }

        return $usr_data;
    }

    public function user_list($input_data, $usr_type): array
    {

        $output_message = new OutputMessage();
        $item_details = new ItemDetails();
        $beautify_arr = new ItemBeautify();

        $usr_data = [];

        if (!$usr_type) {
            $input_data->usr_type = "inspector";
        }

        $tmp_user_data = $item_details->details_item_user("authorize_token!='" . $input_data->usr_auth . "' AND status!='delete' AND usr_type='" . $input_data->usr_type . "' ORDER BY verification_status ASC");


        if (count($tmp_user_data) > 0) {
            foreach ($tmp_user_data as $single_user) {
                $single_user = $beautify_arr->beautify($single_user, ["authorize_token", "password", "reset_code", "reset_time", "type", "verification_code", "reset_status", "date_time"]);
                $usr_data[] = $single_user;
            }
            $api_output = $output_message->successOutput($usr_data, 'All User(s) Loaded');
        } else {
            $api_output = $output_message->errorOutput('No User available');
        }


        return $api_output;
    }

    public function user_login($input_data): array
    {
        $output_message = new OutputMessage();
        $item_details = new ItemDetails();
        $beautify_arr = new ItemBeautify();

        $usr_mail = $input_data->usr_mail;
        $usr_pass = $input_data->usr_password;

        $user_details_data = $item_details->details_item_user("mail='$usr_mail' AND status='true'");

        if ($user_details_data[0]['id'] != null) {
            if (password_verify($usr_pass, $user_details_data[0]['password'])) {
                $single_user = $beautify_arr->beautify($user_details_data[0], ["alias", "first_name", "id", "last_name", "mail", "password", "reset_code", "reset_status", "reset_time", "status", "user_img", "verification_code", "verification_status", "date_time"]);
                $usr_data = $single_user;

                $api_output = $output_message->successOutput($usr_data, 'Login Successful');
            } else {
                $api_output = $output_message->errorOutput('Incorrect Password');
            }
        } else {
            $api_output = $output_message->errorOutput('Incorrect Username');

        }

        return $api_output;
    }

    public function user_profile_details($input_data): array
    {
        $item_details = new ItemDetails();
        $output_message = new OutputMessage();
        $beautify_arr = new ItemBeautify();

        $user_profile_data = [];

        $user_profile_details_data = $item_details->details_item_user("authorize_token='$input_data->usr_auth'");

        if (count($user_profile_details_data) > 0) {
            foreach ($user_profile_details_data as $single_user_profile) {
                $single_user_profile = $beautify_arr->beautify($single_user_profile, ["id", "authorize_token", "emp_id", "phone", "mail", "password", "reset_code", "reset_time", "reset_status", "verification_code", "verification_status", "type", "status", "date_time"]);

                $user_profile_data = $single_user_profile;
            }
            $api_output = $output_message->successOutput($user_profile_data, "User details loaded successfully");
        } else {
            $api_output = $output_message->errorOutput("USER DETAILS ERROR");
        }

        return $api_output;
    }

    public function user_details($input_data): array
    {

        $item_details = new ItemDetails();
        $output_message = new OutputMessage();
        $beautify_arr = new ItemBeautify();

        $user_data = [];

        $user_details_data = $item_details->details_item_user("uid='$input_data->usr_id' AND usr_type='" . $input_data->usr_type . "' AND status='true'");
       
        if (count($user_details_data) > 0) {
            foreach ($user_details_data as $single_user) {
                // $single_user = $beautify_arr->beautify($single_user, ["id", "authorize_token", "user_img", "password", "reset_code", "reset_time", "type", "access_level", "verification_code", "verification_status", "status", "reset_status", "date_time"]);

                $single_user = $beautify_arr->beautify($single_user, ["id", "authorize_token", "user_img", "password", "reset_code", "reset_time", "type", "access_level", "verification_code", "verification_status", "status", "reset_status", "date_time"]);


                $user_data = $single_user;
            }
            // echo "Finlly here............";
            // echo "<pre>"; print_r($user_data); echo "</pre>";
            // die;
            $api_output = $output_message->successOutput($user_data, "User details loaded successfully");
        } else {
            $api_output = $output_message->errorOutput("USER DETAILS ERROR");
        }

        return $api_output;
    }

    public function user_settings($input_data, $usr_type): array
    {
        $item_details = new ItemDetails();
        $output_message = new OutputMessage();
        $beautify_arr = new ItemBeautify();

        $user_data = [];

        $user_details_data = $item_details->details_item_user("authorize_token='$input_data->usr_auth'");

        if (count($user_details_data) > 0) {
            foreach ($user_details_data as $single_user) {
                $single_user = $beautify_arr->beautify($single_user, ["id", "authorize_token", "password", "reset_code", "reset_time", "reset_status", "verification_code", "verification_status", "status", "date_time"]);
                if (!$usr_type) {
                    $single_user = $beautify_arr->beautify($single_user, ["type", "manager_price"]);
                }
                $user_data = $single_user;
            }


            $api_output = $output_message->successOutput($user_data, "User details loaded successfully");
        } else {
            $api_output = $output_message->errorOutput("USER DETAILS ERROR");
        }

        return $api_output;
    }

    public function user_manage($manage_type, $input_data, $usr_type)
    {
        // echo "Manage Type   ".$manage_type;
        // echo "<pre>"; print_r($input_data); echo "</pre>";
        // echo "<pre>"; print_r($usr_type); echo "<pre>";
        // die;
        $item_manage = new ItemManage();
        $item_details = new ItemDetails();
        $output_message = new OutputMessage();

        if ($manage_type == "add") {
            $user_details_data = $item_details->details_item_user("mail='" . $input_data->usr_mail . "'");

            if (count($user_details_data) > 0) {
                return $output_message->errorOutput("Email Already Registered", "warning");
            }
        }

        if ($input_data->usr_type == "inspector") {
            $input_data->usr_verification_status = "true";
        } else {
            $input_data->usr_verification_status = "false";
        }

        if ($manage_type == "delete") {
            $user_details_data = $item_details->details_item_user("uid='" . $input_data->usr_id . "'");
            $input_data->usr_type= $user_details_data[0]["type"];
        }

        $user_request_data = $item_manage->manage_item_user($manage_type, $input_data);

        if ($user_request_data) {
            if ($manage_type == "add" && $input_data->usr_type=="manager") {
                $tmp_usr_data = $item_details->details_item_user("mail='" . $input_data->usr_mail . "'");
                if (count($tmp_usr_data) > 0) {
                    $tmp_usr_details = new stdClass();
                    $tmp_usr_details->usr_id = $tmp_usr_data[0]["id"];
                    $mail_status = $this->user_verification_mail($tmp_usr_details, $usr_type);
                    if ($mail_status) {
                        $api_output = $output_message->successOutput("", "User " . join(" ", explode("-", $manage_type)) . " successfully");
                    } else {
                        $api_output = $output_message->errorOutput("USER " . join(" ", explode("-", $manage_type)) . " ERROR");
                    }
                } else {
                    $api_output = $output_message->errorOutput("USER " . join(" ", explode("-", $manage_type)) . " ERROR");
                }
            } else {
                $api_output = $output_message->successOutput("", "User " . join(" ", explode("-", $manage_type)) . " successfully");
            }
        } else {
            $api_output = $output_message->errorOutput("USER " . join(" ", explode("-", $manage_type)) . " ERROR");
        }

        return $api_output;
    }

    public function user_verification_mail($input_data, $usr_type): array
    {
        $output_message = new OutputMessage();
        $item_details = new ItemDetails();
        $item_manage = new ItemManage();
        $mail = new Mail();

        if (!$usr_type) {
            return $output_message->errorOutput();
        }

        $usr_details_data = $item_details->details_item_user("uid='$input_data->usr_id'");

        if ($usr_details_data) {
            $reset_verify_code = $item_manage->manage_item_user("re-verify", $input_data);
            if ($reset_verify_code) {
                $tmp_usr_details_data = $item_details->details_item_user("uid='$input_data->usr_id'");
                if ($tmp_usr_details_data) {
                    $mail_template = str_replace("{{user_name}}", $tmp_usr_details_data[0]["first_name"] . " " . $tmp_usr_details_data[0]["last_name"], file_get_contents("lib/template/email/template_verification.html"));
                    $mail_template = str_replace("{{verification_code}}", $tmp_usr_details_data[0]["verification_code"], $mail_template);
                    $send_mail_status = $mail->send_mail($tmp_usr_details_data[0]["mail"], $tmp_usr_details_data[0]["first_name"] . " " . $tmp_usr_details_data[0]["last_name"], "Verify Account", $mail_template, null, true);
                } else {
                    $send_mail_status = false;
                }
            } else {
                $send_mail_status = false;
            }
        } else {
            $send_mail_status = false;
        }


        if ($send_mail_status) {
            $api_output = $output_message->successOutput("", "Verification Mail Send successfully");
        } else {
            $api_output = $output_message->errorOutput("Verification Mail Send ERROR");
        }

        return $api_output;
    }

    public function user_change_image($input_data)
    {
        $item_details = new ItemDetails();
        $item_manage = new ItemManage();
        $output_message = new OutputMessage();
        $api_output = "";


        $usr_details = $item_details->details_item_user("authorize_token='$input_data->usr_auth'");

        if (count($usr_details) > 0) {
            $upload_img_status = $item_manage->manage_item_file($input_data->usr_img_name, $input_data->usr_img_data);
            if ($upload_img_status[0]) {
                $input_data->usr_img_id = $upload_img_status[1];
                $user_request_data = $item_manage->manage_item_user("change-image", $input_data);
                if ($user_request_data) {
                    $api_output = $output_message->successOutput("", "User change image successfully");
                } else {
                    $api_output = $output_message->errorOutput("USER Change image ERROR");
                }
            }
        } else {
            $api_output = $output_message->errorOutput("USER Change image ERROR");
        }
        return $api_output;
    }

    //Upload File
    function user_upload_file($input_data)
    {
        // echo "Weocmoe to upload file function";
        // echo "<pre>"; print_r($_REQUEST); echo "</pre>"; 
        // echo "<pre>"; print_r($_FILES); echo "</pre>"; 
        // die;

        // echo "<pre>"; print_r($input_data); echo "</pre>"; die;
        $item_details = new ItemDetails();
        $item_manage = new ItemManage();
        $output_message = new OutputMessage();
        $api_output = "";


        $usr_details = $item_details->details_item_user("authorize_token='$input_data->usr_auth'");

        if (count($usr_details) > 0) {
            $upload_img_status = $item_manage->manage_item_file($input_data->usr_img_name, $input_data->usr_img_data);
            if ($upload_img_status[0]) {
                $input_data->usr_img_id = $upload_img_status[1];
                $user_request_data = $item_manage->manage_item_user("change-image", $input_data);
                if ($user_request_data) {
                    $api_output = $output_message->successOutput("", "User change image successfully");
                } else {
                    $api_output = $output_message->errorOutput("USER Change image ERROR");
                }
            }
        } else {
            $api_output = $output_message->errorOutput("USER Change image ERROR");
        }
        return $api_output;
    }
    public function user_update_password($input_data): array
    {
        $output_message = new OutputMessage();
        $item_manage = new ItemManage();
        $item_details = new ItemDetails();


        $usr_data = $item_details->details_item_user("authorize_token='$input_data->usr_auth'");

        if ($usr_data) {
            if (password_verify($input_data->usr_password_old, $usr_data[0]['password'])) {
                $usr_manage_data = $item_manage->manage_item_user("update-pass", $input_data);
                if ($usr_manage_data) {
                    $api_output = $output_message->successOutput('', 'Password Changed Successfully');
                } else {
                    $api_output = $output_message->errorOutput('Server Error!!!');
                }
            } else {
                $api_output = $output_message->errorOutput('Invalid Current Password');
            }
        } else {
            $api_output = $output_message->errorOutput('Not Enough Data To Process');
        }

        return $api_output;
    }

    public function user_verification_code($manage_type, $input_data)
    {

        $output_message = new OutputMessage();
        $item_details = new ItemDetails();
        $item_manage = new ItemManage();
        $api_output = "";

        $tmp_pass = $this->random_password();
        $input_data->usr_password = $tmp_pass;


        $user_details_data = $item_details->details_item_user("mail='$input_data->usr_mail' AND status='true'");

        if ($user_details_data) {
            if ($manage_type == "verify-account") {
                if ($user_details_data[0]['verification_status']) {
                    $api_output = $output_message->successOutput("", "User Already verified");
                } else {
                    if ($user_details_data[0]['verification_code'] == $input_data->usr_verification_code) {
                        $verify_usr_status = $item_manage->manage_item_user("verify", $input_data);
                        if ($verify_usr_status) {
                            $mail_status = $this->send_verification_mail($user_details_data[0]["first_name"] . " " . $user_details_data[0]["last_name"], $tmp_pass, $input_data->usr_mail);
                            if ($mail_status) {
                                $api_output = $output_message->successOutput("", "User verified successfully");
                            } else {
                                $api_output = $output_message->errorOutput("Server Error!!!");
                            }
                        } else {
                            $api_output = $output_message->errorOutput("User Verification Error");
                        }
                    } else {
                        $api_output = $output_message->errorOutput("Invalid Verification Code");
                    }
                }
            }
            if ($manage_type == "reset-account") {
                if (!$user_details_data[0]['reset_status']) {
                    $api_output = $output_message->successOutput("", "Password Already Reset");
                } else {
                    if ($user_details_data[0]['reset_code'] == $input_data->usr_verification_code) {
                        if (time() > strtotime($user_details_data[0]['reset_time'])) {
                            $api_output = $output_message->errorOutput("Invalid Reset Code");
                        } else {
                            $input_data->usr_auth = $user_details_data[0]['authorize_token'];

                            $reset_usr_status = $item_manage->manage_item_user("update-pass", $input_data);
                            if ($reset_usr_status) {
                                $mail_status = $this->send_verification_mail($user_details_data[0]["first_name"] . " " . $user_details_data[0]["last_name"], $tmp_pass, $input_data->usr_mail);
                                if ($mail_status) {
                                    $api_output = $output_message->successOutput("", "Check your mail for temporary password");
                                } else {
                                    $api_output = $output_message->errorOutput("Server Error!!!");
                                }
                            } else {
                                $api_output = $output_message->errorOutput("Reset Password Error");
                            }
                        }

                    } else {
                        $api_output = $output_message->errorOutput("Invalid Reset Code");
                    }
                }
            }
        } else {
            $api_output = $output_message->errorOutput("Invalid Email ID");
        }
        return $api_output;
    }

    private function random_password(): string
    {
        $alpha_small = 'abcdefghijklmnopqrstuvwxyz';
        $alpha_large = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $number = '0123456789';
        $spl_chr = '!@#$%&*';
        $randomString = '';
        $tmp_pass = [$alpha_small, $alpha_large, $number, $spl_chr, $number, $alpha_large, $spl_chr, $alpha_small];

        for ($i = 0; $i < sizeof($tmp_pass); $i++) {
            $randomString .= $tmp_pass[$i][rand(0, strlen($tmp_pass[$i]) - 1)];
        }

        return str_shuffle($randomString);
    }

    private function send_verification_mail($user_name, $user_code, $usr_mail): bool
    {
        $mail = new Mail();
        $mail_template = str_replace("{{user_name}}", $user_name, file_get_contents("lib/template/email/template_password_auto.html"));
        $mail_template = str_replace("{{password}}", $user_code, $mail_template);

        return $mail->send_mail($usr_mail, $user_name, "Verification Completed", $mail_template, null, true);
    }

    public function user_reset_code($input_data): array
    {
        $output_message = new OutputMessage();
        $item_details = new ItemDetails();
        $item_manage = new ItemManage();
        $mail = new Mail();

        $usr_mail = $input_data->usr_mail;

        $user_mail_data = $item_details->details_item_user("mail='$usr_mail' AND status='true'");

        if ($user_mail_data[0]['id'] != null) {
            $user_reset_pass_data = $item_manage->manage_item_user("reset-pass", $input_data);
            if ($user_reset_pass_data) {
                $tmp_usr_details_data = $item_details->details_item_user("mail='$usr_mail'");
                if ($tmp_usr_details_data) {
                    $mail_template = str_replace("{{user_name}}", $tmp_usr_details_data[0]["first_name"] . " " . $tmp_usr_details_data[0]["last_name"], file_get_contents("lib/template/email/template_reset.html"));
                    $mail_template = str_replace("{{reset_code}}", $tmp_usr_details_data[0]["reset_code"], $mail_template);
                    $send_mail_status = $mail->send_mail($tmp_usr_details_data[0]["mail"], $tmp_usr_details_data[0]["first_name"] . " " . $tmp_usr_details_data[0]["last_name"], "Reset Password", $mail_template, null, true);
                } else {
                    $send_mail_status = false;
                }
            } else {
                $send_mail_status = false;
            }
        } else {
            $send_mail_status = false;
        }
        if ($send_mail_status) {
            $api_output = $output_message->successOutput("", "Reset password Mail Send successfully");
        } else {
            $api_output = $output_message->errorOutput("Reset password Mail Send ERROR");
        }

        return $api_output;
    }

    //Update inspector details

    public function update_inspector_details($manage_type, $input_data, $usr_type)
    {
        // echo "<pre>"; print_r($manage_type); echo "</pre>"; 
        // echo "<pre>"; print_r($input_data); echo "</pre>"; 
        // echo "<pre>"; print_r($usr_type); echo "</pre>"; 

        // die;
        
        $item_manage = new ItemManage();
        $item_details = new ItemDetails();
        $output_message = new OutputMessage();

        if ($manage_type == "add") {
            $user_details_data = $item_details->details_item_user("mail='" . $input_data->usr_mail . "'");

            if (count($user_details_data) > 0) {
                return $output_message->errorOutput("Email Already Registered", "warning");
            }
        }

        if ($input_data->usr_type == "inspector") {
            $input_data->usr_verification_status = "true";
        } else {
            $input_data->usr_verification_status = "false";
        }

        if ($manage_type == "delete") {
            $user_details_data = $item_details->details_item_user("uid='" . $input_data->usr_id . "'");
            $input_data->usr_type= $user_details_data[0]["type"];
        }

        $user_request_data = $item_manage->manage_item_user($manage_type, $input_data);

        if ($user_request_data) {
            if ($manage_type == "add" && $input_data->usr_type=="manager") {
                $tmp_usr_data = $item_details->details_item_user("mail='" . $input_data->usr_mail . "'");
                if (count($tmp_usr_data) > 0) {
                    $tmp_usr_details = new stdClass();
                    $tmp_usr_details->usr_id = $tmp_usr_data[0]["id"];
                    $mail_status = $this->user_verification_mail($tmp_usr_details, $usr_type);
                    if ($mail_status) {
                        $api_output = $output_message->successOutput("", "User " . join(" ", explode("-", $manage_type)) . " successfully");
                    } else {
                        $api_output = $output_message->errorOutput("USER " . join(" ", explode("-", $manage_type)) . " ERROR");
                    }
                } else {
                    $api_output = $output_message->errorOutput("USER " . join(" ", explode("-", $manage_type)) . " ERROR");
                }
            } else {
                $api_output = $output_message->successOutput("", "User " . join(" ", explode("-", $manage_type)) . " successfully");
            }
        } else {
            $api_output = $output_message->errorOutput("USER " . join(" ", explode("-", $manage_type)) . " ERROR");
        }

        return $api_output;
    }

}