<?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 . '/views/default/images/product_image/';
            if ($this->lang == 'ar') {
                $select = 'productName as name, productSellUnitPrice as price, discount, discountRatio as discount_ratio';
            } else {
                $select = 'productNameE as name, productSellUnitPrice as price, discount, discountRatio as discount_ratio';
            }
            
            if ($request['id'] > 0) {
                $response = R::getRow("SELECT wishlist.id, $select, CONCAT('$src', logo) as image  FROM `wishlist`
                left join product on product.productId = wishlist.productid
                left join onlineproductcat on onlineproductcat.id = product.productCatIdOnline
                WHERE wishlist.id = ?",[$request['id']]);
                $this->respond(200,true,$this->trans['httpStatusCodes']['200'], null, [],$response);
            }


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

            // استخدام معاملات آمنة بدل دمج النصوص في SQL
            $sql = "SELECT wishlist.id, $select, CONCAT('$src', logo) as image  FROM `wishlist`
                left join product on product.productId = wishlist.productid
                left join onlineproductcat on onlineproductcat.id = product.productCatIdOnline
                WHERE wishlist.clientid = ? LIMIT ? OFFSET ?";
                
                
                

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

            // إجمالي السجلات
            $totalRecords = R::getCell('SELECT COUNT(*) FROM wishlist WHERE clientid = ?',[$request['clientid']]);
            
            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "wishlists"  => $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 = ['productid', 'clientid'];
            $fields = [
                'productid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    '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('client', 'clientid = ?', [$request['clientid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['clientid' => $this->trans['messages']['wishlist']['clientIdNotExists']]);
            }
            
            
            if (helpers::valueNotExistsInTable('product', 'productId = ?', [$request['productid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['productid' => $this->trans['messages']['wishlist']['productIdNotExists']]);
            }
            
            
            // if (helpers::valueExistsInTable('wishlist', 'clientid = ? and productId = ?', [$request['clientid'], $request['productid']])) {
            //     $this->respond(200,true,$this->trans['messages']['wishlist']['productIsFavourites'], null,[]);
            // }
            if (helpers::valueExistsInTable('wishlist', 'clientid = ? and productId = ?', [$request['clientid'], $request['productid']])) {
                $deleteWishlist = R::findOne('wishlist', 'clientid = ? or productId = ?', [$request['clientid'],$request['productid']]);
                R::trash($deleteWishlist);
                $this->respond(200,true,$this->trans['messages']['wishlist']['deleteWishlist'], null,[]);
            }
            
            
            $rdispense = R::dispense('wishlist');
            $rdispense->clientid = $request['clientid'];
            $rdispense->productid = $request['productid'];
            $rdispense->sysDate = date('Y-m-d');
            $id = R::store($rdispense);
            $fresponse = helpers::beanToStdClass($rdispense,[], [],['clientid' => 'client_id','productid' => 'product_id']);
            $response = [];
            $response['wishlist'] = $fresponse;
            $this->respond(200,true,$this->trans['messages']['wishlist']['200'], null, [],$response);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
        
    }
    
    function deleted() {
        try{
            
            $allowed = ['productid', 'clientid'];
            $fields = [
                'productid' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'clientid' => [
                    'rules' => 'required|integer|min:1',
                    '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('client', 'clientid = ?', [$request['clientid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['clientid' => $this->trans['messages']['wishlist']['clientIdNotExists']]);
            }
            
            
            if (helpers::valueNotExistsInTable('product', 'productId = ?', [$request['productid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['productid' => $this->trans['messages']['wishlist']['productIdNotExists']]);
            }
            
            $responses = R::find('wishlist', 'clientid = ? or productId = ?', [$request['clientid'],$request['productid']]);
            if ($responses) {
                R::trashAll($responses);
            }
            $this->respond(200,true,$this->trans['messages']['wishlist']['deleteWishlist'], null,[]);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
        
    }
 

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

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