<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
class pageClass extends apiHandler
{   
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
        $checkTokenClient = $this->checkTokenClient();
        $this->getrequest->clientid = $checkTokenClient->clientid;
    }
    
    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 : 10;
            $this->getrequest->id  = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;
            $allowed = ['clientid','page', 'limit','id'];
            $fields = [
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:100',
                    'type'  => 'integer',
                ],
                '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']);
            
            
            if($this->lang == 'ar'){
                $select = 'government.governmentname as governorate_name, clientarea.name as city_name';
            }else{
                $select = 'government.governmentname as governorate_name, clientarea.name as city_name';
            }
            
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT clientaddresses.id as id, addressTitle as address_title, clientaddresses.clientid as client_id, clientaddresses.name as name, clientaddresses.mobile as mobile, addressDetails as address_details,
            latitude,longitude, clientaddresses.governorateid as governorate_id, clientaddresses.cityid as city_id, $select FROM `clientaddresses`
                left join government on government.governmetid = clientaddresses.governorateid
                left join clientarea on clientarea.id = clientaddresses.cityid
                WHERE clientaddresses.isdel = 0 and clientaddresses.id = ? and clientaddresses.clientid = ?",[$request['id'], $request['clientid']]);
                $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);
            }


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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            
            $sql = "SELECT clientaddresses.id as id, addressTitle as address_title, clientaddresses.clientid as client_id, clientaddresses.name as name, clientaddresses.mobile as mobile, addressDetails as address_details,
            latitude,longitude, clientaddresses.governorateid as governorate_id, clientaddresses.cityid as city_id, $select FROM `clientaddresses`
                left join government on government.governmetid = clientaddresses.governorateid
                left join clientarea on clientarea.id = clientaddresses.cityid
                WHERE clientaddresses.isdel = 0 and clientaddresses.clientid = ? LIMIT ? OFFSET ?";
            $results   = R::getAll($sql, array($request['clientid'],$request['limit'], $offset));

            // إجمالي السجلات
            $totalRecords = R::getCell('SELECT COUNT(*) FROM clientaddresses WHERE isdel=0 and clientid = ?',[$request['clientid']]);
            
            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "Addresses"  => $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 = ['clientid','name','mobile', 'governorateid','cityid','addressDetails', 'latitude', 'longitude'];
            $fields = [
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'name' => [
                    'rules' => 'required|text|min:1|max:200',
                    'type'  => 'string',
                ],
                'mobile' => [
                    'rules' => 'required|numeric|min:8|max:11',
                    'type'  => 'integer',
                ],
                'governorateid' => [
                    'rules' =>  'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'cityid' => [
                    'rules' =>  'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'addressDetails' => [
                    'rules' => 'required|string|min:1|max:5000',
                    'type'  => 'string',
                ],
                'latitude' => [
                    'rules' => 'required|string',
                    'type'  => 'string',
                ],
                'longitude' => [
                    'rules' => 'required|string',
                    'type'  => 'string',
                ]
                // 'addressType' => [
                //     'rules' => 'required|integer|min:1',
                //     '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('client', 'clientid = ?', [$request['clientid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['clientid' => $this->trans['messages']['addresses']['clientIdNotExists']]);
            }
            
            if (helpers::valueNotExistsInTable('government', 'governmetid = ?', [$request['governorateid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['governorateid' => $this->trans['messages']['addresses']['governorateIdNotExists']]);
            }
            
            if (helpers::valueNotExistsInTable('clientarea', 'id = ?', [$request['cityid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['cityid' => $this->trans['messages']['addresses']['cityIdNotExists']]);
            }
            
            
            $rdispense = R::dispense('clientaddresses');
            $rdispense->addressTitle =  mb_substr($request['addressDetails'], 0, 100, "UTF-8");
            $rdispense->clientid = $request['clientid'];
            $rdispense->name = $request['name'];
            $rdispense->mobile = $request['mobile'];
            $rdispense->governorateid = $request['governorateid'];
            $rdispense->cityid = $request['cityid'];
            $rdispense->addressDetails = $request['addressDetails'];
            $rdispense->latitude = $request['latitude'];
            $rdispense->longitude = $request['longitude'];
            $rdispense->sysDate = date('Y-m-d');
            $rdispense->isdel = 0;
            $id = R::store($rdispense);
            $fresponse = helpers::beanToStdClass($rdispense,[], [],['id' => 'id','clientid' => 'client_id','name' => 'name','mobile' => 'mobile','governorateid' => 'governorate_id',
            'cityid' => 'city_id','addressDetails' => 'address_details','latitude' => 'latitude','longitude' => 'longitude']);
            $fresponse->governorate_name = $governorate_name = R::getcell("SELECT government.governmentname as governorate_name FROM `government` WHERE governmetid = ?",[$request['governorateid']]);
            $fresponse->city_name = $city_name = R::getcell("SELECT clientarea.name as city_name FROM `clientarea` WHERE id = ?",[$request['cityid']]);

            $this->respond(200,true,$this->trans['messages']['addresses']['200'], null, [],$fresponse);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
        
    }
    
    function edit() {
        try{
            $allowed = ['id', 'clientid'];
            $fields = [
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                '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('clientaddresses', 'id = ? and clientid = ?', [$request['id'], $request['clientid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['addressid' => $this->trans['messages']['addresses']['addressIdNotExists']]);
            }
            
             if($this->lang == 'ar'){
                $select = 'government.governmentname as governorate_name, clientarea.name as city_name';
                // $home = 'منزل';
                // $work = 'عمل';
                // $unknown = 'غير معروف';
            }else{
                $select = 'government.governmentname as governorate_name, clientarea.name as city_name';
                // $home = 'Home';
                // $work = 'Work';
                // $unknown = 'Unknown';
                // CASE clientaddresses.addresstype
                //    WHEN 1 THEN '$home'
                //    WHEN 2 THEN '$work'
                //    ELSE '$unknown' END as address_type_name
            }
            

            $response = R::getRow("SELECT clientaddresses.id as id, addressTitle as address_title, clientaddresses.clientid as client_id, clientaddresses.name as name, clientaddresses.mobile as mobile, addressDetails as address_details, latitude,longitude, clientaddresses.governorateid as governorate_id, clientaddresses.cityid as city_id, $select FROM `clientaddresses`
            left join government on government.governmetid = clientaddresses.governorateid
            left join clientarea on clientarea.id = clientaddresses.cityid
            WHERE clientaddresses.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 {
            $this->getrequest->addressType = (!empty($this->getrequest->addressType)) ? (int) $this->getrequest->addressType : 1;
            
            $allowed = ['id','clientid','name','mobile', 'governorateid','cityid','addressDetails', 'latitude', 'longitude','addressType'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'name' => [
                    'rules' => 'required|text|min:1|max:200',
                    'type'  => 'string',
                ],
                'mobile' => [
                    'rules' => 'required|numeric|min:8|max:11',
                    'type'  => 'integer',
                ],
                'governorateid' => [
                    'rules' =>  'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'cityid' => [
                    'rules' =>  'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'addressDetails' => [
                    'rules' => 'required|string|min:1|max:5000',
                    'type'  => 'string',
                ],
                'latitude' => [
                    'rules' => 'required|string|min:1|max:100',
                    'type'  => 'string',
                ],
                'longitude' => [
                    'rules' => 'required|string|min:1|max:100',
                    'type'  => 'string',
                ],
                'addressType' => [
                    'rules' => 'required|integer|min:1',
                    '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('clientaddresses', 'id = ?', [$request['id']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['addressid' => $this->trans['addresses']['addresses']['addressIdNotExists']]);
            }
            
            if (helpers::valueNotExistsInTable('client', 'clientid = ?', [$request['clientid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['clientid' => $this->trans['messages']['addresses']['clientIdNotExists']]);
            }
            
            if (helpers::valueNotExistsInTable('government', 'governmetid = ?', [$request['governorateid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['governorateid' => $this->trans['messages']['addresses']['governorateIdNotExists']]);
            }
            
            if (helpers::valueNotExistsInTable('clientarea', 'id = ?', [$request['cityid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['cityid' => $this->trans['messages']['addresses']['cityIdNotExists']]);
            }
            
            
            $rdispense = R::load('clientaddresses', $request['id']);
            $rdispense->addressTitle =  mb_substr($request['addressDetails'], 0, 100, "UTF-8");
            $rdispense->clientid = $request['clientid'];
            $rdispense->name = $request['name'];
            $rdispense->mobile = $request['mobile'];
            $rdispense->governorateid = $request['governorateid'];
            $rdispense->cityid = $request['cityid'];
            $rdispense->addressDetails = $request['addressDetails'];
            $rdispense->latitude = $request['latitude'];
            $rdispense->longitude = $request['longitude'];
            $id = R::store($rdispense);
            $fresponse = helpers::beanToStdClass($rdispense,[], [],['id' => 'id','clientid' => 'client_id','name' => 'name','mobile' => 'mobile','governorateid' => 'governorate_id',
            'cityid' => 'city_id','addressDetails' => 'address_details','latitude' => 'latitude','longitude' => 'longitude']);
             $fresponse->governorate_name = $governorate_name = R::getcell("SELECT government.governmentname as governorate_name FROM `government` WHERE governmetid = ?",[$request['governorateid']]);
            $fresponse->city_name = $city_name = R::getcell("SELECT clientarea.name as city_name FROM `clientarea` WHERE id = ?",[$request['cityid']]);
            $this->respond(200,true,$this->trans['messages']['addresses']['update'], null, [],$fresponse);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
        
    }
    
    
    function softDelete() {
        try{
            $allowed = ['id','clientid'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'clientid' => [
                    '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('clientaddresses', 'id = ?', [$request['id']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['addressid' => $this->trans['addresses']['addresses']['addressIdNotExists']]);
            }

            if (helpers::valueNotExistsInTable('client', 'clientid = ?', [$request['clientid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['clientid' => $this->trans['messages']['addresses']['clientIdNotExists']]);
            }

            $rupdate = R::load('clientaddresses', $request['id']);
            $rupdate->isdel = 1;
            $id = R::store($rupdate);
            $this->respond(200,true,$this->trans['messages']['addresses']['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");
