<?php

class Admin extends Controller
{

    public function login()
    {
        $dataView['title'] = "Admin Login";

        $this->do_login();

        // global $ADMIN_LOGIN
        global $ADMIN_LOGIN;
        // set content
        $ADMIN_LOGIN['files']['content'] = BACK_END_CONTROL_PATH . "admin_login";
        // render template
        $this->loadTemplate($ADMIN_LOGIN, $dataView)->render();
    }

    private function do_login()
    {
        if (isset($_POST['action']) && $_POST['action'] == 'login') {
            $userMail = $this->loadSecurity($_POST['email'])->clear();
            $password = $this->loadSecurity($_POST['password'])->clear();
            // check if empty user name or password
            if (!empty($userMail) && !empty($password)) {
                $userData = $this->loadModel("UserModel")->retrieveAllData("WHERE `mail`=? AND `password`=? AND `job_type`=? AND `status`=? AND `deleted`=?", array($userMail, sha1(md5($password)), 1, 1, 1));
                // check if there is user with mail and password
                if ($userData != NULL) {
                    $user = array_shift($userData);
                    // check if admin type is admin
                    $adminType = $this->loadModel("EmployeeModel")->retrieveAllData("WHERE `user_id` = ? AND `admin_type_id`=? ", array($user['id'], 1));
                    if ($adminType != NULL) {
                        // make array for login and employee id
                        $session_array = array("login" => TRUE, "user_id" => $user['id'], "job_type" => 1, "admin_type" => 1);
                        // load session class and make sessions
                        $this->loadSession($session_array)->setSession();
                        $dataView['status'] = 'success';
                        echo $this->loadAjax()->DataToJson($dataView);
                        exit;
                    } else {
                        $dataView['status'] = 'faild';
                        $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong>Error : </strong>Invalid User Name Or Password.</div>';
                        echo $this->loadAjax()->DataToJson($dataView);
                        exit;
                    }
                } else {
                    $dataView['status'] = 'faild';
                    $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong>Error : </strong>Invalid User Name Or Password.</div>';
                    echo $this->loadAjax()->DataToJson($dataView);
                    exit;
                }
            } else {
                $dataView['status'] = 'faild';
                $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong>Error : </strong>Please Fill All Fields.</div>';
                echo $this->loadAjax()->DataToJson($dataView);
                exit;
            }
        }
    }

    public function logOut()
    {
        if ($this->loadSession()->hasSession("login") && $this->loadSession()->getSession("login") == TRUE) {
            $this->loadSession()->destroySession();
            $this->redirect("admin", "login");
            exit;
        } else {
            $this->redirect("admin", "login");
            exit;
        }
    }

    public function edit_profile()
    {
        /******** start header code ********/
        if (FALSE !== $this->loadHelper("UserHelper")->check_user_login()) {
            // get user id from session
            $user_id = $this->loadSession()->getSession("user_id");
            // get user data for header
            $dataView['userData'] = $this->loadModel("UserModel")->retriveDataById("id", $user_id);
            if ($dataView['userData'] == NULL) {
                $this->redirect("error", "index");
                exit();
            }
        } else {
            $this->redirect("admin", "login");
        }

        /******* end header code *******/

        $id = $user_id;
        // get data
        $dataView['user'] = $this->loadModel("UserModel")->retrieveAllData("WHERE `id` =? AND `job_type` =? AND `deleted` =?", array($id, 1, 1));
        if ($dataView['user'] == NULL) {
            $this->redirect("error", "index");
            exit();
        }
        $dataView['user'] = array_shift($dataView['user']);

        //start Edit profile
        if (isset($_POST['edit'])) {

            // preparing validation array
            $validationArray = array(
                "name" => array(
                    "value" => $this->loadSecurity($_POST['fullName'])->clear(),
                    "errorName" => "Full Name",
                    "rules" => "required|min-length[4]"
                ),
                "phone" => array(
                    "value" => $this->loadSecurity($_POST['phone'])->clear(),
                    "errorName" => "Mobile Number",
                    "rules" => "required"
                ),
                "mail" => array(
                    "value" => $this->loadSecurity($_POST['email'])->clear(),
                    "errorName" => "Email",
                    "rules" => "required|email"
                ),
                "address" => array(
                    "value" => $this->loadSecurity($_POST['address'])->clear(),
                    "errorName" => "Address",
                    "rules" => "required|min-length[3]"
                ),
            );
            // load validation classs and pass validation data
            $dataValid = $this->loadValidation($validationArray)->formValidate();
            // check if the data is ok
            if (is_array($dataValid) && array_key_exists("success", $dataValid)) {
                //check if mail exists before
                if (TRUE !== $this->loadModel("UserModel")->CheckExists("WHERE `mail` =? AND `id`!=? AND `deleted`=?", array($dataValid['success']['mail'], $id, 1))) {
                    //check if phone exists before
                    if (TRUE !== $this->loadModel("UserModel")->CheckExists("WHERE `phone` =?  AND `id`!=? AND `deleted`=?", array($dataValid['success']['phone'], $id, 1))) {

                        if (FALSE !== $this->loadModel("UserModel", $dataValid['success'])->updateData('id', $id)) {
                            $dataView['message'] = '<div class="alert alert-success" role="alert"><staong><i class="fa fa-check" aria-hidden="true"></i> Success </strong> Your Data Updated Successfully Please Wait .. </div>';
                            header("Refresh: 2");
                        } else {
                            $dataView['message'] = '<div class="alert alert-danger" role="alert"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> Error Updating Your Data </div>';
                        }
                    } else {
                        $dataView['message'] = '<div class="alert alert-danger" role="alert"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> User Phone Exists Before </div>';
                    }
                } else {
                    $dataView['message'] = '<div class="alert alert-danger" role="alert"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> User Mail Exists Before </div>';
                }
            } else {
                $dataView['message'] = '<div class="alert alert-danger" role="alert"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong>' . $dataValid . '</div>';
            }
        }
        // set page title
        $dataView['title'] = "Edit Profile";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "admin_edit_profile";
        // load template
        $this->loadTemplate($TEMPLATE_BACK_END, $dataView)->render();
    }

