<?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;
        }else if($this->clientSource == 'web' && $this->getrequest->clientid){
            $this->getrequest->clientid = $this->getrequest->clientid;
        }
        
        $this->pathUrl =  $this->hosturl.'/upload/notifications/';
        $this->apiName = 'notifications';
        $this->pageTable = 'notifications';
        $this->pageTableId = 'notifications.id';
        $this->pageJoin = " 
        LEFT JOIN branch  ON notifications.target_type = 'branch' AND notifications.target_id = branch.branchId 
        LEFT JOIN government  ON notifications.target_type = 'government' AND notifications.target_id = government.governmetid
        LEFT JOIN clientarea  ON notifications.target_type = 'city' AND notifications.target_id = clientarea.id 
        left join user on notifications.user_id = user.userid  ";
        $this->selectWhere = ' and notifications.is_del= 0 and notifications.is_active= 1 ';
        $this->selectColumns = "notifications.id as id, CONCAT('$this->pathUrl', image) as image, notifications.type, notifications.target_type, notifications.target_id, notifications.client_ids,  notifications.is_active, notifications.is_del, notifications.sys_date, notifications.user_id, employeename as user_creat_at ";
        $this->searchColumns = '(notifications.title_ar LIKE ? or notifications.title_en LIKE ?)';
        $this->tarnsSelect = ['ar'=>' , notifications.title_ar as title , notifications.content_ar as content, branch.branchName as branch_name, government.governmentname as governorate_name , clientarea.name as city_name'
        ,'en'=>', notifications.title_en as title, notifications.content_en as content, branch.nameEn as branch_name, government.governmentname_en as governorate_name , clientarea.name_en as city_name',
        'lang_all'=>' , notifications.title_ar , notifications.content_ar, notifications.title_en , notifications.content_en'];
        $this->checkFoundBefore = '(notifications.title_ar LIKE ? or notifications.title_en LIKE ?)';
        $this->renameFields = [];
        $this->allowedFields = ['id','title_ar','title_en','content_ar','content_en','branch_name','governorate_name','city_name','type','path_image','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->type  = isset($this->getrequest->type) ?  $this->getrequest->type : '';

            $allowed = ['clientid','page', 'limit','id','searchName','type'];
            $fields = [
                'clientid' => [
                    'rules' => 'integer|min:1',
                    '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',
                ],
                 'type' => [
                    'rules' => 'string',
                    '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']]);
                if($response['client_ids'] != 0){
                    $client_ids = explode(',', $response['client_ids']);
                    if (!in_array($request['clientid'], $client_ids)) {
                        $this->respond(403,true,$this->trans['messages']['notifications']['403'], null, [],[]);
                    }
                    
                }
                $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['type']) {
                $searchQuery .= " AND $this->pageTable.type = ". $request['type'];
            }
            
            
            
            if ($request['branch_id'] > 0) {
                $searchQuery .= " AND $this->pageTable.branch_id = ". $request['branch_id'];
            }
            
            
            if ($request['clientid']) {
                $this->pageJoin  .= " LEFT JOIN notificationsclients ON notificationsclients.notification_id = notifications.id ";
                $client = helpers::getRowTable("client", "clientid = ?", [$request['clientid']]);
                $clientid = $client['clientid'];
                $branchid = $client['branchId'];
                $governorateid = $client['governorate_id'];
                $cityid = $client['clientareaid'];
                
                $searchQuery .= " and ( 
                    notifications.target_type = 'all'
                    OR (notifications.target_type = 'branch' AND notifications.target_id = $branchid)
                    OR (notifications.target_type = 'government' AND notifications.target_id = $governorateid)
                    OR (notifications.target_type = 'city' AND notifications.target_id = $cityid)
                    or  notificationsclients.client_id = $clientid ) ";
            }
          


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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT DISTINCT $this->selectColumns,  IF(notifications.client_ids = 0, 1, IFNULL(notificationsclients.is_read, 0)) as `read` FROM $this->pageTable $this->pageJoin WHERE  1   $this->selectWhere $searchQuery LIMIT ? OFFSET ?";

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

            // إجمالي السجلات
            $totalRecords = R::getCell("SELECT COUNT(DISTINCT notifications.id) FROM $this->pageTable $this->pageJoin  WHERE 1 $this->selectWhere $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 = ['title_ar','title_en','content_ar','content_en','type','is_active','target_type','target_id','branch_id','governorate_id','city_id','client_ids', 'image','user_id'];
            
            $fields = [
                'title_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'title_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'content_ar' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'content_en' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'type' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'target_type' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'target_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'branch_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'governorate_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],'city_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'client_ids' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'is_active' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                '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::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/notifications/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'notifications') !== false) {
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                $image_name = $url_array[$count_url_array - 1];
            }
            
            if ($request['city_id']) {
                $target_type = 'city';
                $target_id = $request['city_id'];
            }else if($request['governorate_id']){
               $target_type = 'government';
               $target_id = $request['governorate_id']; 
            }else if($request['branch_id']){
               $target_type = 'branch';
               $target_id = $request['branch_id']; 
            }else if($request['client_ids']){
               $target_type = 'clients';
               $target_id = 0; 
            }else{
               $target_type = 'all';
               $target_id = 0; 
            }
    
    
            
            $rdispense = R::dispense("$this->pageTable");
            $rdispense->title_ar = $request['title_ar'];
            $rdispense->title_en = $request['title_en'];
            $rdispense->content_ar = $request['content_ar'];
            $rdispense->content_en = $request['content_en'];
            $rdispense->type = $request['type'];
            $rdispense->image = $image_name;
            $rdispense->target_type = $target_type;
            $rdispense->target_id = $target_id;
            $rdispense->is_active = $is_active;
            $rdispense->sys_date = date("Y-m-d H:i:s");
            $rdispense->user_id = $request['user_id'];
            $rdispense->is_del = 0;
            $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']]);
            $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_ar','title_en','content_ar','content_en','type','is_active','target_type','target_id','branch_id','governorate_id','city_id','client_ids', 'image','user_id'];
            
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                  'title_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'title_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'content_ar' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'content_en' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                 'type' => [
                    'rules' => 'required|text',
                    'type'  => 'string',
                ],
                'target_type' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'target_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'branch_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'governorate_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],'city_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'client_ids' => [
                    'rules' => 'text|min:1|max:255',
                    'type'  => 'string',
                ],
                'user_id' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'is_active' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                    'default' => 0
                ],
                '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/notifications/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'notifications') !== 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->title_ar = $request['title_ar'];
            $rupdate->title_en = $request['title_en'];
            $rupdate->content_ar = $request['content_ar'];
            $rupdate->content_en = $request['content_en'];
            $rupdate->type = $request['type'];
            $rupdate->image = $image_name;
            $rupdate->target_type = $target_type;
            $rupdate->target_id = $target_id;
            $rupdate->is_active = $is_active;
            $rupdate->sys_date = date("Y-m-d H:i:s");
            $rupdate->user_id = $request['user_id'];
            $rupdate->is_del = 0;
            $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']);
            $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(), []);
        }
    }
    
    
    function updateRead() {
        
        try{
            $this->getrequest->id = (!empty($this->getrequest->id)) ? (int) $this->getrequest->id : 0; 
            $allowed = ['clientid','id'];
            $fields = [
                'clientid' => [
                    'rules' => 'integer|min:1',
                    '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) {
                R::exec("UPDATE notificationsclients SET is_read = 1 WHERE notification_id = ?", [$request['id']]);
                $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],[]);
            }
 
            R::exec("UPDATE notificationsclients SET is_read = 1 WHERE client_id = ?", [$request['clientid']]);
            $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],[]);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
        
    }


  

    public function __destruct() {
        parent::__destruct();
    }

}
require_once("_master/fireApi.php");

