<?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();
        $this->pathUrl =  $this->hosturl.'/upload/coupons/';
        $this->apiName = 'coupons';
        $this->pageTable = 'coupons';
        $this->pageTableId = 'coupons.id';
        $this->pageJoin = ' left join user on coupons.user_id = user.userid  ';
        $this->selectWhere = ' and coupons.del = 0 and coupons.is_active = 1 ';
        $this->selectColumns = "coupons.id as id, CONCAT('$this->pathUrl', image) as image, coupons.code, coupons.discount_type, coupons.discount_value, coupons.start_date, coupons.end_date, DAY(end_date) AS day_number, MONTHNAME(end_date) AS month_name, coupons.usage_limit, coupons.per_user_limit
        , coupons.minimum_order_value, coupons.applicable_categories, coupons.auto_apply, coupons.note, coupons.is_active, coupons.del as is_del, coupons.created_at, coupons.user_id, employeename as user_creat_at ";
        $this->searchColumns = '(coupons.code LIKE ?)';
        $this->tarnsSelect = ['ar'=>' , title_ar as title','en'=>' , title_en as title', 'lang_all'=>' , title_ar, title_en '];
        $this->checkFoundBefore = '(coupons.code LIKE ?)';
        $this->renameFields = ['del' => 'is_del'];
        $this->allowedFields = ['id','code','title_ar','title_en','day_number','month_name','discount_type','discount_value','start_date','end_date','usage_limit','per_user_limit','minimum_order_value','applicable_categories','auto_apply','note','is_del','is_active','created_at','user_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) : ''; 

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

            $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'];
            // }
            
            // if ($request['branch_id'] > 0) {
            //     $searchQuery .= " AND $this->pageTable.branch_id = ". $request['branch_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 $this->selectWhere 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->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',
                'code',
                'discount_type',
                'discount_value',
                'start_date',
                'end_date',
                'is_active',
                'usage_limit',
                'per_user_limit',
                'minimum_order_value',
                'applicable_categories',
                'auto_apply',
                'note',
                'user_id',
                'image'
            ];

            $fields = [
                'title_ar' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'title_en' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'code' => [
                    'rules' => 'required|text|min:1|max:50',
                    'type'  => 'string',
                ],
                'discount_type' => [
                    'rules' => 'required|integer|min:0',
                    'type'  => 'integer',
                ],
                'discount_value' => [
                    'rules' => 'required|numeric|min:0',
                    'type'  => 'float',
                ],
                'start_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'end_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'is_active' => [
                    'rules' => 'integer|in:0,1',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'usage_limit' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'per_user_limit' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'minimum_order_value' => [
                    'rules' => 'numeric',
                    'type'  => 'float',
                ],
                'applicable_categories' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'auto_apply' => [
                    'rules' => 'integer|in:0,1',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'note' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                 'user_id' => [
                    '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['code']])) {
              $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/coupons/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'coupons') !== false) {
                $url_array = explode('/', $image_name);
                $count_url_array = count($url_array);
                $image_name = $url_array[$count_url_array - 1];
            }
            
            $rdispense = R::dispense("$this->pageTable");
            $rdispense->title_ar = $request['title_ar'];
            $rdispense->title_en = $request['title_en'];
            $rdispense->code = $request['code'];
            $rdispense->discount_type = $request['discount_type'];
            $rdispense->discount_value = $request['discount_value'];
            $rdispense->start_date = $request['start_date'];
            $rdispense->end_date = $request['end_date'];
            $rdispense->is_active = $request['is_active'];
            $rdispense->usage_limit = $request['usage_limit'];
            $rdispense->per_user_limit = $request['per_user_limit'];
            $rdispense->minimum_order_value = $request['minimum_order_value'];
            $rdispense->applicable_categories = $request['applicable_categories'];
            $rdispense->auto_apply = $request['auto_apply'];
            $rdispense->image = $image_name;
            $rdispense->note = $request['note'];
            $rdispense->user_id =  $request['user_id'];
            $rdispense->created_at = date('Y-m-d H:i:s');
            $rdispense->updated_at = date('Y-m-d H:i:s');
            $rdispense->del = 0;
            $id = R::store($rdispense);
            $user = helpers::getRowTable("user", "userid = ?", [$request['user_id']]);
            $rdispense->user_creat_at = $user['employeename'];
            $unixtime = strtotime($request['end_date']);
            $rdispense->month_name = date('F', $unixtime); //month
            $rdispense->day_number = date('d', $unixtime); 
            // $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',
                'code',
                'discount_type',
                'discount_value',
                'start_date',
                'end_date',
                'is_active',
                'usage_limit',
                'per_user_limit',
                'minimum_order_value',
                'applicable_categories',
                'auto_apply',
                'note',
                'user_id','image'];
            
            $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',
                ],
                'code' => [
                    'rules' => 'required|text|min:1|max:50',
                    'type'  => 'string',
                ],
                'discount_type' => [
                    'rules' => 'required|integer|min:0',
                    'type'  => 'integer',
                ],
                'discount_value' => [
                    'rules' => 'required|numeric|min:0',
                    'type'  => 'float',
                ],
                'start_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'end_date' => [
                    'rules' => 'required|date',
                    'type'  => 'string',
                ],
                'is_active' => [
                    'rules' => 'integer|in:0,1',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'usage_limit' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'per_user_limit' => [
                    'rules' => 'integer',
                    'type'  => 'integer',
                ],
                'minimum_order_value' => [
                    'rules' => 'numeric',
                    'type'  => 'float',
                ],
                'applicable_categories' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                'auto_apply' => [
                    'rules' => 'integer|in:0,1',
                    'type'  => 'integer',
                    'default' => 0
                ],
                'note' => [
                    'rules' => 'text',
                    'type'  => 'string',
                ],
                 'user_id' => [
                    '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['code'], $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/coupons/" . $url_array[$count_url_array - 1]);
                }
                $image_name = $url_array[$count_url_array - 1];
            }else if (strpos($image_name, 'coupons') !== 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->code = $request['code'];
            $rupdate->discount_type = $request['discount_type'];
            $rupdate->discount_value = $request['discount_value'];
            $rupdate->start_date = $request['start_date'];
            $rupdate->end_date = $request['end_date'];
            $rupdate->is_active = $request['is_active'];
            $rupdate->usage_limit = $request['usage_limit'];
            $rupdate->per_user_limit = $request['per_user_limit'];
            $rupdate->minimum_order_value = $request['minimum_order_value'];
            $rupdate->applicable_categories = $request['applicable_categories'];
            $rupdate->auto_apply = $request['auto_apply'];
            $rupdate->image = $image_name;
            $rupdate->note = $request['note'];
            $rupdate->user_id =  $request['user_id'];
            $rupdate->updated_at = date('Y-m-d H:i:s');
            $id = R::store($rupdate);
            $user = helpers::getRowTable("user", "userid = ?", [$rupdate['user_id']]);
            $rupdate->user_creat_at = $user['employeename'];
            $unixtime = strtotime($request['end_date']);
            $rupdate->month_name = date('F', $unixtime); //month
            $rupdate->day_number = date('d', $unixtime); 
            // $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']);
            $rdelete->is_active = 0;
            $rdelete->del = 2;
            $rdelete->deleted_at = date('Y-m-d H:i:s');
            $id = R::store($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 validate()
    {
        $couponCode = isset($this->getrequest->coupon_code) ? $this->getrequest->coupon_code : '';
        $coupon = R::findOne('coupons', 'code = ?', [$couponCode]);

        if (!$coupon) {
            $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['couponCode' => 'Coupon not found']);
        }

        if ($coupon->is_active == 0) {
            $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, ['couponCode' => 'Coupon is not active']);
        }

        $now = new DateTime();
        $startDate = new DateTime($coupon->start_date);
        $endDate = new DateTime($coupon->end_date);

        if ($now < $startDate || $now > $endDate) {
            $this->respond(400, false, $this->trans['httpStatusCodes']['400'], null, ['couponCode' => 'Coupon is not active']);
        }

        $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], ['couponCode' => 'Coupon is valid']);
    }
    
        
    
    
    
   
}

require_once("_master/fireApi.php");
