<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
class pageClass extends apiHandler
{   
    private $pageTable;
    private $pageTableId;
    private $selectColumns;
    private $searchColumns;
    private $checkFoundBefore;
    private $renameFields;
    private $blockedFields;
    private $pathUrl;
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
        $this->pageTable = 'properties';
        $this->pageTableId = 'properties.propertyid';
        $this->selectColumns = 'properties.propertyid as id, propertyparent as parent, propertydefault as property_default, propertyurl as property_url';
        $this->searchColumns = '(propertyname LIKE ? OR propertyname_en LIKE ?)';
        $this->checkFoundBefore = '(propertyname LIKE ? OR propertyname_en LIKE ?)';
        $this->renameFields = ['propertyid' => 'id','propertyname' => 'title','propertyname_en' => 'title_en','propertyparent' => 'parent','propertydefault' => 'property_default',
                'propertyurl' => 'property_url'];
        $this->allowedFields = [];
        $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) : ''; 

            $allowed = ['page', 'limit','id','searchName'];
            $fields = [
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:100',
                    'type'  => 'integer',
                ],
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'searchName' => [
                    'rules' => 'text|min:1|max:100',
                    '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->lang == 'ar'){
                $select = ' ,propertyname as title';
            }else{
                $select = ' ,propertyname_en as title';
            }
            $this->selectColumns = $this->selectColumns . $select;
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT $this->selectColumns FROM $this->pageTable 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)";
            }
           


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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT $this->selectColumns FROM $this->pageTable WHERE  1 $searchQuery  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(
                    "Properties"  => $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 = ['title','title_en', 'parent', 'property_default', 'property_url'];
            
            $fields = [
                'title' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'title_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'parent' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'property_default' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'property_url' => [
                    'rules' => 'text',
                    '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['title'], $request['title_en']])) {
              $this->respond(409,false,$this->trans['messages']['properties']['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            
            $rdispense = R::dispense("$this->pageTable");
            $rdispense->propertyname = $request['title'];
            $rdispense->propertyname_en = $request['title_en'];
            $rdispense->propertyparent = $request['parent'];
            $rdispense->propertydefault = $request['property_default'];
            $rdispense->propertyurl = $request['property_url'];
            $id = R::store($rdispense);
            $fresponse = helpers::beanToStdClass($rdispense,$this->allowedFields, $this->blockedFields,$this->renameFields);
            $this->respond(200, true, $this->trans['messages']['properties']['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']['ads']['adIdNotExists']]);
            }
            
            $select = ', propertyname as title, propertyname_en title_en';
            $this->selectColumns = $this->selectColumns . $select;
            $response = R::getRow("SELECT $this->selectColumns FROM $this->pageTable 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','title','title_en', 'parent', 'property_default', 'property_url'];
            
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'title' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'title_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'parent' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'property_default' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'property_url' => [
                    'rules' => 'text',
                    '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']['properties']['propertyIdNotExists']]);
            }
            
            
            if (helpers::valueExistsInTable("$this->pageTable", "$this->checkFoundBefore and $this->pageTableId != ?", [$request['title'], $request['title_en'], $request['id']])) {
              $this->respond(409,false,$this->trans['messages']['properties']['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            
            
             
            $rupdate = R::load("$this->pageTable",$request['id']);;
            $rupdate->propertyname = $request['title'];
            $rupdate->propertyname_en = $request['title_en'];
            $rupdate->propertyparent = $request['parent'];
            $rupdate->propertydefault = $request['property_default'];
            $rupdate->propertyurl = $request['property_url'];
            $id = R::store($rupdate);
            $fresponse = helpers::beanToStdClass($rupdate,$this->allowedFields, $this->blockedFields,$this->renameFields);
            $this->respond(200,true,$this->trans['messages']['properties']['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']['properties']['propertyIdNotExists']]);
            }

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