<?php

class Image_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'])) {

            // preparing validation array
            $validationArray = array(
                "name" => array(
                    "value" => $this->loadSecurity($_POST['enName'])->clear(),
                    "errorName" => "Album Name",
                    "rules" => "required|min-length[3]"
                ),
                "ar_name" => array(
                    "value" => $this->loadSecurity($_POST['arName'])->clear(),
                    "errorName" => "اسم الالبوم",
                    "rules" => "required|min-length[3]"
                ),

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

                //if there is no errors
                if (!array_key_exists('uploadError', $upload)) {
                    // prepare data
                    $dataModel['created_by'] = $user_id;
                    $dataModel['last_update_by'] = $user_id;
                    $dataModel['status'] = $dataValid['success']['status'];
                    $dataModel['image'] = $upload['uploaded'][0];
                    $dataModel['createdAt'] = date('Y-m-d h:i:s');

                    $add = $this->loadModel("ImageGalleryModel", $dataModel)->add();
                    if (FALSE !== $add) {
                        // preparing en data
                        $dataEnModel['id_image_gallery'] = $add;
                        $dataEnModel['name'] = $dataValid['success']['name'];
                        $dataEnModel['last_update_by'] = $user_id;
                        $dataEnModel['created_by'] = $user_id;
                        $dataEnModel['createdAt'] = date('Y-m-d h:i:s');
                        $addEnData = $this->loadModel("ImageGalleryEnModel", $dataEnModel)->add();
                        // preparing ar data
                        $dataArModel['id_image_gallery'] = $add;
                        $dataArModel['name'] = $dataValid['success']['ar_name'];
                        $dataArModel['last_update_by'] = $user_id;
                        $dataArModel['created_by'] = $user_id;
                        $dataArModel['createdAt'] = date('Y-m-d h:i:s');
                        $addArData = $this->loadModel("ImageGalleryArModel", $dataArModel)->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> Error Adding Your Data Please Try Again</div>';
                        }
                    } else {
                        $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> Error Adding Your Data Please Try Again1</div>';
                    }

                } else {
                    $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> Main 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 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 Gallries

        $dataView['gallries'] = $this->loadModel("ImageGalleryModel")->retrieveAllData("WHERE `deleted` =?", array(1));
        if (is_array($dataView['gallries'])) {
            foreach ($dataView['gallries'] as $key => $value) {
                // get ar and en Data
                $dataView['gallriesEn'][$key] = $this->loadModel("ImageGalleryEnModel")->retriveDataById("id_image_gallery", $value['id']);
                $dataView['gallriesAr'][$key] = $this->loadModel("ImageGalleryArModel")->retriveDataById("id_image_gallery", $value['id']);
            }
        }

        $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("ImageGalleryModel")->retrieveAllData("WHERE `id` =? AND `deleted` =?", array($id, 1));
        if ($dataView['gallery'] == NULL) {
            $this->redirect("error", "index");
            exit();
        }
        $dataView['gallery'] = array_shift($dataView['gallery']);
        // get ar and en Data
        $dataView['galleryEn'] = $this->loadModel("ImageGalleryEnModel")->retriveDataById("id_image_gallery", $id);
        $dataView['galleryAr'] = $this->loadModel("ImageGalleryArModel")->retriveDataById("id_image_gallery", $id);

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

            // preparing validation array
            $validationArray = array(
                "name" => array(
                    "value" => $this->loadSecurity($_POST['enName'])->clear(),
                    "errorName" => "Gallery Name",
                    "rules" => "required|min-length[3]"
                ),
                "ar_name" => array(
                    "value" => $this->loadSecurity($_POST['arName'])->clear(),
                    "errorName" => "اسم الالبوم",
                    "rules" => "required|min-length[3]"
                ),
                "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
                $dataModel['last_update_by'] = $user_id;
                $dataModel['status'] = $dataValid['success']['status'];

                $update = $this->loadModel("ImageGalleryModel", $dataModel)->updateData("id", $id);
                if (FALSE !== $update) {
                    // preparing en data
                    $dataEnModel['name'] = $dataValid['success']['name'];
                    $updateEnData = $this->loadModel("ImageGalleryEnModel", $dataEnModel)->updateData("id_image_gallery", $id);
                    // preparing ar data
                    $dataArModel['name'] = $dataValid['success']['ar_name'];
                    $updateArData = $this->loadModel("ImageGalleryArModel", $dataArModel)->updateData("id_image_gallery", $id);
                    if (False !== $updateEnData && FALSE !== $updateArData) {
                        $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 Please Try Again</div>';
                    }
                } else {
                    $dataView['message'] = '<div class="alert alert-danger" role="alert"><strong><i class="fa fa-times" aria-hidden="true"></i> Error ! </strong> Error Adding Your Data Please Try Again</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'] = "Edit Selected Gallery";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "gallery" . DIRECTORY_SEPARATOR . "gallery_edit_selected";
        // load template
        $this->loadTemplate($TEMPLATE_BACK_END, $dataView)->render();
    }

    public function edit_images()
    {
        /******** 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("ImageGalleryModel")->retrieveAllData("WHERE `id` =? AND `deleted` =?", array($id, 1));
        if (!is_array($dataView['gallery'])) {
            $this->redirect("error", "index");
            exit();
        }
        $dataView['gallery'] = array_shift($dataView['gallery']);
        // get offer images
        $dataView['galleryImages'] = $this->loadModel("ImageGalleryImagesModel")->retrieveAllData("WHERE `id_image_gallery` =? AND `status` =? AND `deleted` = ?", array($id, 1, 1));


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

    public function gallery_add_more_images()
    {
        $id = (int)$_POST['id'];
        if ($id == 0) {
            echo $this->loadAjax()->DataToJson(array("status" => "faild"));
            exit;
        }
        $user_id = $this->loadSession()->getSession("user_id");
        // upload images
        $upload = $this->loadUpload("images")->do_upload();
        $counter = 0;
        foreach ($upload['uploaded'] as $value) {

            //preparing data to be sent to model
            $albumImagesData['id_image_gallery'] = $id;
            $albumImages['created_by'] = $user_id;
            $albumImages['last_update_by'] = $user_id;
            $albumImages['createdAt'] = date('Y-m-d h:i:s');
            $albumImagesData['image'] = $value;
            // load Model To Add Images Name
            if ($this->loadModel("ImageGalleryImagesModel", $albumImagesData)->add()) {
                $counter++;
            }
        }
        if ($counter == 0) {
            echo $this->loadAjax()->DataToJson(array("status" => "faild"));
            exit;
        } else if ($counter < count($upload['uploaded'])) {
            echo $this->loadAjax()->DataToJson(array("status" => "Somefaild"));
            exit;
        } else {
            echo $this->loadAjax()->DataToJson(array("status" => "success"));
            exit;
        }
    }

    public function delete_gallery_images()
    {
        if (isset($_POST['action'], $_POST['imageId']) && $_POST['action'] == "deleteImage") {

            // get image id
            $image_id = (int)$_POST['imageId'];

            if ($image_id == 0) {
                echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                exit;
            } else {

                if (false !== $this->loadModel("ImageGalleryImagesModel", array("deleted" => 2))->updateData("id", $image_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) {
            echo $this->loadAjax()->DataToJson(array("status" => "falid"));
            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];
                // get user id from session
                $user_id = $this->loadSession()->getSession("user_id");
                $dataModel['last_update_by'] = $user_id;
                if (false !== $this->loadModel("ImageGalleryModel", $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 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;
                // get user id from session
                $user_id = $this->loadSession()->getSession("user_id");
                $dataModel['last_update_by'] = $user_id;
                if (false !== $this->loadModel("ImageGalleryModel", $dataModel)->updateData("id", $id)) {
                    $this->loadModel("ImageGalleryArModel", $dataModel)->updateData("id_image_gallery", $id);
                    $this->loadModel("ImageGalleryEnModel", $dataModel)->updateData("id_image_gallery", $id);
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    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 {
                // get user id from session
                $user_id = $this->loadSession()->getSession("user_id");
                $dataModel['last_update_by'] = $user_id;
                $dataModel['deleted'] = 2;
                if (FALSE !== $this->loadModel("ImageGalleryModel", $dataModel)->updateData("id", $id)) {
                    $this->loadModel("ImageGalleryArModel", $dataModel)->updateData("id_image_gallery", $id);
                    $this->loadModel("ImageGalleryEnModel", $dataModel)->updateData("id_image_gallery", $id);
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }


}

?>