<?php

class DbOps
{

    private $con;

    function __construct()
    {
        require_once dirname(__FILE__) . '/DbConnects.php';

        $db = new DbConnect();
        $this->con = $db->connect();
    }



    private function isUserExistReset($username,$email,$code){
        $stmt = $this -> con -> prepare("SELECT * FROM password_reset_request WHERE username = ? and email = ? and arial_code=?");
        $stmt -> bind_param("sss", $username, $email,$code);
        $stmt -> execute();
        $stmt ->  store_result();
        return $stmt -> num_rows > 0;
    }

    public function passreset($username,$email){
        if($this -> isUserExist($username, $email)){
            $status = "Y";
            $random_string = substr(str_shuffle(str_repeat("123456789abcdefghijklmnopqrstuvwxyz", 6)), 0, 6);
            $stmt = $this -> con -> prepare("INSERT INTO  password_reset_request (id,username,email,arial_code,status) VALUES (NULL, ?,?,?,?);");
            $stmt -> bind_param ("ssss", $username, $email,$random_string,$status);
            $message = "This is your reset code <br> <span style='font-weight:bold'> {$random_string} </span> </br> Kindly click on <a href='https://api.treenetlabs.com/android/vi/passreset.php'>this link to Change your password </a> . Please ignore if password reset was not initiated by you.";

            if($stmt -> execute()){
                mail('info@treenetlabs.com', 'Password Reset - OrderApp', $message);

                return  1;

            }else{
                return 0;

            }


        }
    }

    public function checkuserreset($username,$email,$code,$password){
        if($this -> isUserExistReset($username, $email,$code)){
            $password = md5($password);
            $stmts = $this -> con -> prepare("UPDATE users SET password = ? WHERE username = ? and email=?;");
            $stmts -> bind_param ("sss", $password,$username,$email);

            if($stmts -> execute()){

                $stmt = $this -> con -> prepare("DELETE FROM password_reset_request WHERE username = ? and email=? ;");
                $stmt -> bind_param ("ss", $username,$email);


                if($stmt -> execute()){
                    return  1;
                }else{
                    return 0;
                }

            }else{
                return 2;
            }
        }
    }

}