<?php
/**
 * Created by PhpStorm.
 * User: Tarek Mahfouz 01114254513
 * Date: 2/15/2021
 * Time: 11:42 PM
 */

class Seo  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'])) {
             //var_dump($_POST); die();
            // preparing validation array
            $validationArray = array(
                "title" => array(
                    "value" => $this->loadSecurity($_POST['title'])->clear(),
                    "errorName" => "Page Title",
                    "rules" => "required|min-length[3]"
                ),
                "slug" => array(
                    "value" => $this->loadSecurity($_POST['slug'])->clear(),
                    "errorName" => "URL Slug",
                    "rules" => "required|min-length[3]"
                ),
            );
            // load validation class and pass validation data
            $dataValid = $this->loadValidation($validationArray)->formValidate();
            //var_dump($dataValid);die();
            // check if the data is ok
            if (is_array($dataValid) && array_key_exists("success", $dataValid)) {
                $dataModel['slug'] = $dataValid['success']['slug'];
                $dataModel['title'] = $dataValid['success']['title'];
                $dataModel['content'] = $_POST['content'];
                $dataModel['keywords'] = $_POST['keywords'];
                $dataModel['created_at'] = date('Y-m-d h:i:s');
                // add
                $add = $this->loadModel("SeoModel", $dataModel)->add();
                if (!$add) {
                    $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</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 SEO";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "seos" . DIRECTORY_SEPARATOR . "seo_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['branches'] = $this->loadModel("SeoModel")->retrieveAllData();
        // get lang data

        $dataView['title'] = "Show / Edit SEO";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "seos" . DIRECTORY_SEPARATOR . "seo_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['seo'] = $this->loadModel("SeoModel")->retrieveAllData("WHERE `id` =? ", array($id));
        if ($dataView['seo'] == NULL) {
            $this->redirect("seo", "getAll");
            exit();
        }
        $dataView['seo'] = array_shift($dataView['seo']);

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

            // preparing validation array
            $validationArray = array(
                "title" => array(
                    "value" => $this->loadSecurity($_POST['title'])->clear(),
                    "errorName" => "Page Title",
                    "rules" => "required|min-length[3]"
                ),
                "slug" => array(
                    "value" => $this->loadSecurity($_POST['slug'])->clear(),
                    "errorName" => "URL Slug",
                    "rules" => "required|min-length[3]"
                ),
            );
            // load validation classs and pass validation data
            $dataValid = $this->loadValidation($validationArray)->formValidate();
            // check if the data is ok
            //var_dump($dataValid);die();
            if (is_array($dataValid) && array_key_exists("success", $dataValid)) {
                // prepare data model
                $dataModel['slug'] = $dataValid['success']['slug'];
                $dataModel['title'] = $dataValid['success']['title'];
                $dataModel['content'] = $_POST['content'];
                $dataModel['keywords'] = $_POST['keywords'];
                // edit news

                $edit = $this->loadModel("SeoModel", $dataModel)->updateData("id", $id);
                if (FALSE === $edit) {
                    $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 {
                    header("Refresh: 1");
                }
            } 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 SEO";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "seos" . DIRECTORY_SEPARATOR . "seo_edit";
        // 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("BranchesModel", $dataModel)->updateData("id", $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) {
                echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                exit;
                /*$this->redirect("error", "index");
                exit;*/
            } else {
                if (FALSE !== $this->loadModel("SeoModel")->deleteById("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }
}