<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
class pageClass extends apiHandler
{   
    public function __construct() {
        parent::__construct(); 
        $this->checkERPAccess();
        $checkTokenClient = $this->checkTokenClient();
        $this->getrequest->clientid = $checkTokenClient->clientid;
    }
    
    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 : 10;
            $this->getrequest->id  = isset($this->getrequest->id) ? (int) $this->getrequest->id : 0;
            $allowed = ['clientid','page', 'limit','id'];
            $fields = [
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer'
                ],
                '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']);
            $src = $this->hosturl.'/upload/notifications/';
            if($this->lang == 'ar'){
                $select = 'notifications.title as title, notifications.content as content';
            }else{
                $select = 'notifications.titleEn as title, notifications.contentEn as content';
            }
            
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT notifications.id as id, $select , CONCAT('$src', image) as image, branch.branchName as branch_name, government.governmentname as governorate_name, clientarea.name as city_name, notifications.client_ids  FROM `notifications`
                left join branch on branch.branchId = notifications.branch_id
                left join government on government.governmetid = notifications.governorate_id
                left join clientarea on clientarea.id = notifications.city_id
                WHERE notifications.isdel = 0 and notifications.id = ? ",[$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);
            }


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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            
            $sql = "SELECT notifications.id as id, $select , CONCAT('$src', image) as image, branch.branchName as branch_name, government.governmentname as governorate_name, clientarea.name as city_name  FROM `notifications`
                left join branch on branch.branchId = notifications.branch_id
                left join government on government.governmetid = notifications.governorate_id
                left join clientarea on clientarea.id = notifications.city_id
                left join notificationsclients on notificationsclients.notification_id = notifications.id
                WHERE notifications.isdel = 0 and (notifications.client_ids = 0 or  notificationsclients.client_id = ? ) LIMIT ? OFFSET ?";
            $results   = R::getAll($sql, array($request['clientid'],$request['limit'], $offset));

            // إجمالي السجلات
            $totalRecords = R::getCell('SELECT COUNT(*) FROM notifications WHERE isdel=0 and clientid = ?',[$request['clientid']]);
            
            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "Notifications"  => $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(), []);
        }
        
    }
    

   
 

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

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