<?php

class Branches 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" => "Branch Title",
                    "rules" => "required|min-length[3]"
                ),
                "address" => array(
                    "value" => $this->loadSecurity($_POST['address'])->clear(),
                    "errorName" => "Branch Address",
                    "rules" => "required|min-length[3]"
                ),
                "phone" => array(
                    "value" => $this->loadSecurity($_POST['phone'])->clear(),
                    "errorName" => "Branch Phone",
                    "rules" => "required|min-length[3]"
                ),
                "email" => array(
                    "value" => $this->loadSecurity($_POST['email'])->clear(),
                    "errorName" => "Branch email"
                ),
                "ar_title" => array(
                    "value" => $this->loadSecurity($_POST['ar_title'])->clear(),
                    "errorName" => "الفرع",
                    "rules" => "required|min-length[3]"
                ),
                "ar_address" => array(
                    "value" => $this->loadSecurity($_POST['ar_address'])->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)) {

                $dataModel['phone'] = $dataValid['success']['phone'];
                $dataModel['email'] = $dataValid['success']['email'];
                $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
                $add = $this->loadModel("BranchesModel", $dataModel)->add();
                if (FALSE !== $add) {
                    // preparing en data model
                    $enDataModel['id_branch'] = $add;
                    $enDataModel['title'] = $dataValid['success']['title'];
                    $enDataModel['address'] = $dataValid['success']['address'];
                    $addEnData = $this->loadModel("BranchesEnModel", $enDataModel)->add();
                    // preparing ar data model
                    $arDataModel['id_branch'] = $add;
                    $arDataModel['title'] = $dataValid['success']['ar_title'];
                    $arDataModel['address'] = $dataValid['success']['ar_address'];
                    $addArData = $this->loadModel("BranchesArModel", $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> 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> 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 Branch";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "branch" . DIRECTORY_SEPARATOR . "branch_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("BranchesModel")->retrieveAllData("WHERE `deleted` =?", array(1));
        // get lang data
        if (is_array($dataView['branches'])) {
            foreach ($dataView['branches'] as $key => $value) {
                $dataView['branchesEn'][$key] = $this->loadModel("BranchesEnModel")->retriveDataById("id_branch", $value['id']);
                $dataView['branchesAr'][$key] = $this->loadModel("BranchesArModel")->retriveDataById("id_branch", $value['id']);
            }
        }

        $dataView['title'] = "Show / Edit Branches";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "branch" . DIRECTORY_SEPARATOR . "branch_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['branches'] = $this->loadModel("BranchesModel")->retrieveAllData("WHERE `id` =? AND `deleted` =?", array($id, 1));
        if ($dataView['branches'] == NULL) {
            $this->redirect("error", "index");
            exit();
        }
        $dataView['branches'] = array_shift($dataView['branches']);
        // get lang data
        $dataView['branchesEn'] = $this->loadModel("BranchesEnModel")->retriveDataById("id_branch", $dataView['branches']['id']);
        $dataView['branchesAr'] = $this->loadModel("BranchesArModel")->retriveDataById("id_branch", $dataView['branches']['id']);
        $dataView['branchesPhones'] = $this->loadModel("BranchesPhoneModel")->retrieveAllData("WHERE `id_branch` =? AND `deleted` =?", array($id, 1));

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

            // preparing validation array
            $validationArray = array(
                "title" => array(
                    "value" => $this->loadSecurity($_POST['title'])->clear(),
                    "errorName" => "Branch Title",
                    "rules" => "required|min-length[3]"
                ),
                "address" => array(
                    "value" => $this->loadSecurity($_POST['address'])->clear(),
                    "errorName" => "Branch Address",
                    "rules" => "required|min-length[3]"
                ),
                "phone" => array(
                    "value" => $this->loadSecurity($_POST['phone'])->clear(),
                    "errorName" => "Branch Phone",
                    "rules" => "required|min-length[3]"
                ),
                "email" => array(
                    "value" => $this->loadSecurity($_POST['email'])->clear(),
                    "errorName" => "Branch email",
                ),
                "ar_title" => array(
                    "value" => $this->loadSecurity($_POST['ar_title'])->clear(),
                    "errorName" => "الفرع",
                    "rules" => "required|min-length[3]"
                ),
                "ar_address" => array(
                    "value" => $this->loadSecurity($_POST['ar_address'])->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 model
                $dataModel['phone'] = $dataValid['success']['phone'];
                $dataModel['email'] = $dataValid['success']['email'];
                $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("BranchesModel", $dataModel)->updateData("id", $id);
                if (FALSE !== $edit) {
                    // preparing en data model
                    $enDataModel['title'] = $dataValid['success']['title'];
                    $enDataModel['address'] = $dataValid['success']['address'];
                    $editEnData = $this->loadModel("BranchesEnModel", $enDataModel)->updateData("id_branch", $id);
                    // preparing ar data model
                    $arDataModel['title'] = $dataValid['success']['ar_title'];
                    $arDataModel['address'] = $dataValid['success']['ar_address'];
                    $editArData = $this->loadModel("BranchesArModel", $arDataModel)->updateData("id_branch", $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 Branch";
        // global Template Config
        global $TEMPLATE_BACK_END;
        // set content
        $TEMPLATE_BACK_END['files']['content'] = BACK_END_CONTROL_PATH . "branch" . DIRECTORY_SEPARATOR . "branch_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("BranchesModel", $dataModel)->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }

    public function edit_phones()
    {
        /******** 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['branch'] = $this->loadModel("BranchesModel")->retrieveAllData("WHERE `id` =? AND `deleted` =?", array($id, 1));
        if (!is_array($dataView['branch'])) {
            $this->redirect("error", "index");
            exit();
        }
        $dataView['branch'] = array_shift($dataView['branch']);
        // get branches phones
        $dataView['branchPhones'] = $this->loadModel("BranchesPhoneModel")->retrieveAllData("WHERE `id_branch` =? AND `status` =? AND `deleted` = ?", array($id, 1, 1));

        //start Add Anew Data
        if (isset($_POST['add'])) {
            // add phone if exists
            $phones = count($_POST["phones"]);
            if ($phones > 0) {
                for ($i = 0; $i < $phones; $i++) {
                    if (trim($_POST["phones"][$i] != '')) {
                        $otherPhones['id_branch'] = $id;
                        $otherPhones['phone'] = $_POST["phones"][$i];
                        $otherPhones['created_by'] = $user_id;
                        $otherPhones['last_update_by'] = $user_id;
                        $otherPhones['createdAt'] = date('Y-m-d h:i:s');
                        // load Model To Add
                        $addPhones = $this->loadModel("BranchesPhoneModel", $otherPhones)->add();
                    }

                }
            }
            if (FALSE !== $addPhones) {
                $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>';
            }

        }

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

    public function delete_branch_phones()
    {
        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("BranchesPhoneModel", array("deleted" => 2))->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) {
                $this->redirect("error", "index");
                exit;
            } else {
                if (FALSE !== $this->loadModel("BranchesModel", array("deleted" => 2))->updateData("id", $id)) {
                    echo $this->loadAjax()->DataToJson(array("status" => "success"));
                    exit;
                } else {
                    echo $this->loadAjax()->DataToJson(array("status" => "faild"));
                    exit;
                }
            }
        }
    }
}

?>
