

<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
class pageClass extends apiHandler
{   
    private $apiName;
    private $pageTable;
    private $pageTableId;
    private $pageJoin;
    private $selectColumns;
    private $searchColumns;
    private $selectWhere;
    private $tarnsSelect;
    private $checkFoundBefore;
    private $renameFields;
    private $blockedFields;
    private $pathUrl;
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
        if($this->accessToken){
            $checkTokenClient = $this->checkTokenClient();
            $this->getrequest->clientid = $checkTokenClient->clientid;
        }
        $this->pathUrl =  $this->hosturl.'/upload/clientaddresses/';
        $this->apiName = 'contactus';
        $this->pageTable = 'contactus';
        $this->pageTableId = 'contactus.id';
        $this->pageJoin = ' left join client on contactus.clientid = client.clientid  ';
        $this->selectWhere = ' and contactus.isdel = 0  ';
        $this->selectColumns = "contactus.id as id, contactus.clientid as client_id, contactus.name as name, contactus.mobile as mobile, contactus.email as email,subject, message, client.clientname as client_name ";
        $this->searchColumns = '(contactus.name LIKE ? or contactus.mobile LIKE ? or contactus.message LIKE ?)';
        $this->tarnsSelect = ['ar'=>'  ','en'=>'','lang_all'=>''];
        $this->checkFoundBefore = '';
        $this->renameFields = ['clientid' => 'client_id'];
        $this->allowedFields = ['id','name','mobile','email','subject','message','client_name'];
        $this->blockedFields = [];
    }
    
    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;
            $this->getrequest->is_sort = isset($this->getrequest->is_sort) ? $this->getrequest->is_sort : '';

            $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']);
            
             $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['clientid']) {
                $searchQuery .= " AND $this->pageTable.clientid = ". $request['clientid'];
            }
            
            $orderQuery = '';
            switch ($this->getrequest->is_sort) {
                case 'newest':
                    $orderQuery .= ' order by id desc';
                    break;
                case 'oldest':
                    $orderQuery .= ' order by id asc';
                    break;
                default:
                    $orderQuery .= ' order by id desc';
                    break;
            }


            // حساب الإزاحة (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 $orderQuery 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 {
            if($this->getrequest->clientid){
                $clientRule = 'required|numeric';
                $notrequired = '';
            }else{
                $clientRule = '';
                $notrequired = '';
            }
            
            $allowed = ['clientid','name','mobile','email', 'subject', 'message'];
            $fields = [
                'clientid' => [
                    'rules' => $clientRule,
                    'type'  => 'integer',
                ],
                'name' => [
                    'rules' => $notrequired.'text|min:1|max:200',
                    'type'  => 'string',
                ],
                'mobile' => [
                    'rules' => $notrequired.'numeric|digits_between:8,11',
                    'type'  => 'string',
                ],
                'email' => [
                    'rules' => $notrequired.'email|min:1|max:100',
                    'type'  => 'email',
                ],
                'subject' => [
                    'rules' => 'string|max:255',
                    'type'  => 'string',
                ],
                'message' => [
                    'rules' => 'required|string|min:1|max:5000',
                    'type'  => 'string',
                ]
            ];
  
            $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->getrequest->clientid){
                if (helpers::valueNotExistsInTable('client', 'clientid = ?', [$request['clientid']])) {
                    $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['clientid' => $this->trans['messages'][$this->apiName]['clientIdNotExists']]);
                }
                $clientData = R::load('client',$request['clientid']);
                $request['name'] = $clientData->clientname;
                $request['mobile'] = $clientData->clientphone;
                $request['email'] = $clientData->txtemail;
            }else{
                $request['clientid'] = 0;
            }
            
            $rdispense = R::dispense('contactus');
            $rdispense->clientid = $request['clientid'];
            $rdispense->name = $request['name'];
            $rdispense->mobile = $request['mobile'];
            $rdispense->email = $request['email'];
            if(!$request['subject']){
              $request['subject'] =  mb_substr($request['message'], 0, 100, "UTF-8");
            }
            $rdispense->subject = $request['subject'];
            $rdispense->message = $request['message'];
            $rdispense->sysDate = date('Y-m-d');
            $rdispense->isRead = 0;
            $rdispense->userreadid = 0;
            $rdispense->isdel = 0;
            $id = R::store($rdispense);
            $client = helpers::getRowTable("client", "clientid = ?", [$rdispense['clientid']]);
            $rdispense->client_name = $client['clientname'];
            $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 softDelete() {
        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']]);
            }

            $rupdate = R::load("$this->pageTable", $request['id']);
            $rupdate->isdel = 1;
            $id = R::store($rupdate);
            $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");
