<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
class pageClass extends apiHandler
{   
    private $apiName;
    private $pageTable;
    private $pageTableId;
    private $pageJoin;
    private $selectColumns;
    private $selectWhere;
    private $searchColumns;
    private $tarnsSelect;
    private $checkFoundBefore;
    private $renameFields;
    private $blockedFields;
    private $pathUrl;
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
        $this->apiName = 'cities';
        $this->pageTable = 'clientarea';
        $this->pageTableId = 'clientarea.id';
        $this->pageJoin = ' left join user on clientarea.user_id = user.userid  ';
        $this->selectColumns = 'clientarea.id as id, clientarea.user_id, clientarea.sys_date, clientarea.is_active, clientarea.is_del, employeename as user_creat_at, shipping_cost';
        $this->selectWhere = ' and clientarea.is_del = 0 and clientarea.is_active = 1  ';
        $this->searchColumns = '(clientarea.name LIKE ? or clientarea.name_en LIKE ?)';
        $this->tarnsSelect = ['ar'=>' , clientarea.name as name','en'=>', clientarea.name_en as name','lang_all'=>' , clientarea.name as name_ar , clientarea.name_en as name_en'];
        $this->checkFoundBefore = '(clientarea.name LIKE ? or clientarea.name_en LIKE ?)';
        $this->renameFields = ['name' => 'name_ar'];
        $this->allowedFields = ['id','user_id','name_en','shipping_cost','sys_date','user_creat_at','is_active','is_del'];
        $this->blockedFields = [];
        $this->pathUrl = '';
        
    }

    function index() {
         
        try{
            $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 = (!empty($this->getrequest->id)) ? (int) $this->getrequest->id : 0; 
            $this->getrequest->searchName = (!empty($this->getrequest->searchName)) ? trim($this->getrequest->searchName) : ''; 
            $this->getrequest->governorate_id  = isset($this->getrequest->governorate_id) ? (int) $this->getrequest->governorate_id : '';
            if ($this->getrequest->id > 0) {
                $rulegovernorate_id = 'integer';
            }else{
                $rulegovernorate_id = 'required|integer|min:1';
            }

            $allowed = ['page', 'limit','id','searchName','governorate_id'];
            $fields = [
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:10000',
                    'type'  => 'integer',
                ],
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'searchName' => [
                    'rules' => 'text|min:1|max:100',
                    'type'  => 'string',
                ],
                'governorate_id' => [
                    'rules' => $rulegovernorate_id,
                    '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 = ? $this->selectWhere ",[$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)";
            }
            
             
            if ($request['governorate_id']) {
                $this->pageJoin .= " join goverarea on clientarea.id = goverarea.clientareaid ";
                $searchQuery .= " AND goverarea.governmentid = " . $request['governorate_id'];
            }
         

            // حساب الإزاحة (Offset)
            $offset = ($request['page'] > 0 ? $request['page'] - 1 : 0) * $request['limit'];

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT $this->selectColumns FROM $this->pageTable $this->pageJoin WHERE  1 $searchQuery $this->selectWhere  LIMIT ? OFFSET ?";
   

         
  
            $results   = R::getAll($sql, array($request['limit'], $offset));

            // إجمالي السجلات
            $totalRecords = R::getCell("SELECT COUNT(*) FROM $this->pageTable WHERE 1 $searchQuery");

            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "$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(), []);
        }
        
    }
    
    
  
    function add() {

        try {
            $allowed = ['name_ar','name_en', 'user_id', 'governorate_id', 'shipping_cost'];
            
            $fields = [
                'name_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'name_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'governorate_id' => [
                    'rules' => 'required|integer',
                    'type'  => 'integer',
                ],
                'shipping_cost' => [
                    'rules' => 'integer',
                    '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('government', 'governmetid = ?',[$request['governorate_id']])) {
               $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['governorate_id' => $this->trans['messages']['governorates']['governoratesIdNotExists']]);
            }
            
            if (helpers::valueExistsInTable("$this->pageTable", "join goverarea on clientarea.id = goverarea.clientareaid where $this->checkFoundBefore and governmentid = ? ", [$request['name_ar'], $request['name_en'], $request['governorate_id']])) {
              $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            
            $rdispense = R::dispense("$this->pageTable");
            $rdispense->name = $request['name_ar'];
            $rdispense->name_en = $request['name_en'];
            $rdispense->shipping_cost = $request['shipping_cost'];
            $rdispense->user_id = $request['user_id'];
            $rdispense->sys_date = date('Y-m-d H:i:s');
            $rdispense->is_active = 1;
            $rdispense->is_del = 0;
            $id = R::store($rdispense);
            
            $rgoverarea = R::dispense('goverarea');
            $rgoverarea->clientareaid = $id;
            $rgoverarea->governmentid = $request['governorate_id'];
            R::store($rgoverarea);
            
            $user = helpers::getRowTable("user", "userid = ?", [$request['user_id']]);
            $rdispense->user_creat_at = $user['employeename'];
            $fresponse = helpers::beanToStdClass($rdispense,$this->allowedFields, $this->blockedFields,$this->renameFields);
            $this->respond(200, true, $this->trans['messages'][$this->apiName]['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(), []);
        }
        
    }

    function update() {
        try {
            $allowed = ['id','name_ar','name_en', 'user_id','is_active', 'governorate_id', 'shipping_cost'];
            
            $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',
                ],
                'shipping_cost' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'is_active' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 1
                ],
                'governorate_id' => [
                    'rules' => 'required|integer',
                    'type'  => 'integer',
                ],
                'shipping_cost' => [
                    'rules' => 'integer',
                    '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('government', 'governmetid = ?',[$request['governorate_id']])) {
               $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['governorate_id' => $this->trans['messages']['governorates']['governoratesIdNotExists']]);
            }
            
            
            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", "join goverarea on clientarea.id = goverarea.clientareaid where $this->checkFoundBefore and governmentid = ? and $this->pageTableId != ?", [$request['name_ar'], $request['name_en'], $request['governorate_id'], $request['id']])) {
              $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
           
            $rupdate = R::load("$this->pageTable",$request['id']);
            $rupdate->name = empty($request['name_ar']) ? $rupdate->name : $request['name_ar'];
            $rupdate->name_en = empty($request['name_en']) ? $rupdate->name_en : $request['name_en'];
            $rupdate->shipping_cost = empty($request['shipping_cost']) ? $rupdate->shipping_cost : $request['shipping_cost'];
            $rupdate->user_id = empty($request['user_id']) ? $rupdate->user_id : $request['user_id'];
            $rupdate->is_active = empty($request['is_active']) ? $rupdate->is_active : $request['is_active'];
            $rupdate->is_del = empty($request['is_del']) ? $rupdate->is_del : $request['is_del'];
            $id = R::store($rupdate);
            
            $rgoverarea = R::findOne('goverarea', 'clientareaid = ?',[$request['id']]);
            if($rgoverarea){
               $rgoverarea->governmentid = $request['governorate_id'];
               R::store($rgoverarea);
            }else{
                $urgoverarea = R::dispense('goverarea');
                $urgoverarea->clientareaid = $request['id'];
                $urgoverarea->governmentid = $request['governorate_id'];
                R::store($urgoverarea);  
            }
            
            $user = helpers::getRowTable("user", "userid = ?", [$rupdate['user_id']]);
            $rupdate->user_creat_at = $user['employeename'];
            $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(), []);
        }
    }

    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']);
            $rdelete->is_del = 1;
            R::store($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(), []);
        }
    }


  

    public function __destruct() {
        parent::__destruct();
    }

}
require_once("_master/fireApi.php");
