<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
class pageClass extends apiHandler
{
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
    }

    function index() {
        try{

            $this->getrequest->page  = isset($this->getrequest->page) ? (int) $this->getrequest->page : 1;
            $this->getrequest->limit    =isset($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->governorate_id  = isset($this->getrequest->governorate_id) ? (int) $this->getrequest->governorate_id : 1;
            $allowed = ['searchName','page', 'limit','id','governorate_id'];
            $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:100',
                    'type'  => 'integer',
                ],
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'governorate_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']);
            $src = $this->hosturl.'/upload/clientarea/';
            if($this->lang == 'ar'){
                $select = 'name as name';
            }else{
                $select = 'name as name';
            }
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT id, $select, shipping_cost FROM clientarea WHERE id = ?",[$request['id']]);
                $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);
            }

            $searchQuery = "";
            if ($request['searchName']) {
                $ids = R::getCol('SELECT id FROM clientarea WHERE (name LIKE ? OR name LIKE ?)', ['%' . $request['searchName'] . '%', '%' . $request['searchName'] . '%']);
                $idList = implode(",", $ids);
                $searchQuery .= " AND id in (0$idList)";
            }


            $searchJoin = "";
            if ($request['governorate_id']) {
                $searchJoin .= " 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 id, $select, shipping_cost FROM clientarea $searchJoin WHERE 1 $searchQuery LIMIT ? OFFSET ?";

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

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

            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "cities"  => $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 = ['governorate_id','name', 'shipping_cost'];
            $fields = [
                'governorate_id' => [
                    'rules' => 'required|integer',
                    'type'  => 'integer',
                ],
                'name' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                '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']['governorateIdNotExists']]);
            }

            if (helpers::valueExistsInTable('clientarea', 'join goverarea on clientarea.id = goverarea.clientareaid  where clientarea.name = ? and governmentid = ?', [$request['name'], $request['governorate_id']])) {
               $this->respond(409,false,$this->trans['messages']['cities']['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            

            $rdispense = R::dispense('clientarea');
            $rdispense->name = $request['name'];
            $rdispense->shipping_cost = $request['shipping_cost'];
            $id = R::store($rdispense);
            
            
            $rgoverarea = R::dispense('goverarea');
            $rgoverarea->clientareaid = $id;
            $rgoverarea->governmentid = $request['governorate_id'];
            R::store($rgoverarea);
            
            $this->respond(200, true, $this->trans['messages']['governorates']['200'], null, [],$rdispense);
        } 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('clientarea', 'id = ?',[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['cities']['cityIdNotExists']]);
            }
            
            $select = 'name as name, name as name_en';
            
            $response = R::getRow("SELECT id, $select, shipping_cost FROM clientarea WHERE id = ?",[$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 = ['governorate_id','id','name','shipping_cost'];
            $fields = [
                'governorate_id' => [
                    'rules' => 'required|integer',
                    'type'  => 'integer',
                ],
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'name' => [
                    'rules' => 'required|text|min:1|max:200',
                    'type'  => 'string',
                ],
                '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']['governorateIdNotExists']]);
            }
            
            
            if (helpers::valueNotExistsInTable('clientarea', 'id = ?',[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['cities']['cityIdNotExists']]);
            }
            
            
            if (helpers::valueExistsInTable('clientarea', 'join goverarea on clientarea.id = goverarea.clientareaid  where  clientarea.name = ? and clientarea.id != ? and governmetid = ?', [$request['name'], $request['id'], $request['governorate_id']])) {
               $this->respond(409,false,$this->trans['messages']['governorates']['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }


            $rupdate = R::load('clientarea',$request['id']);
            $rupdate->name = empty($request['name']) ? $rupdate->name : $request['name'];
            $rupdate->shipping_cost = empty($request['shipping_cost']) ? $rupdate->shipping_cost : $request['shipping_cost'];
            $id = R::store($rupdate);
            
            
            
            $rgoverarea = R::findOne('goverarea', 'clientareaid = ?',[$request['id']]);
            $rgoverarea->governmentid = $request['governorate_id'];
            R::store($rgoverarea);
            
            $this->respond(200,true,$this->trans['messages']['governorates']['update'], null, [],$rupdate);
        }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('clientarea', 'id = ?', [$request['id']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['cities']['cityIdNotExists']]);
            }

            $rupdate = R::load('clientarea', $request['id']);
            $id = R::trash($rupdate);
            $this->respond(200,true,$this->trans['messages']['cities']['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");
