<?php

class Features extends Controller
{


    public function add()
    {
        /******** 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 *******/

        //start Add Anew Data
        if (isset($_POST['add'])) {

            // preparing validation array
            $validationArray = array(
                "title" => array(
                    "value" => $this->loadSecurity($_POST['title'])->clear(),
                    "errorName" => "features Title",
                    "rules" => "required|min-length[3]"
                ),
                "title_ar" => array(
                    "value" => $this->loadSecurity($_POST['title_ar'])->clear(),
                    "errorName" => "عنوان الميزة",
                    "rules" => "required|min-length[3]"
                ),
                "status" => array(
                    "value" => $this->loadSecurity($_POST['status'])->clear(),
                    "errorName" => "Status",
                    "rules" => "number"
                ),
            );
            // load validation class and pass validation data
            $dataValid = $this->loadValidation($validationArray)->formValidate();
            // check if the data is ok
            if (is_array($dataValid) && array_key_exists("success", $dataValid)) {

                // start upload features image
                // upload image
                $upload = $this->loadUpload("image")->do_upload();
                //if there is no errors
                if (!array_key_exists('uploadError', $upload)) {
                    // prepare data model
                    $dataModel['image'] = $upload['uploaded'][0];
                    $dataModel['created_by'] = $user_id;
                    $dataModel['last_update_by'] = $user_id;
                    $dataModel['status'] = $dataValid['success']['status'];
                    $dataModel['createdAt'] = date('Y-m-d h:i:s');
                    // add features
                    $add = $this->loadModel("FeaturesModel", $dataModel)->add();
                    if (FALSE !== $add) {
                        // preparing en data model
                        $enDataModel['id_features'] = $add;
                        $enDataModel['title'] = $dataValid['success']['title'];
                        $addEnData = $this->loadModel("FeaturesEnModel", $enDataModel)->add();
                        // preparing ar data model
                        $arDataModel['id_features'] = $add;
                        $arDataModel['title'] = $dataValid['success']['title_ar'];
                        $addArData = $this->loadModel("FeaturesArModel", $arDataModel)->add();

                        if (FALSE !== $addEnData && FALSE !== $addArData) {
                            $dataView['message'] = '<div class="alert alert-success" role="alert"><strong><i class="fa fa-check" aria-hidden="true"></i> Success </strong> Your Data Added Successfully Please Wait .. </div>';
                            header("Refresh: 2");
                        } else {
                            $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> EError Adding Your Data</div>';
                        }
                    } else {
                        $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong><i class="fa fa-times" aria-hidden="true"></i> Errorr ! </strong> Error Adding Your Data</div>';
                    }
                } else {
                    $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> Features Image Is Required (Max Image Size 2MB)</div>';
                }
            } else {
                $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong>' . $dataValid . '</div>';
            }
        }

        $dataView['title'] = "Add a features";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "features" . DIRECTORY_SEPARATOR . "features_add";
        // load template
        $this->loadTemplate($TEMPLATE_BACK_END, $dataView)->render();
    }

    public function getAll()
    {
        /******** 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 *******/

        // get all Data
        $dataView['features'] = $this->loadModel("FeaturesModel")->retrieveAllData("WHERE `deleted` =?", array(1));
        // get lang data
        if (is_array($dataView['features'])) {
            foreach ($dataView['features'] as $key => $value) {
                $dataView['featuresEn'][$key] = $this->loadModel("FeaturesEnModel")->retriveDataById("id_features", $value['id']);
                $dataView['featuresAr'][$key] = $this->loadModel("FeaturesArModel")->retriveDataById("id_features", $value['id']);
            }
        }

        $dataView['title'] = "Show / Edit features";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "features" . DIRECTORY_SEPARATOR . "features_getall";
        // load template
        $this->loadTemplate($TEMPLATE_BACK_END, $dataView)->render();
    }

