<?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->clientSource !== 'web'){
            $checkTokenClient = $this->checkTokenClient();
            $this->getrequest->clientid = $checkTokenClient->clientid;
            if (empty($this->getrequest->branch_id)) {
                $this->getrequest->branch_id = isset($checkTokenClient->branchId) ? (int)$checkTokenClient->branchId : 0;
            }
        }else if($this->clientSource == 'web' && $this->getrequest->clientid){
            $this->getrequest->clientid = $this->getrequest->clientid;
        }
        $this->pathUrl =  $this->hosturl.'/upload/prescriptions/';
        $this->apiName = 'prescriptions';
        $this->pageTable = 'prescriptions';
        $this->pageTableId = 'prescriptions.id';
        $this->pageJoin = ' left join user on prescriptions.user_id = user.userid left join client on prescriptions.clientid = client.clientid  ';
        $this->selectWhere = ' and prescriptions.is_del= 0 and prescriptions.is_active= 0 ';
        $this->selectColumns = "prescriptions.id as id, prescriptions.status as status, prescriptions.order_id as order_id, prescriptions.clientid as client_id, CONCAT('$this->pathUrl', image) as image, prescriptions.note,prescriptions.replay_note, prescriptions.is_active, prescriptions.is_del, 
        prescriptions.sys_date, prescriptions.user_id, employeename as user_creat_at, clientname as name , clientphone as mobile, clientmobile as affiliate_mobile, txtemail as email ";
        $this->searchColumns = '(prescriptions.note LIKE ?)';
        $this->tarnsSelect = ['ar'=>" , CASE WHEN status = 1 THEN 'جديد' WHEN status = 2 THEN 'قيد المراجعة'  WHEN status = 3 THEN 'تمت الموافقة'  ELSE 'مرفوضة' END AS status_name",'en'=>" , CASE WHEN status = 1 THEN 'new' WHEN status = 2 THEN 'prepare' 
        WHEN status = 3 THEN 'Approved'  ELSE 'refused' END AS status_name",'lang_all'=>''];        
        $this->checkFoundBefore = '(prescriptions.note LIKE ?)';
        $this->renameFields = ['clientid' => 'client_id'];
        $this->allowedFields = ['id','note','note','replay_note','is_active','is_del','sys_date','image','path_image','user_creat_at','status','order_id','branch_id'];
        $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) : ''; 
            if($this->clientSource == 'web'){
              $clientRule = 'integer|min:1';
            }else{
              $clientRule =  'required|integer|min:1'; 
            }
            $allowed = ['clientid','page', 'limit','id','searchName'];
            $fields = [
                'clientid' => [
                    'rules' => $clientRule,
                    'type'  => 'integer'
                ],
                'page' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'limit' => [
                    'rules' => 'required|integer|min:1|max:100000',
                    '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']);
            

            $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'];
            }
          


            // حساب الإزاحة (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 LIMIT ? OFFSET ?";
            // print_r($sql);
          
      
         
  
            $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->pageTable"  => $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','note','replay_note','image','user_id'];
            
            $fields = [
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                'note' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'replay_note' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'image' => [
                    'rules' => 'required|text|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']);
            }
            
          
            
            // if (helpers::valueExistsInTable("$this->pageTable", "$this->checkFoundBefore", [$request['title_ar'], $request['title_en']])) {
            //   $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            // }
            
            
               $image_name = $request['image'];
            if (strpos($image_name, 'dump') !== false) {
                //mine
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                if (file_exists('../../upload/dump/' . $url_array[$count_url_array - 1])) {
                    rename("../../upload/dump/" . $url_array[$count_url_array - 1], "../../upload/prescriptions/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'prescriptions') !== false) {
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                $image_name = $url_array[$count_url_array - 1];
            }else if (file_exists('../../upload/dump/'.$image_name)) {
                    rename("../../upload/dump/" . $image_name, "../../upload/prescriptions/".$image_name);
            }
         
            
            $rdispense = R::dispense("$this->pageTable");
            $rdispense->clientid = $request['clientid'];
            $rdispense->note = $request['note'];
            $rdispense->replay_note = $request['replay_note'];
            $rdispense->image = $image_name;
            $rdispense->status = 1;
            $rdispense->is_active = 0;
            $rdispense->is_del = 0;
            $rdispense->user_id = $request['user_id'];
            $rdispense->sys_date = date('Y-m-d H:i:s');
            $rdispense->branch_id = $request['branch_id'];
            $id = R::store($rdispense);
            $user = helpers::getRowTable("user", "userid = ?", [$request['user_id']]);
            $rdispense->user_creat_at = $user['employeename'];
            $rdispense->path_image = $this->pathUrl . $rdispense->image;
            $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']]);
            $client = helpers::getRowTable("client", "clientid = ?", [$response['client_id']]);
            $response['name'] = $client['clientname'];
            $response['mobile'] = $client['clientphone'];
            $response['affiliate_mobile'] = $client['clientmobile'];
            $response['email'] = $client['txtemail'];
            $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','clientid','note','replay_note','image','status','user_id','order_id'];
            
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                 'clientid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                  'note' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                 'replay_note' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'order_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'status' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 1
                ],
                'image' => [
                    'rules' => 'text|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']);
            }
            
            
            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::valueExistsInTable("$this->pageTable", "$this->checkFoundBefore and $this->pageTableId != ?", [$request['title_ar'], $request['title_en'], $request['id']])) {
            //   $this->respond(409,false,$this->trans['messages'][$this->apiName]['dataUsedBy'], null,['name' => $this->trans['messages']['nameExists']]);
            // }
            
            $image_name = $request['image'];
            if (strpos($image_name, 'dump') !== false) {
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                if (file_exists('../../upload/dump/' . $url_array[$count_url_array - 1])) {
                    rename("../../upload/dump/" . $url_array[$count_url_array - 1], "../../upload/prescriptions/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'prescriptions') !== false) {
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                $image_name = $url_array[$count_url_array - 1];
            }
            
            
             
            $rupdate = R::load("$this->pageTable",$request['id']);
            $rupdate->clientid = $request['clientid'];
            $rupdate->note = $request['note'];
            $rupdate->replay_note = $request['replay_note'];
            $rupdate->status = $request['status'];
            $rupdate->image = $image_name;
            $rupdate->is_active = 0;
            $rupdate->is_del = 0;
            $rupdate->user_id = $request['user_id'];
            $rupdate->order_id = $request['order_id'];
            $id = R::store($rupdate);
            $user = helpers::getRowTable("user", "userid = ?", [$rupdate['user_id']]);
            $rupdate->user_creat_at = $user['employeename'];
            $rupdate->path_image = $this->pathUrl . $image_name;
            $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']);
            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");
