<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
class pageClass extends apiHandler
{   private $apiName;
    private $pageTable;
    private $pageTableId;
    private $pageJoin;
    private $selectColumns;
    private $searchColumns;
    private $tarnsSelect;
    private $checkFoundBefore;
    private $renameFields;
    private $blockedFields;
    private $pathUrl;
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
        $this->pathUrl =  $this->hosturl.'/upload/sellbillstatus/';
        $this->apiName = 'sellbillstatus';
        $this->pageTable = 'sellbillstatus';
        $this->pageTableId = 'sellbillstatus.id';
        $this->pageJoin = ' left join user on sellbillstatus.userid = user.userid  ';
        $this->selectColumns = 'sellbillstatus.id as id, sellbillid as sellbill_id, sellbillstatus.userid as user_id, sysdate as sys_date, employeename as user_creat_at';
        $this->searchColumns = '(sellbillstatus.status LIKE ? or sellbillstatus.status_ar LIKE ?)';
        $this->tarnsSelect = ['ar'=>' , sellbillstatus.status_ar as status','en'=>', sellbillstatus.status as status','lang_all'=>' , sellbillstatus.status_ar as status_ar , sellbillstatus.status as status_en'];
        $this->checkFoundBefore = '(sellbillstatus.status LIKE ? or sellbillstatus.status_ar LIKE ?)';
        $this->renameFields = ['sellbillid' => 'sellbill_id','status' => 'status_en','status_ar' => 'status_ar','userid' => 'user_id','sysdate' => 'sys_date'];
        $this->allowedFields = ['id','user_creat_at'];
        $this->blockedFields = [];
    }

    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) : ''; 
            $this->getrequest->sellbill_id = (!empty($this->getrequest->sellbill_id)) ? (int) $this->getrequest->sellbill_id : 0;
            if ($this->getrequest->id > 0) {
                $rulesellbill_id = 'integer';
            }else{
                $rulesellbill_id = 'required|integer|min:1';
            }

            $allowed = ['page', 'limit','id','searchName','sellbill_id'];
            $fields = [
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:10000',
                    'type'  => 'integer',
                ],
                'id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'searchName' => [
                    'rules' => 'text|min:1|max:100',
                    'type'  => 'string',
                ],
                'sellbill_id' => [
                    'rules' => $rulesellbill_id,
                    '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 = ?",[$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['sellbill_id']) {
                $searchQuery .= " AND sellbillid = ". $request['sellbill_id'];
            }
           


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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT $this->selectColumns FROM $this->pageTable $this->pageJoin 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(
                    "$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 statuses() {
        
         if($this->lang == 'en'){
            $results = array("new" => "new","prepare"  => "prepare","shipped"  => "shipped","deliver"  => "deliver","refused"  => "refused");
         }else{
            $results = array("new" => "جديد","prepare"  => "قيد التجهيز","shipped"  => "تم الشحن","deliver"  => "تم التسليم","refused"  => "مرفوض");
         }
          
          $response = array(
                    "$this->apiName"  => $results,
                    "pagination" => [
                      "current_page"=> 1,
                      "total_pages"=> 1,           
                      "total_items"=> 4,
                      "per_page"=> 4
                    ]
                );
           $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);
    }
    
    
  
    function add() {

        try {
            $allowed = ['sellbill_id','status_en','status_ar', 'user_id'];
            
            $fields = [
                'sellbill_id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'status_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'status_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ]
            ];

            $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("sellbill", "sellbillid = ?", [$request['sellbill_id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['sellbill_id' => $this->trans['messages']['sellbill']['sellbillIdNotExists']]);
            }
            
            
            if (helpers::valueExistsInTable("$this->pageTable", "$this->checkFoundBefore", [$request['status_en'], $request['status_ar']])) {
              $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            
            $rdispense = R::dispense("$this->pageTable");
            $rdispense->status = $request['status_en'];
            $rdispense->status_ar = $request['status_ar'];
            $rdispense->sellbillid = $request['sellbill_id'];
            $rdispense->userid = $request['user_id'];
            $rdispense->sysdate = date('Y-m-d H:i:s');
            $id = R::store($rdispense);
            $user = helpers::getRowTable("user", "userid = ?", [$request['user_id']]);
            $rdispense->user_creat_at = $user['employeename'];
            $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 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'][$this->apiName][$this->apiName.'IdNotExists']]);
            }
            
            $this->selectColumns = $this->selectColumns . $this->tarnsSelect['lang_all'];
            $response = R::getRow("SELECT $this->selectColumns FROM $this->pageTable $this->pageJoin 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','sellbill_id','status_en','status_ar', 'user_id'];
            
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'sellbill_id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'status_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'status_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ]
            ];
            
         
        

            $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']]);
            }
            
            if (helpers::valueNotExistsInTable("sellbill", "sellbillid = ?", [$request['sellbill_id']])) {
              $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['sellbill_id' => $this->trans['messages']['sellbill']['sellbillIdNotExists']]);
            }
            
            
            if (helpers::valueExistsInTable("$this->pageTable", "$this->checkFoundBefore and $this->pageTableId != ?", [$request['status_en'], $request['status_ar'], $request['id']])) {
              $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            }
            
            
             
            $rupdate = R::load("$this->pageTable",$request['id']);;
            $rupdate->status = $request['status_en'];
            $rupdate->status_ar = $request['status_ar'];
            $rupdate->sellbillid = $request['sellbill_id'];
            $rupdate->userid = $request['user_id'];
            $id = R::store($rupdate);
            $user = helpers::getRowTable("user", "userid = ?", [$rupdate['user_id']]);
            $rupdate->user_creat_at = $user['employeename'];
            $fresponse = helpers::beanToStdClass($rupdate,$this->allowedFields, $this->blockedFields,$this->renameFields);
            $this->respond(200,true,$this->trans['messages'][$this->apiName]['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'][$this->apiName][$this->apiName.'IdNotExists']]);
            }

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