    public function edit_selected()
    {
        /******** 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 *******/
        // get id from url
        $id = (int)$this->loadRoute()->getSegment(2);
        if ($id == 0) {
            $this->redirect("error", "index");
            exit();
        }
        // get data
        $dataView['features'] = $this->loadModel("FeaturesModel")->retrieveAllData("WHERE `id` =? AND `deleted` =?", array($id, 1));
        if ($dataView['features'] == NULL) {
            $this->redirect("error", "index");
            exit();
        }
        $dataView['features'] = array_shift($dataView['features']);
        // get lang data
        $dataView['featuresEn'] = $this->loadModel("FeaturesEnModel")->retriveDataById("id_features", $dataView['features']['id']);
        $dataView['featuresAr'] = $this->loadModel("FeaturesArModel")->retriveDataById("id_features", $dataView['features']['id']);

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

            // preparing validation array
            $validationArray = array(
                "title" => array(
                    "value" => $this->loadSecurity($_POST['title'])->clear(),
                    "errorName" => "features Title",
                    "rules" => "required"
                ),
                "title_ar" => array(
                    "value" => $this->loadSecurity($_POST['title_ar'])->clear(),
                    "errorName" => "عنوان الميزة",
                    "rules" => "required"
                ),
                "status" => array(
                    "value" => $this->loadSecurity($_POST['status'])->clear(),
                    "errorName" => "Status",
                    "rules" => "number"
                ),
            );
            // 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)) {
                // prepare data model
                $dataModel['created_by'] = $user_id;
                $dataModel['last_update_by'] = $user_id;
                $dataModel['status'] = $dataValid['success']['status'];
                $dataModel['createdAt'] = date('Y-m-d h:i:s');
                // edit features
                $edit = $this->loadModel("FeaturesModel", $dataModel)->updateData("id", $id);
                if (FALSE !== $edit) {
                    // preparing en data model
                    $enDataModel['title'] = $dataValid['success']['title'];
                    $editEnData = $this->loadModel("FeaturesEnModel", $enDataModel)->updateData("id_features", $id);
                    // preparing ar data model
                    $arDataModel['title'] = $dataValid['success']['title_ar'];
                    $editArData = $this->loadModel("FeaturesArModel", $arDataModel)->updateData("id_features", $id);
                    if (FALSE !== $editEnData && FALSE !== $editArData) {
                        $dataView['message'] = '<div class="alert alert-success" role="alert"><strong><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"><strong><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"><strong><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"><strong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong>' . $dataValid . '</div>';
            }
        }

        // set page title
        $dataView['title'] = "Edit Selected features";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "features" . DIRECTORY_SEPARATOR . "features_edit_selected";
        // load template
        $this->loadTemplate($TEMPLATE_BACK_END, $dataView)->render();
    }

    public function updateStatus()
    {
        if (isset($_POST['action'], $_POST['id'], $_POST['status']) && $_POST['action'] == "updateStatus") {
            // get User id
            $id = (int)$_POST['id'];
            if ($id == 0) {
                $this->redirect("error", "index");
                exit;
            } else {
                // get current status
                $currentStatus = $_POST['status'];
                // if current status = on set it off
                if ($currentStatus == "on") {
                    $setStatus = 2;
                } else {
                    $setStatus = 1;
                }
                $dataModel['status'] = $setStatus;

                if (false !== $this->loadModel("FeaturesModel", $dataModel)->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }

    public function update_image()
    {
        //get id
        $id = (int)$_POST['field_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['image'] = $upload['uploaded'][0];
                if (false !== $this->loadModel("FeaturesModel", $dataModel)->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success", "newImage" => $dataModel['image']));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "falid"));
                    exit;
                }
            }
        }
    }

    public function delete()
    {
        if (isset($_POST['action'], $_POST['id']) && $_POST['action'] == "deleteData") {
            $id = (int)$_POST['id'];
            if ($id == 0) {
                $this->redirect("error", "index");
                exit;
            } else {
                if (FALSE !== $this->loadModel("FeaturesModel", array("deleted" => 2))->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }

}

?>
