<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
require_once '_helper/ProductHelper.php';
class pageClass extends apiHandler
{
    private $apiName;
    private $pageTable;
    private $pageTableId;
    private $pageJoin;
    private $selectColumns;
    private $selectWhere;
    private $searchColumns;
    private $tarnsSelect;
    private $checkFoundBefore;
    private $renameFields;
    private $blockedFields;
    private $pathUrl;
    public function __construct() {
        parent::__construct(); 
        // $this->checkERPAccess();
        // $checkTokenClient = $this->checkTokenClient();
        $this->getrequest->clientid = 219;
        $this->pathUrl =  $this->hosturl . '/views/default/images/product_image/';
        $this->apiName = 'wishlists';
        $this->pageTable = 'wishlist';
        $this->pageTableId = 'wishlist.id';
        $this->pageJoin = ' left join product on product.productId = wishlist.productid left join onlineproductcat on onlineproductcat.id = product.productCatIdOnline ';
        $this->selectColumns = "wishlist.id as wishlist_id, wishlist.productid as id, wishlist.productid as product_id, CONCAT('$this->pathUrl', logo) as image, productSellUnitPrice as price, discount, discountRatio as discount_ratio, productCatIdOnline as category_id";
        $this->selectWhere = ' ';
        $this->searchColumns = ' (product.productName LIKE ? or product.productNameE LIKE ?) ';
        $this->tarnsSelect = ['ar'=>' , product.productName as name','en'=>', product.productNameE as name','lang_all'=>' , product.productName as name_ar , product.productNameE as name_en'];
        $this->checkFoundBefore = '(product.productName LIKE ? or product.productNameE LIKE ?)';
        $this->renameFields = ['productName' => 'name_ar', 'productNameE' => 'name_en', 'productCatIdOnline' => 'category_id'];
        $this->allowedFields = ['id','user_id','name_ar','name_en','shipping_cost','sys_date','user_creat_at','is_active','is_del'];
        $this->blockedFields = [];

    }
    
    
    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:10000',
                    '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) {
                $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 ?";
   

         
  
            $results   = R::getAll($sql, array($request['limit'], $offset));
            $productIds = array_column($results, 'product_id');
            $this->getrequest->product_ids = $productIds;
            $this->getrequest->to_array = 1;
            $productsFull = ProductHelper::products($this);
            $products = $this->customArrayObjectIndexOne($productsFull['products'], 'id');
            foreach ($results as $key => $res) {
                $results[$key]['product'] = $products[$res['product_id']];
            }
            
            
             
            // إجمالي السجلات
            $totalRecords = R::getCell("SELECT COUNT(*) FROM $this->pageTable WHERE 1 $searchQuery");

            if ($request['id'] > 0) {
                $response = $results;
            }else{
                $response = array(
                    "$this->apiName"  => $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'][$this->apiName]['clientIdNotExists']]);
            }
            
            
            if (helpers::valueNotExistsInTable('product', 'productId = ?', [$request['productid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['productid' => $this->trans['messages'][$this->apiName]['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("$this->pageTable", 'clientid = ? and productId = ?', [$request['clientid'], $request['productid']])) {
                $deleteWishlist = R::findOne("$this->pageTable", 'clientid = ? and productId = ?', [$request['clientid'],$request['productid']]);
                R::trash($deleteWishlist);
                $deleteWishlist['counts'] = R::getCell("SELECT COUNT(*) FROM $this->pageTable WHERE clientid = ?",[$request['clientid']]);
                $this->respond(200,true,$this->trans['messages'][$this->apiName]['deleteWishlist'], null,[],$deleteWishlist);
            }
            
            
            $rdispense = R::dispense("$this->pageTable");
            $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['counts'] = R::getCell("SELECT COUNT(*) FROM $this->pageTable WHERE clientid = ?",[$request['clientid']]);
            $response['wishlist'] = $fresponse;
            $this->respond(200,true,$this->trans['messages'][$this->apiName]['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'][$this->apiName]['clientIdNotExists']]);
            }
            
            
            if (helpers::valueNotExistsInTable('product', 'productId = ?', [$request['productid']])) {
                $this->respond(404,false,$this->trans['httpStatusCodes']['404'], null,['productid' => $this->trans['messages'][$this->apiName]['productIdNotExists']]);
            }
            
            $responses = R::find("$this->pageTable", 'clientid = ? or productId = ?', [$request['clientid'],$request['productid']]);
            if ($responses) {
                R::trashAll($responses);
            }
            $this->respond(200,true,$this->trans['messages'][$this->apiName]['deleteWishlist'], null,[]);
        }catch (Exception $exception){
            $this->respond(500,false,$this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
        
    }
    
    
     function deleteAllWishlist() {
        try{
            
            $allowed = ['clientid'];
            $fields = [
                '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'][$this->apiName]['clientIdNotExists']]);
            }
            
            
            
            $responses = R::findAll("$this->pageTable", 'clientid = ?', [$request['clientid']]);
            if ($responses) {
                R::trashAll($responses);
            }
            $this->respond(200,true,$this->trans['messages'][$this->apiName]['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");
