<?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) : '';
            $allowed = ['searchName','page', 'limit','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',
                ],
            ];

            $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 = 'governmentname as name';
            }else{
                $select = 'governmentname as name';
            }
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT governmetid  as id, $select FROM government WHERE governmetid = ?",[$request['id']]);
                $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);
            }

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


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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT governmetid as id, $select FROM government WHERE 1 $searchQuery LIMIT ? OFFSET ?";

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

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

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

            // Check if branch name already exists
            if (helpers::valueExistsInTable('government', 'name = ? ', [$request['name']])) {
               $this->respond(409,false,$this->trans['messages']['governorates']['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }

            $rdispense = R::dispense('government');
            $rdispense->governmentname = $request['name'];
            $id = R::store($rdispense);
            $fresponse = helpers::beanToStdClass($rdispense,[], [],['governmetid' => 'id','governmentname' => 'name']);
            $this->respond(200, true, $this->trans['messages']['governorates']['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('government', 'governmetid = ?',[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['governorates']['governorateIdNotExists']]);
            }
            
            $select = 'governmentname as name , governmentname as name_en';
    
            $response = R::getRow("SELECT governmetid  as id, $select FROM government WHERE governmetid = ?",[$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'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'name' => [
                    'rules' => 'required|text|min:1|max:200',
                    '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('government', 'governmetid = ?',[$request['id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['governorates']['governorateIdNotExists']]);
            }
            
            
            if (helpers::valueExistsInTable('government', 'name = ? and governmetid != ?', [$request['name'], $request['id']])) {
               $this->respond(409,false,$this->trans['messages']['governorates']['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }


            $rupdate = R::load('government',$request['id']);
            $rupdate->governmentname = empty($request['name']) ? $rupdate->governmentname : $request['name'];
            $id = R::store($rupdate);
            $rupdate->id = $id;
            $fresponse = helpers::beanToStdClass($rupdate,[], [],['governmetid' => 'id','governmentname' => 'name']);
            $this->respond(200,true,$this->trans['messages']['governorates']['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('government', 'governmetid = ?', [$request['id']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['id' => $this->trans['messages']['governorates']['governorateIdNotExists']]);
            }

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