<?php

class Service 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" => "Service Title",
                    "rules" => "required|min-length[3]"
                ),
                "slug" => array(
                    "value" => $this->loadSecurity($_POST['slug'])->clear(),
                    "errorName" => "Slug Service",
                    "rules" => "required"
                ),
                "description" => array(
                    "value" => $this->loadSecurity($_POST['description'])->clear(),
                    "errorName" => "description Service",
                    "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)) {

                // 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['title'] = $dataValid['success']['title'];
                    $dataModel['slug'] = $dataValid['success']['slug'];
                    $dataModel['description'] = $dataValid['success']['description'];
                    $dataModel['status'] = $dataValid['success']['status'];
                    $dataModel['createdAt'] = date('Y-m-d h:i:s');
                    // add news
                    $add = $this->loadModel("ServiceModel", $dataModel)->add();
                    if (FALSE !== $add) {

                        $dataView['message'] = '<div class="alert alert-success" role="alert"><staong><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"><staong><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"><staong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong>' . $upload['uploadError'] . '</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>';
            }
        }

        $dataView['title'] = "Add Service";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "service" . DIRECTORY_SEPARATOR . "service_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['services'] = $this->loadModel("ServiceModel")->retrieveAllData("WHERE `deleted` =?", array(1));

        $dataView['title'] = "Show / Edit Services";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "service" . DIRECTORY_SEPARATOR . "service_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['services'] = $this->loadModel("ServiceModel")->retrieveAllData("WHERE `id` =? AND `deleted` =?", array($id, 1));
        if ($dataView['services'] == NULL) {
            $this->redirect("error", "index");
            exit();
        }
        $dataView['services'] = array_shift($dataView['services']);

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

            // preparing validation array
            $validationArray = array(
                "title" => array(
                    "value" => $this->loadSecurity($_POST['title'])->clear(),
                    "errorName" => "Service Title",
                    "rules" => "required"
                ),

                "slug" => array(
                    "value" => $this->loadSecurity($_POST['slug'])->clear(),
                    "errorName" => "Slug Service",
                    "rules" => "required"
                ),
                "description" => array(
                    "value" => $this->loadSecurity($_POST['description'])->clear(),
                    "errorName" => "Description Service",
                    "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['title'] = $dataValid['success']['title'];
                $dataModel['slug'] = $dataValid['success']['slug'];
                $dataModel['description'] = $dataValid['success']['description'];
                $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 news
                $edit = $this->loadModel("ServiceModel", $dataModel)->updateData("id", $id);
                if (FALSE !== $edit) {

                    $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>' . $dataValid . '</div>';
            }
        }

        // set page title
        $dataView['title'] = "Edit Selected Service";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "service" . DIRECTORY_SEPARATOR . "service_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("ServiceModel", $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("ServiceModel", $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("ServiceModel", array("deleted" => 2))->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }

}

?>
