<?php
require_once '_master/apiHandler.php';

class pageClass extends apiHandler
{
 
    private $apiName;
    private $pageTable;
    private $pageTableId;
    private $pageJoin;
    private $selectWhere;
    private $selectColumns;
    private $searchColumns;
    private $tarnsSelect;
    private $checkFoundBefore;
    private $renameFields;
    private $blockedFields;
    private $pathUrl;
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
        if($this->clientSource !== 'web'){
           $this->selectWhere = ' and branch.status = 0 ';
        }else{
            $this->selectWhere = '';
        }
        $this->pathUrl = $this->hosturl.'/views/default/images/branch_image/';
        $this->apiName = 'branches';
        $this->pageTable = 'branch';
        $this->pageTableId = 'branch.branchId';
        $this->pageJoin = ' ';
        $this->selectColumns = "branchId as id, logo as image, CONCAT('$this->pathUrl', logo) as path_image, phone, mobile, branchNo as branch_no, email, branchDate as branch_date, latitude, longitude";
        $this->searchColumns = '(branch.branchName LIKE ? or branch.nameEn LIKE ?)';
        $this->tarnsSelect = ['ar'=>' , branchName as name, branchAddress as address, description_ar as description ','en'=>', nameEn as name, addressEn as address, description_en as description'
        ,'lang_all'=>' , branchName as name_ar, branchAddress as address_ar , nameEn as name_en, addressEn as address_en, description_ar, description_en'];
        $this->checkFoundBefore = '(branch.branchName LIKE ? or branch.nameEn LIKE ?)';
        $this->renameFields = ['branchId' => 'id','branchName' => 'name_ar','nameEn' => 'name_en','branchAddress' => 'address_ar','addressEn' => 'address_en','branchNo' => 'branch_no','branchDate' => 'branch_date','logo' => 'image'];
        $this->allowedFields = ['phone','mobile','email','path_image','description_ar','description_en','latitude', 'longitude'];
        $this->blockedFields = [];
        
        
    }
    
    function index() {
        try {
            /* ===============================
             *  Request defaults
             * =============================== */
            $this->getrequest->page  = (!empty($this->getrequest->page)) ? (int)$this->getrequest->page : 1;
            $this->getrequest->limit = (!empty($this->getrequest->limit)) ? (int)$this->getrequest->limit : 1000;
            $this->getrequest->id    = isset($this->getrequest->id) ? (int)$this->getrequest->id : 0;
            $this->getrequest->searchName = isset($this->getrequest->searchName) ? trim($this->getrequest->searchName): '';
            $this->getrequest->latitude = isset($this->getrequest->latitude) ? trim($this->getrequest->latitude) : '';
            $this->getrequest->longitude = isset($this->getrequest->longitude) ? trim($this->getrequest->longitude) : '';
            $this->getrequest->distance = isset($this->getrequest->distance) ? (float)$this->getrequest->distance : 50;
    
            /* ===============================
             *  Validation config
             * =============================== */
            $allowed = ['searchName','page','limit','id','latitude','longitude','distance'];
    
            $fields = [
                'searchName' => [
                    'rules' => 'text|min:1|max:100',
                    'type'  => 'string',
                ],
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:10000',
                    'type'  => 'integer',
                ],
                'latitude' => [
                    'rules' => 'numeric',
                    'type'  => 'float',
                ],
                'longitude' => [
                    'rules' => 'numeric',
                    'type'  => 'float',
                ],
                'distance' => [
                    'rules' => 'numeric|min:1|max:500',
                    'type'  => 'float',
                ],
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
            ];
    
            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) $this->respond(401,false,$this->trans['httpStatusCodes']['401'], null,$request['validation_errors']);
         
            $this->selectColumns = $this->selectColumns . $this->tarnsSelect[$this->lang];
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT $this->selectColumns FROM $this->pageTable $this->pageJoin WHERE $this->pageTableId = ?",[$request['id']]);
                $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
            }
    
            
            $searchQuery = "";
    
            if ($request['searchName']) {
                $ids = R::getCol("SELECT $this->pageTableId FROM $this->pageTable WHERE $this->searchColumns",['%' . $request['searchName'] . '%', '%' . $request['searchName'] . '%']);
                $idList = implode(",", $ids);
                $searchQuery .= " AND $this->pageTableId IN (0$idList)";
            }
    
            $lat    = !empty($request['latitude'])  ? (float)$request['latitude']  : null;
            $lng    = !empty($request['longitude']) ? (float)$request['longitude'] : null;
            $radius = !empty($request['distance'])  ? (float)$request['distance']  : 50;
    
            $distanceSelect = '';
            $distanceHaving = '';
            $params = [];
    
            if ($lat && $lng) {
                $distanceSelect = ",
                    (6371 * acos(
                        cos(radians(?))
                        * cos(radians($this->pageTable.latitude))
                        * cos(radians($this->pageTable.longitude) - radians(?))
                        + sin(radians(?))
                        * sin(radians($this->pageTable.latitude))
                    )) AS distance
                ";
                $distanceHaving = " HAVING distance <= ? ";
                $params[] = $lat;
                $params[] = $lng;
                $params[] = $lat;
                $params[] = $radius;
            }
            
            $offset = ($request['page'] > 0 ? $request['page'] - 1 : 0) * $request['limit'];
    
            /* ===============================
             *  Main query
             * =============================== */
            $sql = "SELECT $this->selectColumns $distanceSelect FROM $this->pageTable $this->pageJoin WHERE 1 $searchQuery $this->selectWhere $distanceHaving LIMIT ? OFFSET ?";
            $params[] = $request['limit'];
            $params[] = $offset;
            $results = R::getAll($sql, $params);
    
            /* ===============================
             *  Total records
             * =============================== */
            if ($lat && $lng) {
                $totalRecords = R::getCell("
                    SELECT COUNT(*) FROM (
                        SELECT
                        (6371 * acos(
                            cos(radians(?))
                            * cos(radians(latitude))
                            * cos(radians(longitude) - radians(?))
                            + sin(radians(?))
                            * sin(radians(latitude))
                        )) AS distance
                        FROM $this->pageTable
                        WHERE 1 $searchQuery $this->selectWhere
                    ) t
                    WHERE distance <= ?
                ", [$lat, $lng, $lat, $radius]);
            } else {
                $totalRecords = R::getCell(
                    "SELECT COUNT(*) FROM $this->pageTable WHERE 1 $searchQuery $this->selectWhere"
                );
            }
    
            /* ===============================
             *  Response
             * =============================== */
            $response = [
                $this->apiName => $results,
                "pagination" => [
                    "current_page" => (int)$request['page'],
                    "total_pages"  => ceil($totalRecords / $request['limit']),
                    "total_items" => (int)$totalRecords,
                    "per_page"    => $request['limit'],
                ]
            ];
    
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
    
        } catch (Exception $exception) {
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }



    /**
     * Add a new branch
     */
    function add() {

        try {
            $allowed = ['name_ar', 'name_en', 'address', 'address_en','description_ar','description_en', 'branch_date', 
                       'phone', 'mobile', 'email', 'branch_no', 'comment', 'logo', 'branch_tax_no', 'status','latitude', 'longitude'];
            
            $fields = [
                'name_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'address' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'address_en' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'description_ar' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'description_en' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'branch_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'phone' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'mobile' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'email' => [
                    'rules' => 'required|text|max:100',//email
                    'type'  => 'string',
                ],
                'branch_no' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'comment' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'logo' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'branch_tax_no' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 1
                ],
                'latitude' => [
                    'rules' => 'required|text|min:1|max:200',
                    'type'  => 'string',
                ],
                'longitude' => [
                    'rules' => 'required|text|min:1|max:200',
                    'type'  => 'string',
                ],
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }

            if (helpers::valueExistsInTable("$this->pageTable", "$this->checkFoundBefore", [$request['name_ar'], $request['name_en']])) {
              $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            
            
            $image_name = $request['logo'];
            if (strpos($image_name, 'dump') !== false) {
                //mine
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                if (file_exists('../../upload/dump/' . $url_array[$count_url_array - 1])) {
                    rename("../../upload/dump/" . $url_array[$count_url_array - 1], "../../views/default/images/branch_image/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'branch_image') !== false) {
                $image_name = $url_array[$count_url_array - 1];
            }

            $rdispense = R::dispense("$this->pageTable");
            $rdispense->branchName = $request['name_ar'];
            $rdispense->nameEn = $request['name_en'];
            $rdispense->branchAddress = $request['address'];
            $rdispense->addressEn = $request['address_en'];
            $rdispense->description_ar = $request['description_ar'];
            $rdispense->description_en = $request['description_en'];
            $rdispense->latitude = $request['latitude'];
            $rdispense->longitude = $request['longitude'];
            $rdispense->branchDate = $request['branch_date'];
            $rdispense->phone = $request['phone'];
            $rdispense->mobile = $request['mobile'];
            $rdispense->email = $request['email'];
            $rdispense->branchNo = $request['branch_no'];
            $rdispense->message = $request['comment'];
            $rdispense->logo = $image_name;
            $rdispense->branchTaxNo = $request['branch_tax_no'];
            $rdispense->status = (int) $request['status'];
            $rdispense->createdAt = date('Y-m-d H:i:s');
            $rdispense->updatedAt = date('Y-m-d H:i:s');
            $id = R::store($rdispense);
             
            $rdispense->path_image = $this->pathUrl . $image_name;
            $fresponse = helpers::beanToStdClass($rdispense,$this->allowedFields, $this->blockedFields,$this->renameFields);
            $this->respond(200, true, $this->trans['messages']['branches']['200'], null, [],$fresponse);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function edit() {
        try{

            $allowed = ['id'];
             $fields = [
                'id' => [
                    'rules' => 'required|integer',
                    'type'  => 'integer',
                ],
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) $this->respond(401,false,$this->trans['httpStatusCodes']['401'], null,$request['validation_errors']);
            
            if (helpers::valueNotExistsInTable("$this->pageTable", "$this->pageTableId = ? ",[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages'][$this->apiName][$this->apiName.'IdNotExists']]);
            }
            
            $this->selectColumns = $this->selectColumns . $this->tarnsSelect['lang_all'];
            $response = R::getRow("SELECT $this->selectColumns FROM $this->pageTable $this->pageJoin WHERE $this->pageTableId = ?",[$request['id']]);
            $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);

        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
        
    }

    /**
     * Update an existing branch
     */
    function update() {
        try {
            
            $allowed = ['id','name_ar', 'name_en', 'address', 'address_en', 'branch_date', 
                       'isdel', 'mobile', 'email', 'branch_no', 'comment', 'logo', 'branch_tax_no', 'status','latitude', 'longitude'];

            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'name_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'address' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'address_en' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'description_ar' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'description_en' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'branch_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'phone' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'mobile' => [
                    'rules' => 'required|text|max:50',
                    'type'  => 'string',
                ],
                'email' => [
                    'rules' => 'required|text|max:100',//email
                    'type'  => 'string',
                ],
                'branch_no' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'comment' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'logo' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'branch_tax_no' => [
                    'rules' => 'text|max:255',
                    'type'  => 'string',
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 1
                ],
                'latitude' => [
                    'rules' => 'required|text|min:1|max:200',
                    'type'  => 'string',
                ],
                'longitude' => [
                    'rules' => 'required|text|min:1|max:200',
                    'type'  => 'string',
                ],
            ];
            
            
        

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) {
                $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, $request['validation_errors']);
            }
            
            if (helpers::valueNotExistsInTable("$this->pageTable", "$this->pageTableId = ?",[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages'][$this->apiName][$this->apiName.'IdNotExists']]);
            }
            
             if (helpers::valueExistsInTable("$this->pageTable", "$this->checkFoundBefore and $this->pageTableId != ?", [$request['name_ar'], $request['name_en'], $request['id']])) {
              $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
        
            $image_name = $request['logo'];
            if (strpos($image_name, 'dump') !== false) {
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                if (file_exists('../../upload/dump/' . $url_array[$count_url_array - 1])) {
                    rename("../../upload/dump/" . $url_array[$count_url_array - 1], "../../views/default/images/branch_image/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'branch_image') !== false) {
                $image_name = $url_array[$count_url_array - 1];
            }

            $rupdate = R::load("$this->pageTable",$request['id']);
            $rupdate->branchName = empty($request['name_ar']) ? $rupdate->branchName : $request['name_ar'];
            $rupdate->nameEn = empty($request['name_en']) ? $rupdate->nameEn : $request['name_en'];
            $rupdate->branchAddress = empty($request['address']) ? $rupdate->branchAddress : $request['address'];
            $rupdate->addressEn = empty($request['address_en']) ? $rupdate->addressEn : $request['address_en'];
            $rupdate->description_ar = empty($request['description_ar']) ? $rupdate->description_ar : $request['description_ar'];
            $rupdate->description_en = empty($request['description_en']) ? $rupdate->description_en : $request['description_en'];
            $rupdate->branchDate = empty($request['branch_date']) ? $rupdate->branchDate : $request['branch_date'];
            $rupdate->phone = empty($request['phone']) ? $rupdate->phone : $request['phone'];
            $rupdate->mobile = empty($request['mobile']) ? $rupdate->mobile : $request['mobile'];
            $rupdate->email = empty($request['email']) ? $rupdate->email : $request['email'];
            $rupdate->latitude = empty($request['latitude']) ? $rupdate->latitude : $request['latitude'];
            $rupdate->longitude = empty($request['longitude']) ? $rupdate->longitude : $request['longitude'];
            $rupdate->branchNo = empty($request['branch_no']) ? $rupdate->branchNo : $request['branch_no'];
            $rupdate->message = empty($request['comment']) ? $rupdate->message : $request['comment'];
            $rupdate->logo = empty($image_name) ? $rupdate->logo : $image_name;
            $rupdate->branchTaxNo = empty($request['branch_tax_no']) ? $rupdate->branchTaxNo : $request['branch_tax_no'];
            $rupdate->status = !isset($request['status']) ? $rupdate->status : $request['status'];
            $rupdate->updatedAt = date('Y-m-d H:i:s');
            R::store($rupdate);
            $rupdate->path_image = $this->pathUrl . $image_name;
            $fresponse = helpers::beanToStdClass($rupdate,$this->allowedFields, $this->blockedFields,$this->renameFields);
            $this->respond(200,true,$this->trans['messages'][$this->apiName]['update'], null, [],$fresponse);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    /**
     * Delete a branch
     */
    function delete() {
       try{
            $allowed = ['id'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ]
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);
            if ($request['validation_errors']) $this->respond(400,false,$this->trans['httpStatusCodes']['400'], null,$request['validation_errors']);

            if (helpers::valueNotExistsInTable("$this->pageTable", "$this->pageTableId = ?",[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages'][$this->apiName][$this->apiName.'IdNotExists']]);
            }
            
            $rdelete = R::load("$this->pageTable",$request['id']);
            $id = R::trash($rdelete);
            $this->respond(200,true,$this->trans['messages'][$this->apiName]['softDelete'], null, [],[]);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }
}

require_once("_master/fireApi.php");