<?php

/*
 *
This Class was Created using My MasterClass on  12/07/2022 11:10:30 am. 
*/

class UsersModel
{

    private $result;

    protected $conn;

    protected $db;

    private $firstname, $lastname,  $usertype, $tel,  $email, $username, $password, $ebay_store, $amazon_store, $dnp, $fbm, $address, $terms, $amz;

    function __construct()
    {

        $this->db = new Config();

        $this->conn = $this->db->getConnection();
    }
    function initializeUsers($firstname, $lastname, $usertype,  $tel, $email, $username, $password, $ebay_store, $amazon_store, $dnp, $fbm)
    {
        $this->firstname = $firstname;
        $this->lastname = $lastname;

        $this->usertype = $usertype;
        $this->tel = $tel;
        $this->email = $email;
        $this->username = $username;
        $this->password = $this->encryptPassword($password);
    }

    function addNewUsers()
    {

        if ($this->validateUserExist()) {
            $this->result = "Sorry, member with similar Username/Email Already Exists";
        } else {
            try {
                $sqlQuery = "insert into users(firstname,lastname,usertype,tel,email,username,password)
                     values (:firstname,:lastname,:usertype,:tel,:email,:username,:password)";

                $stmt = $this->conn->prepare($sqlQuery);
                $row2 = $stmt->execute(
                    array(
                        ":firstname" => $this->firstname,
                        ":lastname" => $this->lastname,

                        ":usertype" => $this->usertype,
                        ":tel" => $this->tel,

                        ":email" => $this->email,
                        ":username" => $this->username,
                        ":password" => $this->password
                    )
                );

                if ($row2) {
                    $this->result = "User Added!";
                    return $this->DuplicateUserInControl();
                } else {
                    $this->result = "Registration Failed";
                }
            } catch (Exception $exc) {
                $this->result = "Unexpected Error Occured.Consult admin for assistance.";
            }
        }

        return FALSE;
    }

    function DuplicateUserInControl()
    {

        include_once '../../../control/Config.php';
        $db_c = new ConfigMain();
        $conn_c = $db_c->getConnection();

        try {
            $sqlQuery = "insert into users(brandid,firstname,lastname,usertype,tel,email,username,password)
                     values (:brandid,:firstname,:lastname,:usertype,:tel,:email,:username,:password)";

            $stmt = $conn_c->prepare($sqlQuery);
            $row2 = $stmt->execute(
                array(
                    ":brandid" => $_SESSION['brandid'],
                    ":firstname" => $this->firstname,
                    ":lastname" => $this->lastname,

                    ":usertype" => $this->usertype,
                    ":tel" => $this->tel,

                    ":email" => $this->email,
                    ":username" => $this->username,
                    ":password" => $this->password
                )
            );

            if ($row2) {
                $this->result = "User registered successfully!";
                return true;
            } else {
                $this->result = "Registration Failed";
            }
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured.Consult admin for assistance.";
        }
        return FALSE;
    }


    function returnAddress($address)
    {

        try {
            $clientid = $_SESSION["userid_brand"];
            $sqlQuery = "update users set address=:address where id=:clientid";
            $stmt = $this->conn->prepare($sqlQuery);
            $row = $stmt->execute(array(
                ":clientid" => $clientid,
                ":address" => $address

            ));
            if ($row) {
                return true;
            }
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured";
        }
        return false;
    }
    
    public function updateUsers(int $id)
{
    try {
        // 1. Get current username from DB
        $stmt = $this->conn->prepare("SELECT username FROM users WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            $this->result = "User not found.";
            return false;
        }

        $oldUsername = $row['username'];   // <--- important!

        // 2. Update main DB using ID
        $sql = "UPDATE users 
                SET firstname = :firstname,
                    lastname  = :lastname,
                    usertype  = :usertype,
                    tel       = :tel,
                    email     = :email,
                    username  = :new_username
                WHERE id = :id";

        $stmt = $this->conn->prepare($sql);
        $ok1 = $stmt->execute([
            ':firstname'    => $this->firstname,
            ':lastname'     => $this->lastname,
            ':usertype'     => $this->usertype,
            ':tel'          => $this->tel,
            ':email'        => $this->email,
            ':new_username' => $this->username,  // from form/setter
            ':id'           => $id
        ]);

        // 3. Mirror update in control DB using old username
        $ok2 = $this->updateUserInControlByUsername($oldUsername, $this->username);

        if ($ok1 && $ok2) {
            $this->result = "User updated successfully.";
            return true;
        }

        $this->result = $ok1
            ? "Updated locally, but failed to update in control DB."
            : "Failed to update user.";
        return false;

    } catch (Exception $e) {
        $this->result = "Unexpected error occurred.";
        return false;
    }
}
private function updateUserInControlByUsername(string $oldUsername, string $newUsername)
{
    include_once '../../../control/Config.php';
    $db_c   = new ConfigMain();
    $conn_c = $db_c->getConnection();

    $sql = "UPDATE users 
            SET firstname = :firstname,
                lastname  = :lastname,
                usertype  = :usertype,
                tel       = :tel,
                email     = :email,
                username  = :new_username
            WHERE username = :old_username";

    $stmt = $conn_c->prepare($sql);
    return $stmt->execute([
        ':firstname'    => $this->firstname,
        ':lastname'     => $this->lastname,
        ':usertype'     => $this->usertype,
        ':tel'          => $this->tel,
        ':email'        => $this->email,
        ':new_username' => $newUsername,
        ':old_username' => $oldUsername
    ]);
}


    
    
