<?php

class Gallery 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'])) {
            // upload image
            $upload = $this->loadUpload("image")->do_upload();

            $counter = 0;
            foreach ($upload['uploaded'] as $value) {
                //preparing data to be sent to model
                $galleryDataModel['created_by'] = $user_id;
                $galleryDataModel['last_update_by'] = $user_id;
                $galleryDataModel['createdAt'] = date('Y-m-d h:i:s');
                $galleryDataModel['image'] = $value;
                // load Model To Add Images Name
                if ($this->loadModel("GalleryModel", $galleryDataModel)->add()) {
                    $counter++;
                }
            }
            if ($counter == 0) {
                $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong> Error ! </strong> Can Not Add Your Data Please Select Some Images(Max Size : 5MB & Allowed Extensions : png - jpg - jpeg)</div>';
            } else if ($counter < count($upload['uploaded'])) {
                $dataView['message'] = '<div class="alert alert-warning" role="alert"><strong> Warning ! </strong> Some Images Not Be Uploaded (Max Size : 5MB & Allowed Extensions : png - jpg - jpeg) </div>';
            } else {
                $dataView['message'] = '<div class="alert alert-success" role="alert"><strong>Success </strong> Your Data Added Successfully Please Wait ...</div>';
                header("Refresh: 2");
            }

        }

        $dataView['title'] = "Add a New gallery";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "gallery" . DIRECTORY_SEPARATOR . "gallery_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['gallerys'] = $this->loadModel("GalleryModel")->retrieveAllData("WHERE `deleted` =?", array(1));


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

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

            // preparing validation array
            $validationArray = array(

                "url" => array(
                    "value" => $this->loadSecurity($_POST['url'])->clear(),
                    "errorName" => "Url",
                    "rules" => "required|url"
                ),


                "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['link'] = $dataValid['success']['url'];
                $dataModel['created'] = time();
                $dataModel['status'] = $dataValid['success']['status'];
                // update data
                $update = $this->loadModel("GalleryModel", $dataModel)->updateData("id", $id);
                if (FALSE !== $update) {

                    $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 gallery";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "gallery_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("GalleryModel", $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("GalleryModel", $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("GalleryModel", array("deleted" => 2))->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }

}

?>