    public function update_profile_image()
    {
        //get id
        $id = (int)$this->loadSession()->getSession("user_id");;
        if ($id == 0) {
            $this->redirect("error", "index");
            exit;
        } else {
            $upload = $this->loadUpload("image_name")->do_upload();
            // check if there is error on image
            if (array_key_exists("uploadError", $upload)) {
                echo $this->loadAjax()->DataToJson(array("status" => "falid"));
                exit;

            } else {
                $dataModel['photo'] = $upload['uploaded'][0];
                if (false !== $this->loadModel("UserModel", $dataModel)->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success", "newImage" => $dataModel['photo']));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "falid"));
                    exit;
                }
            }
        }
    }

    public function update_password()
    {
        //get id
        $id = (int)$this->loadSession()->getSession("user_id");
        if ($id == 0) {
            $this->redirect("error", "index");
            exit;
        } else {
            // preparing validation array
            $validationArray = array(
                "old_password" => array(
                    "value" => $this->loadSecurity($_POST['old_password'])->clear(),
                    "errorName" => "Old Password",
                    "rules" => "required|min-length[6]"
                ),
                "password" => array(
                    "value" => $this->loadSecurity($_POST['password'])->clear(),
                    "errorName" => "New Password",
                    "rules" => "required|min-length[6]|sha1_md5"
                ),
                "re_password" => array(
                    "value" => $this->loadSecurity(sha1(md5($_POST['repassword'])))->clear(),
                    "errorName" => "Re-Password",
                    "rules" => "required|match[password]"
                )
            );
            // load validation classs and pass validation data
            $dataValid = $this->loadValidation($validationArray)->formValidate();
            // check if the data is ok
            if (is_array($dataValid) && array_key_exists("success", $dataValid)) {
                // check old password
                $oldPass = $this->loadModel("UserModel")->retrieveAllData("WHERE `id`=? AND `password`=? AND `status`=? AND `deleted`=?", array($id, sha1(md5($dataValid['success']['old_password'])), 1, 1));
                if (is_array($oldPass)) {
                    // unset old password from success array
                    unset($dataValid['success']['old_password']);
                    unset($dataValid['success']['re_password']);
                    if (false !== $this->loadModel("UserModel", $dataValid['success'])->updateData("id", $id)) {
                        $response['status'] = "success";
                        $response['message'] = '<div class="alert alert-success" role="alert"><staong><i class="fa fa-check" aria-hidden="true"></i> Success </strong> Your Data Updated Successfully. </div>';
                        echo $this->loadAjax()->DataToJson($response);
                        exit;
                    } else {
                        $response['status'] = "faild";
                        $response['message'] = '<div class="alert alert-danger" role="alert"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> Error Updating Your Data</div>';
                        echo $this->loadAjax()->DataToJson($response);
                        exit;
                    }
                } else {
                    $response['status'] = "faild";
                    $response['message'] = '<div class="alert alert-danger" role="alert"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> Wrong Old Password</div>';
                    echo $this->loadAjax()->DataToJson($response);
                    exit;
                }
            } else {
                $response['status'] = "faild";
                $response['message'] = '<div class="alert alert-danger" role="alert"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong>' . $dataValid . '</div>';
                echo $this->loadAjax()->DataToJson($response);
                exit;
            }
        }
    }
}

?>