    function validateUserExist()
    { //To prevent Duplicate
        try {
            $sqlQuery = "select * from users where  email=:email or username=:username";
            $stmt = $this->conn->prepare($sqlQuery);
            $stmt->execute(array(
                ':email' => $this->email,
                ':username' => $this->username
            ));
            $row = $stmt->fetch();
            if ($row) {
                return TRUE;
            }
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured";
        }
        return false;
    }


    function loadUsers()
    {
        try {
            $Userslist = array();
            $sqlQuery = "select * from users WHERE id!=1 ";
            $stmt = $this->conn->prepare($sqlQuery);
            $stmt->execute();
            while ($row = $stmt->fetch()) {
                $shop_array = array();
                $shop_array["id"] = $row["id"];
                $shop_array["firstname"] = $row["firstname"];
                $shop_array["lastname"] = $row["lastname"];

                $shop_array["usertype"] = "";

                if ($row["usertype"] == 1) {
                    $shop_array["usertype"] =  "Admin";
                } else if ($row["usertype"] == 2) {
                    $shop_array["usertype"] = "Client";
                } else if ($row["usertype"] == 3) {
                    $shop_array["usertype"] = "VA";
                }

                $shop_array["tel"] = $row["tel"];
                //$shop_array["address"] = $row["address"];
                $shop_array["email"] = $row["email"];
                $shop_array["username"] = $row["username"];

                array_push($Userslist, $shop_array);
            }
            $myJSON = json_encode($Userslist);
            return $myJSON;
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured";
        }
        return false;
    }

    function retrieveUsersById($id)
    {
        try {
            $Userslist = array();
            $sqlQuery = "select * from users where id=$id;";
            $stmt = $this->conn->prepare($sqlQuery);
            $stmt->execute();
            $row = $stmt->fetch();
            if ($row) {

                $this->initializeUsers($row["firstname"], $row["lastname"], $row['usertype'], $row["tel"], $row["email"], $row["username"], $row["password"], '', '', '', '');
            }
            $myJSON = json_encode($Userslist);
            return $myJSON;
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured";
        }
        return false;
    }
    function resetPassword($userid, $pswd)
{
    try {
        // Look up the username for this id
        $stmt = $this->conn->prepare("SELECT username FROM users WHERE id = :id");
        $stmt->execute([':id' => $userid]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row || empty($row['username'])) {
            $this->result = "User not found.";
            return false;
        }

        // Defer to the username-based updater (updates both DBs)
        return $this->resetPasswordByUsername($row['username'], $pswd);

    } catch (Exception $e) {
        $this->result = "Unexpected Error Occurred";
        return false;
    }
}

private function updatePasswordInControlByUsername(string $username, string $hashed): bool
{
    include_once '../../../control/Config.php';
    $db_c  = new ConfigMain();
    $conn_c = $db_c->getConnection();

    $sql = "UPDATE users SET password = :password WHERE username = :username";
    $stmt = $conn_c->prepare($sql);
    return $stmt->execute([
        ':password' => $hashed,
        ':username' => $username
    ]);
}

public function resetPasswordByUsername(string $username, string $newPassword): bool
{
    try {
        $hashed = $this->encryptPassword($newPassword);

        // 1) Update in your local/app DB by username
        $sql = "UPDATE users SET password = :password WHERE username = :username";
        $stmt = $this->conn->prepare($sql);
        $ok1  = $stmt->execute([
            ':password' => $hashed,
            ':username' => $username
        ]);

        // 2) Mirror to control DB by the same username
        $ok2 = $this->updatePasswordInControlByUsername($username, $hashed);

        if ($ok1 && $ok2) {
            $this->result = "Password changed successfully.";
            return true;
        }

        $this->result = $ok1
            ? "Updated locally, but failed to update in control DB."
            : "Failed to update password.";
        return false;

    } catch (Exception $e) {
        $this->result = "Unexpected Error Occurred";
        return false;
    }
}


     public function deleteUsers(int $id)
{
    try {
        // 1. Get current username from DB
        $stmt = $this->conn->prepare("SELECT username FROM users WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            $this->result = "User not found.";
            return false;
        }

        $oldUsername = $row['username'];

        // 2. Delete from main DB using ID
        $sqlQuery = "DELETE FROM users WHERE id = :id";
        $stmt = $this->conn->prepare($sqlQuery);
        $ok1 = $stmt->execute([":id" => $id]);

        // 3. Mirror delete in control DB using old username
        $ok2 = $this->deleteUserInControlByUsername($oldUsername);

        if ($ok1 && $ok2) {
            $this->result = "User deleted successfully.";
            return true;
        }

        $this->result = $ok1
            ? "Deleted locally, but failed to delete in control DB."
            : "Failed to delete user.";
        return false;

    } catch (Exception $e) {
        $this->result = "Unexpected error occurred.";
        return false;
    }
}
private function deleteUserInControlByUsername(string $oldUsername): bool
{
    include_once '../../../control/Config.php';
    $db_c   = new ConfigMain();
    $conn_c = $db_c->getConnection();

    $sqlQuery = "DELETE FROM users WHERE username = :old_username";
    $stmt = $conn_c->prepare($sqlQuery);
    return $stmt->execute([":old_username" => $oldUsername]);
}



    function encryptPassword($password)
    {
        $static_salt = 'asdfdavfqwertyuiop123ABC';

        $username = "masterhighrise";
        return hash('sha512', $password . $static_salt . $username);
    }
    ///LOGIN AUTHENTICATION-------------------------------
    function loginUser($username, $password)
    {
        try {
            $sqlQuery = "select * from users 
        where username=:username and password=:password;";
            $stmt = $this->conn->prepare($sqlQuery);
            $stmt->execute(array(':password' => $this->encryptPassword($password), ':username' => trim($username)));
            $row = $stmt->fetch();
            if ($row) {
                $this->result = $row['usertype'];
                return $this->configureUserSessions($row['id'],  $row['username'], $row['firstname'], $row['lastname'], $row['usertype'], $row['email'], '', '', '');
            } else {
                $this->result = "Invalid Username/Password";
            }
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured";
        }
        return false;
    }
    function configureUserSessions($id, $username, $firstname, $lastname, $usertype, $email, $terms, $amz)
    {


        $_SESSION['userid_brand'] = $id;
        $_SESSION['username'] = $username;
        $_SESSION['firstname'] = $firstname;
        $_SESSION['lastname'] = $lastname;
        $_SESSION['usertype'] = $usertype;
        $_SESSION['email'] = $email;
        $_SESSION['terms'] = $terms;
        $_SESSION['amz'] = $amz;

        if (!empty($_SESSION['userid_brand'])) {
            return true;
        } else {
            $this->result = "Sorry! User Not Yet Set. Try Again Please";
        }

        return false;
    }

    function getUserInfo($id)
    {
        try {

            $sqlQuery = "select * from users where id=$id";
            $stmt = $this->conn->prepare($sqlQuery);
            $stmt->execute();
            $row = $stmt->fetch();
            if ($row) {
                return $row;
            }
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured";
        }
        return false;
    }
    
    function getUser($id)
    {
        try {

            $sqlQuery = "select username from users where id=$id";
            $stmt = $this->conn->prepare($sqlQuery);
            $stmt->execute();
            $row = $stmt->fetch();
            if ($row) {
                return $row['username'];
            }
        } catch (Exception $exc) {
            $this->result = "Unexpected Error Occured";
        }
        return false;
    }

    //Accesors and Mutators


    function getFirstname()
    {
        return $this->firstname;
    }
    function setFirstname($firstname)
    {
        $this->firstname = $firstname;
    }

    function getLastname()
    {
        return $this->lastname;
    }
    function setLastname($lastname)
    {
        $this->lastname = $lastname;
    }



    function getusertype()
    {
        return $this->usertype;
    }
    function setusertype($usertype)
    {
        $this->usertype = $usertype;
    }

    function getTel()
    {
        return $this->tel;
    }
    function setTel($tel)
    {
        $this->tel = $tel;
    }



    function getEmail()
    {
        return $this->email;
    }
    function setEmail($email)
    {
        $this->email = $email;
    }

    function getUsername()
    {
        return $this->username;
    }
    function setUsername($username)
    {
        $this->username = $username;
    }

    function getPassword()
    {
        return $this->password;
    }
    function setPassword($password)
    {
        $this->password = $password;
    }


    function getEbaystore()
    {
        return $this->ebay_store;
    }
    function setEbaystore($ebay_store)
    {
        $this->ebay_store = $ebay_store;
    }


    function getAmazonstore()
    {
        return $this->amazon_store;
    }
    function setAmazonstore($amazon_store)
    {
        $this->amazon_store = $amazon_store;
    }
    function getDnp()
    {
        return $this->dnp;
    }
    function setDnp($dnp)
    {
        $this->dnp = $dnp;
    }
    function getFbm()
    {
        return $this->fbm;
    }
    function setFbm($fbm)
    {
        $this->fbm = $fbm;
    }
    function setResult($result)
    {
        $this->result = $result;
    }
    function getResult()
    {
        return $this->result;
    }
}
