<?php
require_once '_master/apiHandler.php'; // الكلاس الأساسي
require_once '_helper/ProductHelper.php';
//To Be Continued fatma
//dailyentryfun , affect plugins will be redbeans , add daily entry of add
//require_once '../dailyentryfun.php';
class pageClass extends apiHandler
{
    public function __construct()
    {
        parent::__construct();
        $this->checkERPAccess();
        if($this->accessToken){
            $checkTokenClient = $this->checkTokenClient();
            $this->getrequest->clientid = isset($checkTokenClient->clientid) ? (int)$checkTokenClient->clientid : 0;
        }
    }


    public function index()
    {
        if (isset($this->getrequest->id) && $this->getrequest->id > 0) {
            $this->details();
            exit();
        }

       

        try {
            // القيم الافتراضية
            $req = $this->getrequest;
            $req->page = (!empty($req->page)) ? (int) $req->page : 1;
            $req->limit = (!empty($req->limit)) ? (int) $req->limit : 21;
            $req->category_id = isset($req->category_id) ? (int)$req->category_id : '';
            $req->priceFrom = isset($req->priceFrom) ? (int)$req->priceFrom : '';
            $req->priceTo = isset($req->priceTo) ? (int)$req->priceTo : '';
            $req->searchName = isset($req->searchName) ? trim($req->searchName) : '';
            $req->branch_id = isset($req->branch_id) ? (int)$req->branch_id : 1;
            $req->store_id = isset($req->store_id) ? (int)$req->store_id : 1;
            $req->manufacturer_id = isset($req->manufacturer_id) ? (int)$req->manufacturer_id : 0;
            $req->tag_id = isset($req->tag_id) ? (int)$req->tag_id : 0;
            $req->is_available = isset($req->is_available) ? (int)$req->is_available : 1;
            $req->is_sort = isset($req->is_sort) ? trim($req->is_sort) : '';
            $req->is_order = isset($req->is_order) ? trim($req->is_order) : '';

            // ترتيب النتائج
            switch ($req->is_sort) {
                case 'newest':
                    $req->is_sort = 'productId';
                    $req->is_order = 'desc';
                    break;
                case 'oldest':
                    $req->is_sort = 'productId';
                    $req->is_order = 'asc';
                    break;
                case 'price_low':
                    $req->is_sort = 'productSellUnitPrice';
                    $req->is_order = 'asc';
                    break;
                case 'price_high':
                    $req->is_sort = 'productSellUnitPrice';
                    $req->is_order = 'desc';
                    break;
            }

            $allowed = array('page','limit','category_id','priceFrom','priceTo','searchName','branch_id','store_id','manufacturer_id','tag_id','is_available','sort','order');
            $fields = array(
                'page' => array('rules'=>'required|integer','type'=>'integer'),
                'limit'=> array('rules'=>'required|integer|max:100','type'=>'integer'),
                'category_id'=>array('rules'=>'integer','type'=>'integer'),
                'priceFrom'=>array('rules'=>'integer','type'=>'integer'),
                'priceTo'=>array('rules'=>'integer','type'=>'integer'),
                'searchName'=>array('rules'=>'text|min:1|max:100','type'=>'string'),
                'branch_id'=>array('rules'=>'integer','type'=>'integer'),
                'store_id'=>array('rules'=>'integer','type'=>'integer'),
                'manufacturer_id'=>array('rules'=>'integer','type'=>'integer'),
                'tag_id'=>array('rules'=>'integer','type'=>'integer'),
                'is_available'=>array('rules'=>'integer|in:0,1','type'=>'integer'),
                'is_sort'=>array('rules'=>'text|in:productId,productName,productSellUnitPrice','type'=>'string'),
                'is_order'=>array('rules'=>'text|in:asc,desc','type'=>'string')
            );

            $request = $this->cleanRequestInputs((array)$req, $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/';
            $srcCat = $this->hosturl . '/views/default/images/category_image/';
            $srcCompany = $this->hosturl . '/views/default/images/company_image/';
            $srcBranch = $this->hosturl . '/views/default/images/branch_image/';

            if ($this->lang == 'ar') {
                $select = 'productName as name, productDescription as description';
                $selectCategory = 'title as name';
                $selectCompany = 'companyname as name';
                $selectstore = 'store.storeName AS name';
                $selectsearchfilters = 'name_ar as name';
            } else {
                $select = 'productNameE as name, productDescriptionE as description';
                $selectCategory = 'titleEn as name';
                $selectCompany = 'name_en as name';
                $selectstore = 'store.nameEn AS name';
                $selectsearchfilters = 'name_ar as name';
            }

          
            $offset = ($request['page'] - 1) * $request['limit'];
            $searchQuery = '';

            if (!empty($request['category_id'])) {
                if (helpers::valueNotExistsInTable('onlineproductcat', 'id = ?', array($request['category_id']))) {
                    $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, array('category_id'=>'Category not exists'));
                }
                $subs = $this->getAllSubCategories($request['category_id']);
                $idsString = $request['category_id'] . ',' . implode(',', $subs);
                $idsString = trim($idsString, ',');
                $searchQuery .= " AND product.productCatIdOnline IN ($idsString)";
            }

            if (!empty($request['priceFrom'])) {
                $searchQuery .= " AND product.productSellUnitPrice >= " . intval($request['priceFrom']);
            }
            if (!empty($request['priceTo'])) {
                $searchQuery .= " AND product.productSellUnitPrice <= " . intval($request['priceTo']);
            }

            if (!empty($request['searchName'])) {
                $ids = R::getCol('SELECT productId FROM product WHERE conditions = 0 AND (productName LIKE ? OR productNameE LIKE ?)', array('%'.$request['searchName'].'%', '%'.$request['searchName'].'%'));
                if (!empty($ids)) {
                    $searchQuery .= " AND productId IN (" . implode(',', $ids) . ")";
                }
            }

            if (!empty($request['manufacturer_id'])) {
                $searchQuery .= " AND product.company = " . intval($request['manufacturer_id']);
            }

            if (!empty($request['tag_id'])) {
                $searchQuery .= " AND product.tagids LIKE '%" . intval($request['tag_id']) . "%'";
            }

            $orderBy = '';
            if (!empty($request['is_sort']) && !empty($request['is_order'])) {
                $orderBy = " ORDER BY " . $request['is_sort'] . " " . strtoupper($request['is_order']);
            }

            $sql = " SELECT product.productId, productSellUnitPrice, $select, logo, logo1, logo2, logo3, logo4, logo5, logo6, logo7, tagids, productCatIdOnline as category_id, 
            discount, discountRatio, expireDate, company FROM product WHERE conditions = 0 $searchQuery $orderBy LIMIT ? OFFSET ? ";
            $results = R::getAll($sql, array($request['limit'], $offset));

            $searchQueryStore = "";
            $branchStoreIds = '';
            if ($request['store_id']) {
                $searchQueryStore .= " AND storedetail.storeid = " . $request['store_id'];
            } else if ($request['branch_id']) {
                $storeIds = R::getCol('SELECT storeId FROM store WHERE branchId = ?', [$request['branch_id']]);
                if (!empty($storeIds)) {
                    $searchQueryStore .= ' AND storedetail.storeid IN (' . implode(',', $storeIds) . ')';
                }
            }

            if (isset($request['is_available']) && $request['is_available'] == 1) {
                $searchQueryStore .= " AND productquantity > 0 ";
            }

            $storedetailData = R::getAll("SELECT storedetail.*, $selectstore
            FROM storedetail join store on storedetail.storeid = store.storeId 
            WHERE 1 " . $searchQueryStore);
            $storedetailData = $this->customArrayIndexMany($storedetailData, 'productid');

            //get company and tag
            list($companyIDs, $tagIDs) = [[], []];
            foreach ($results as $value) {
                $companyIDs[] = $value['company'];
                if (isset($value['tagids']) && $value['tagids'] != '') {
                    $tagIDs = array_merge($tagIDs, explode(',', $value['tagids']));
                }
            }
            $companyIDs = !empty($companyIDs) ? array_unique($companyIDs) : [0];
            $tagIDs = !empty($tagIDs) ? array_unique($tagIDs) : [0];

            $companies = R::getAll("SELECT id, $selectCompany FROM companyproduces WHERE id in ('" . implode("', '", $companyIDs) . "')");
            $companies = $this->customArrayIndexOne($companies,'id');

            $tags = R::getAll("SELECT id, $selectsearchfilters FROM searchfilters WHERE id in ('" . implode("', '", $tagIDs) . "')");
            $tags = $this->customArrayIndexOne($tags, 'id');

            $onlineproductcats = R::getAll("SELECT id, $selectCategory FROM onlineproductcat WHERE isdel = 0");
            $onlineproductcats = $this->customArrayIndexOne($onlineproductcats, 'id');

            $resultsToRet = array();
            foreach ($results as $result) {
                $rowData = new stdClass();
                $rowData->id = $result['productId'];
                $rowData->name = $result['name'];
                $rowData->description = $result['description'];
                $rowData->price = $result['productSellUnitPrice'];
                $rowData->discount = $result['discount'];
                $rowData->discount_ratio = $result['discountRatio'];
                $rowData->expire_date = "2025-08-17";
                $rowData->image = $this->hosturl . '/views/default/images/product_image/' . $result['logo'];
                $rowData->images = array();
                for ($i = 0; $i <= 7; $i++) {
                    $logo = 'logo';
                    if ($i > 0)
                        $logo .= $i;
                    $proImg = $this->hosturl . '/views/default/images/product_image/' . $result[$logo];
                    if (!empty($result[$logo]) && file_exists($proImg)) {
                        $rowData->images[] = $proImg;
                    }
                }
                //onlineproductcats
                $rowData->category = (isset($result['category_id']) && $result['category_id'] > 0) ? $onlineproductcats[$result['category_id']] : null;
                // add manufacturer
                $rowData->manufacturer = (isset($result['company']) && $result['company'] > 0) ? $companies[$result['company']] : null;

                $rowData->is_favorite = (
                    !empty($this->getrequest->clientid)
                    && R::count('wishlist', 'productid = ? AND clientid = ?', [$result['productId'], $this->getrequest->clientid]) > 0
                );

                //add tags
                $tags_Arr = array();
                if (!empty($result['tagids'])) {
                    foreach (explode(',', $result['tagids']) as $tagid) {
                        $tags_Arr[] = $tags[$tagid];
                    }
                }
                $rowData->tags = $tags_Arr;
                
                $rowData->is_available = 0;
                $rowData->total_amount = '';
                $rowData->store_stock = [];
                $store_stock_Arr = array();
                if (isset($storedetailData[$result['productId']])) {
                    foreach ($storedetailData[$result['productId']] as $storedetail) {
                        if ($request['store_id'] > 0 && $request['store_id'] == $storedetail['storeid']) {
                            $store_stock_Arr[] = [
                                'store_id' => $storedetail['storeid'],
                                'name' => $storedetail['name'],
                                'amount' => $storedetail['productquantity'],
                            ];
                        } else if ($request['branch_id'] > 0 && !empty($branchStoreIds) &&  in_array($storedetail['storeid'], explode(',', $branchStoreIds))) {
                            $store_stock_Arr[] = [
                                'store_id' => $storedetail['storeid'],
                                'name' => $storedetail['name'],
                                'amount' => $storedetail['productquantity'],
                            ];
                        } elseif ($request['store_id'] < 1 && $request['branch_id'] < 1) {
                            $store_stock_Arr[] = [
                                'store_id' => $storedetail['storeid'],
                                'name' => $storedetail['name'],
                                'amount' => $storedetail['productquantity'],
                            ];
                        }
                    }
                    if (count($store_stock_Arr) > 0) {
                        $rowData->is_available = 1;
                        $rowData->total_amount = array_sum(array_column($store_stock_Arr, 'amount')); //total quantity
                    }
                    $rowData->store_stock = $store_stock_Arr;
                } 
                
                ## push to resultsToRet
                if ($request['is_available'] == 1 && !empty($rowData->store_stock)) {
                    $resultsToRet[] = $rowData;
                } else if ($request['is_available'] == 0) {
                    $resultsToRet[] = $rowData;
                }
            }
            $results = $resultsToRet;


            // إجمالي السجلات
            $totalRecords = R::getCell('SELECT COUNT(*) FROM product WHERE conditions=0 ' . $searchQuery);//count($results);
            // إخراج البيانات
            $response = array(
                "products"  => $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 index()
    // {
    //     if (isset($_REQUEST['id']) && $_REQUEST['id'] > 0) {
    //         $this->details();
    //         exit();
    //     }
    //     //
    //     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->category_id  = isset($this->getrequest->category_id) ? (int) $this->getrequest->category_id :  '';
    //         $this->getrequest->priceFrom  = isset($this->getrequest->priceFrom) ? (int) $this->getrequest->priceFrom : '';
    //         $this->getrequest->priceTo  = isset($this->getrequest->priceTo) ? (int) $this->getrequest->priceTo : '';
    //         $this->getrequest->searchName = isset($this->getrequest->searchName) ? trim($this->getrequest->searchName) : '';
    //         $this->getrequest->branch_id  = isset($this->getrequest->branch_id) ? (int) $this->getrequest->branch_id : 1;
    //         $this->getrequest->store_id  = isset($this->getrequest->store_id) ? (int) $this->getrequest->store_id : 1;
    //         $this->getrequest->manufacturer_id  = isset($this->getrequest->manufacturer_id) ? (int) $this->getrequest->manufacturer_id : 0;
    //         $this->getrequest->tag_id  = isset($this->getrequest->tag_id) ? (int) $this->getrequest->tag_id : 0;
    //         $this->getrequest->is_available  = isset($this->getrequest->is_available) ? (int) $this->getrequest->is_available : 1;
    //         $this->getrequest->sort  = isset($this->getrequest->sort) ? trim($this->getrequest->sort) : ''; //newest, oldest, price_low, price_high //productId , productName
    //         $this->getrequest->order  = isset($this->getrequest->order) ? trim($this->getrequest->order) : ''; //asc , desc  
    //         switch ($this->getrequest->sort) {
    //             case 'newest':
    //                 $this->getrequest->sort = 'productId';
    //                 $this->getrequest->order = 'desc';
    //                 break;
    //             case 'oldest':
    //                 $this->getrequest->sort = 'productId';
    //                 $this->getrequest->order = 'asc';
    //                 break;
    //             case 'price_low':
    //                 $this->getrequest->sort = 'productSellUnitPrice';
    //                 $this->getrequest->order = 'asc';
    //                 break;
    //             case 'price_high':
    //                 $this->getrequest->sort = 'productSellUnitPrice';
    //                 $this->getrequest->order = 'desc';
    //                 break;
    //         }

    //         $allowed = ['page', 'limit', 'category_id', 'priceFrom', 'priceTo', 'searchName', 'branch_id', 'store_id', 'manufacturer_id', 'tag_id', 'is_available', 'sort', 'order'];
    //         $fields = [
    //             'page' => [
    //                 'rules' => 'required|integer|min:1',
    //                 'type'  => 'integer',
    //             ],
    //             'limit' => [
    //                 'rules' => 'required|integer|min:1|max:100',
    //                 'type'  => 'integer',
    //             ],
    //             'category_id' => [
    //                 'rules' => 'integer',
    //                 'type'  => 'integer',
    //             ],
    //             'priceFrom' => [
    //                 'rules' => 'integer',
    //                 'type'  => 'integer',
    //             ],
    //             'priceTo' => [
    //                 'rules' => 'integer',
    //                 'type'  => 'integer',
    //             ],
    //             'searchName' => [
    //                 'rules' => 'text|min:1|max:100',
    //                 'type'  => 'string',
    //             ],
    //             'branch_id' => [
    //                 'rules' => 'integer',
    //                 'type'  => 'integer',
    //             ],
    //             'store_id' => [
    //                 'rules' => 'integer',
    //                 'type'  => 'integer',
    //             ],
    //             'manufacturer_id' => [
    //                 'rules' => 'integer',
    //                 'type'  => 'integer',
    //             ],
    //             'tag_id' => [
    //                 'rules' => 'integer',
    //                 'type'  => 'integer',
    //             ],
    //             'is_available' => [
    //                 'rules' => 'integer|in:0,1',
    //                 'type'  => 'integer',
    //             ],
    //             'sort' => [
    //                 'rules' => 'text|in:productId,productName,productSellUnitPrice', //newest,oldest,price_low,price_high',
    //                 'type'  => 'string',
    //             ],
    //             'order' => [
    //                 'rules' => 'text|in:asc,desc',
    //                 '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']);




    //         $src = $this->hosturl . '/views/default/images/product_image/';
    //         if ($this->lang == 'ar') {
    //             $select = 'productName as name, productDescription as description';
    //             $selectcategory = 'title as name';
    //         } else {
    //             $select = 'productNameE as name, productDescriptionE as description';
    //             $selectcategory = 'titleEn as name';
    //         }
    //         // $select = 'productName as name_ar, productDescription as description_ar,productNameE as name_en, productDescriptionE as description_en';
    //         // $selectcategory = 'title as name_ar,titleEn as name_en';

    //         $offset = ($request['page'] > 0 ? $request['page'] - 1 : 0) * $request['limit'];
    //         $searchQuery = "";
    //         if ($request['category_id']) {
    //             if (helpers::valueNotExistsInTable('onlineproductcat', 'id = ?', [$request['category_id']])) {
    //                 $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['category_id' => $this->trans['messages']['products']['categoryIdNotExists']]);
    //             }
    //             $getAllSubCategories =  $this->getAllSubCategories($request['category_id']);
    //             $idsString = $request['category_id'] . ',' . implode(',', $getAllSubCategories);
    //             $idsString = trim($idsString, ',');
    //             $searchQuery .= " AND product.productCatIdOnline in ($idsString)";
    //         }

    //         if ($request['priceFrom']) {
    //             $searchQuery .= " AND product.productSellUnitPrice >= " . $request['priceFrom'];
    //         }

    //         if ($request['priceTo']) {
    //             $searchQuery .= " AND product.productSellUnitPrice <= " . $request['priceTo'];
    //         }


    //         if ($request['searchName']) {
    //             $ids = R::getCol('SELECT productId FROM product WHERE conditions = 0 AND (productName LIKE ? OR productNameE LIKE ?)', ['%' . $request['searchName'] . '%', '%' . $request['searchName'] . '%']);
    //             $idList = implode(",", $ids);
    //             $searchQuery .= " AND productId in ('$idList')";
    //         }

    //         // Add new search parameters to query            
    //         if ($request['manufacturer_id']) {
    //             $searchQuery .= " AND product.company = " . $request['manufacturer_id'];
    //         }

    //         if ($request['tag_id']) {
    //             $searchQuery .= " AND product.tagids like '%" . $request['tag_id'] . "%'";
    //         }

    //         // Add sorting
    //         $orderBy = '';
    //         if ($request['sort'] && !empty($request['order'])) {
    //             $orderBy = " ORDER BY " . $request['sort'] . " " . (strtolower($request['order']) === 'desc' ? 'DESC' : 'ASC');
    //         }

    //         // Use parameterized query for security
    //         $sql = "SELECT product.productId, productSellUnitPrice, $select, logo,logo1,logo2,logo3,logo4,logo5,logo6,logo7, tagids,productCatIdOnline as category_id 
    //         ,discount,discountRatio,expireDate,company
    //                FROM product 
    //                WHERE conditions = 0 $searchQuery 
    //                $orderBy 
    //                LIMIT ? OFFSET ?";

    //         $results = R::getAll($sql, array($request['limit'], $offset));
    //         // Check if the product is available in the store
    //         $searchQueryStore = "";
    //         $branchStoreIds = '';
    //         if ($request['store_id']) {
    //             $searchQueryStore .= " AND storedetail.storeid = " . $request['store_id'];
    //         } else if ($request['branch_id']) {
    //             $branchStores = R::getAll('select storeId from store where branchId = ?', [$request['branch_id']]);
    //             $branchStoreIds = array_column($branchStores, 'storeId');
    //             $branchStoreIds =  implode(",", $branchStoreIds);
    //             $searchQueryStore .= " AND storedetail.storeid in (" . $branchStoreIds . ")";
    //         }
    //         if (isset($request['is_available']) && $request['is_available'] == 1) {
    //             $searchQueryStore .= " AND productquantity > 0 ";
    //         }
    //         $storedetailData = R::getAll("SELECT storedetail.* , store.storeName, store.nameEn
    //         FROM storedetail join store on storedetail.storeid = store.storeId 
    //         WHERE 1 " . $searchQueryStore);
    //         $storedetailData = $this->customArrayIndexMany($storedetailData, 'productid');

    //         //get company and tag
    //         list($companyIDs, $tagIDs) = [[], []];
    //         foreach ($results as $value) {
    //             $companyIDs[] = $value['company'];
    //             if (isset($value['tagids']) && $value['tagids'] != '') {
    //                 $tagIDs = array_merge($tagIDs, explode(',', $value['tagids']));
    //             }
    //         }
    //         $companyIDs = !empty($companyIDs) ? array_unique($companyIDs) : [0];
    //         $tagIDs = !empty($tagIDs) ? array_unique($tagIDs) : [0];

    //         $companies = R::getAll("SELECT id,companyname as name_ar,name_en FROM companyproduces WHERE id in ('" . implode("', '", $companyIDs) . "')");
    //         $companies = $this->customArrayIndexOne($companies,'id');

    //         $tags = R::getAll("SELECT id,name as name_ar,name_en FROM searchfilters WHERE id in ('" . implode("', '", $tagIDs) . "')");
    //         $tags = $this->customArrayIndexOne($tags, 'id');

    //         $onlineproductcats = R::getAll("SELECT id, $selectcategory FROM onlineproductcat WHERE isdel = 0");
    //         $onlineproductcats = $this->customArrayIndexOne($onlineproductcats, 'id');

    //         $resultsToRet = array();
    //         foreach ($results as $result) {
    //             $rowData = new stdClass();
    //             $rowData->id = $result['productId'];
    //             $rowData->name_ar = $result['name_ar'];
    //             $rowData->name_en = $result['name_en'];
    //             $rowData->description_ar = $result['description_ar'];
    //             $rowData->description_en = $result['description_en'];
    //             $rowData->price = $result['productSellUnitPrice'];
    //             $rowData->discount = $result['discount'];
    //             $rowData->discount_ratio = $result['discountRatio'];
    //             $rowData->expire_date = $result['expireDate'];
    //             $rowData->images = array();
    //             for ($i = 0; $i <= 7; $i++) {
    //                 $logo = 'logo';
    //                 if ($i > 0)
    //                     $logo .= $i;
    //                 $proImg = $this->hosturl . '/views/default/images/product_image/' . $result[$logo];
    //                 if (!empty($result[$logo]) && file_exists($proImg)) {
    //                     $rowData->images[] = $proImg;
    //                 }
    //             }
    //             //onlineproductcats
    //             $rowData->category = (isset($result['category_id']) && $result['category_id'] > 0) ? $onlineproductcats[$result['category_id']] : null;
    //             // add manufacturer
    //             $rowData->manufacturer = (isset($result['company']) && $result['company'] > 0) ? $companies[$result['company']] : null;

    //             $rowData->is_favorite = false;
    //             if (isset($clientId) && $clientId > 0 && R::count("SELECT * FROM wishlist WHERE productid = ? and clientid = ?", [$result['productId'], $clientId]) > 0)
    //                 $rowData->is_favorite = true;

    //             //add tags
    //             $tags_Arr = array();
    //             if (!empty($result['tagids'])) {
    //                 foreach (explode(',', $result['tagids']) as $tagid) {
    //                     $tags_Arr[] = $tags[$tagid];
    //                 }
    //             }
    //             $rowData->tags = $tags_Arr;
                
    //             //check if product is available in store , if available add it to store_stock_Arr
    //             $rowData->is_available = 0;
    //             $rowData->total_amount = '';
    //             $rowData->store_stock = [];
    //             $store_stock_Arr = array();
    //             if (isset($storedetailData[$result['productId']])) {
    //                 foreach ($storedetailData[$result['productId']] as $storedetail) {
    //                     if ($request['store_id'] > 0 && $request['store_id'] == $storedetail['storeid']) {
    //                         $store_stock_Arr[] = [
    //                             'store_id' => $storedetail['storeid'],
    //                             'store_name_ar' => $storedetail['storeName'],
    //                             'store_name_en' => $storedetail['nameEn'],
    //                             'amount' => $storedetail['productquantity'],
    //                         ];
    //                     } else if ($request['branch_id'] > 0 && !empty($branchStoreIds) &&  in_array($storedetail['storeid'], explode(',', $branchStoreIds))) {
    //                         $store_stock_Arr[] = [
    //                             'store_id' => $storedetail['storeid'],
    //                             'store_name_ar' => $storedetail['storeName'],
    //                             'store_name_en' => $storedetail['nameEn'],
    //                             'amount' => $storedetail['productquantity'],
    //                         ];
    //                     } elseif ($request['store_id'] < 1 && $request['branch_id'] < 1) {
    //                         $store_stock_Arr[] = [
    //                             'store_id' => $storedetail['storeid'],
    //                             'store_name_ar' => $storedetail['storeName'],
    //                             'store_name_en' => $storedetail['nameEn'],
    //                             'amount' => $storedetail['productquantity'],
    //                         ];
    //                     }
    //                 }
    //                 if (count($store_stock_Arr) > 0) {
    //                     $rowData->is_available = 1;
    //                     $rowData->total_amount = array_sum(array_column($store_stock_Arr, 'amount')); //total quantity
    //                 }
    //                 $rowData->store_stock = $store_stock_Arr;
    //             } 
                
    //             ## push to resultsToRet
    //             if ($request['is_available'] == 1 && !empty($rowData->store_stock)) {
    //                 $resultsToRet[] = $rowData;
    //             } else if ($request['is_available'] == 0) {
    //                 $resultsToRet[] = $rowData;
    //             }
    //         }
    //         $results = $resultsToRet;


    //         // إجمالي السجلات
    //         $totalRecords = count($results); //R::getCell('SELECT COUNT(*) FROM product WHERE conditions=0 ' . $searchQuery);

    //         // إخراج البيانات
    //         $response = array(
    //             "products"  => $results,
    //             "pagination" => array(
    //                 "current_page"  => $request['page'],
    //                 "total_pages"  => ceil($totalRecords / $request['limit']),
    //                 "total_items"  => (int) $totalRecords,
    //                 "per_page"  => $request['limit'],
    //                 //"offset" => $offset,
    //             ),

    //         );
    //         $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
    //     } catch (Exception $exception) {
    //         $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
    //     }
    // }

    function details()
    {
        
        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('product', 'productId = ?', [$request['id']])) {
                $this->respond(404, false, $this->trans['httpStatusCodes']['404'], null, ['productId' => $this->trans['messages']['products']['productIdNotExists']]);
            }
            $src = $this->hosturl . '/views/default/images/product_image/';

            if ($this->lang == 'ar') {
                $select = 'productName as name, productDescription as description';
                $selectcategory = 'title as name';
                $selectCompany = 'companyname as name';
                $selectstore = 'store.storeName AS name';
                $selectsearchfilters = 'name_ar as name';
            } else {
                $select = 'productNameE as name, productDescriptionE as description';
                $selectcategory = 'titleEn as name';
                $selectCompany = 'name_en as name';
                $selectstore = 'store.nameEn AS name';
                $selectsearchfilters = 'name_ar as name';
            }

            // $select = 'productName as name_ar, productDescription as description_ar,productNameE as name_en, productDescriptionE as description_en';
            // $selectcategory = 'title as name_ar,titleEn as name_en';
            $proData = R::getRow("SELECT product.productId, productSellUnitPrice, $select, logo,logo1,logo2,logo3,logo4,logo5,logo6,logo7, productCatIdOnline as category_id
            ,discount,discountRatio,expireDate,company
             FROM `product` WHERE productId = ?", [$request['id']]);
            $productsimages = R::getCell("SELECT CONCAT('$src', image) as image  FROM productsimages WHERE product_id = ? ", [$proData['productId']]);
            ## response
            $response = new stdClass();
            $response->id = $proData['productId'];
            $response->name = $proData['name'];
            $response->description = $proData['description'];
            $response->price = $proData['productSellUnitPrice'];
            $response->discount = $proData['discount'];
            $response->discount_ratio = $proData['discountRatio'];
            $response->expire_date = $proData['expireDate'];
            $response->image = $src . $proData['logo'];
            $response->images = array();
            for ($i = 0; $i <= 7; $i++) {
                $logo = 'logo';
                if ($i > 0)
                    $logo .= $i;
                $proImg = $src . $proData[$logo];
                if (!empty($proData[$logo]) && file_exists($proImg)) {
                    $response->images[] = $proImg;
                }
            }
            $response->images = $productsimages;
            $response->category = R::getRow("SELECT id, $selectcategory FROM onlineproductcat WHERE isdel = 0 and id = ?", [$proData['category_id']]);
            $response->manufacturer = R::getRow("SELECT id, $selectCompany FROM companyproduces WHERE del = 0 and id = ?", [$proData['company']]);
            $response->stock = R::getAll("SELECT storedetail.storeid as store_id, $selectstore ,storedetail.productquantity as amount
            FROM storedetail join store on storedetail.storeid = store.storeId 
            WHERE storedetail.productid = ?", [$proData['productId']]);
            $response->is_favorite = (
                    !empty($this->getrequest->clientid)
                    && R::count('wishlist', 'productid = ? AND clientid = ?', [$result['productId'], $this->getrequest->clientid]) > 0
            );
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $response);
        } catch (Exception $exception) {
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $exception->getMessage(), []);
        }
    }

    function getAllSubCategories($parentId)
    {
        $subcats = R::findAll('onlineproductcat', ' parentid = ? AND isdel = 0 ', [$parentId]);
        $ids = [];
        foreach ($subcats as $cat) {
            $ids[] = $cat->id;
            $ids = array_merge($ids, $this->getAllSubCategories($cat->id));
        }
        return $ids;
    }

    function add()
    {
        try {
            $allowed = ['productName', 'productNameE', 'productCatId', 'productCatIdERP', 'productBuyPrice', 'parcode', 'productSellAllPrice', 'productSellHalfPrice', 'productSellUnitPrice', 'productDescription', 'productDescriptionE', 'hasSizeAndColor', 'logo', 'limitamount'];
            $fields = [
                'productName' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'productNameE' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'productCatId' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'productCatIdERP' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);

            // Start transaction
            R::begin();

            // Create new product
            $product = R::dispense('product');

            // Set basic product info
            $product->productName = $request['productName'];
            $product->productNameE = $request['productNameE'];
            $product->productCatId = (int)$request['productCatIdERP'];
            $product->productCatIdOnline = (int)$request['productCatId'];
            $product->productDescription = $request['productDescription'];
            $product->productDescriptionE = $request['productDescriptionE'];

            $product->productBuyPrice = (float)$request['productBuyPrice'];
            $product->lastbuyprice = $product->productBuyPrice;
            $product->lastbuyprice_withDiscount = $product->productBuyPrice;
            $product->meanbuyprice = $product->productBuyPrice;
            $product->meanbuyprice_withDiscount = $product->productBuyPrice;
            $product->lastbuyprice_withTax = $product->productBuyPrice;
            $product->meanbuyprice_withTax = $product->productBuyPrice;
            $product->overAllAveragePrice = $product->productBuyPrice;
            $product->lastbuyprice_withDiscountAndTax = $product->productBuyPrice;
            $product->type = 0;
            $product->inMenu = 0;
            $product->isService = 0;
            $product->conditions = 0;
            $product->limitamount = (float)$request['limitamount'];

            $product->productSellAllPrice = (float)$request['productSellAllPrice'];
            $product->productSellHalfPrice = (float)$request['productSellHalfPrice'];
            $product->productSellUnitPrice = (float)$request['productSellUnitPrice'];
            $product->parcode = $request['parcode'];
            $product->expireDate = ''; //$request['expireDate'];
            $product->productDate = date('Y-m-d');
            $product->conditions = 0; // Active
            $product->userId = 1; // $this->user->id
            $product->dailyentryId = 0;
            $product->isService = 0; //(int) $request['isService'];
            $product->hasSizeAndColor = 0; //(int)$request['hasSizeAndColor'];
            $product->tagids = $request['tagids'];
            $product->logo = $request['logo'];

            // Save product
            $productId = R::store($product);

            // Generate barcode if not provided
            if (empty($product->parcode)) {
                $parcode = ProductHelper::addPreDigitsToNum($productId);

                ##check for barcode
                $flag = ProductHelper::checkbarcode($parcode);
                if ($flag == 1) {
                    //parcode is repeated get another one
                    $parcode = ProductHelper::generateParcode();
                }
                ProductHelper::removeParcodeFromTable($parcode);
                $product->parcode = $parcode;
                R::store($product);
            }

            // Add default unit if not provided
            $unit = R::dispense('productunit');
            $unit->productid = $productId;
            $unit->unitid = 1; // Default unit
            $unit->productnumber = 1;
            $unit->proUnitSellAllPrice = $product->productSellAllPrice;
            $unit->proUnitSellHalfPrice = $product->productSellHalfPrice;
            $unit->proUnitSellUnitPrice = $product->productSellUnitPrice;
            $unit->proUnitBuyPrice = $product->productBuyPrice;
            $unit->conditions = 0;
            $unit->productunitdate = date('Y-m-d H:i:s');
            $unit->userid = 1; // $this->user->id
            R::store($unit);


            //insert into storedetail tbl
            $storeDetail = R::dispense('storedetail');
            $storeDetail->productid = $productId;
            $storeDetail->productquantity = 0;
            $storeDetail->storedetaildate = date('Y-m-d');
            $storeDetail->storeid = 1;
            $storeDetail->userid = 1;

            R::store($storeDetail);

            if ($product->hasSizeAndColor != 1) { //منتج بمقاسات و الوان لا تضيف له سطر عام
                // Create store report entry using RedBeanPHP
                $storeReport = R::dispense('storereport');
                $storeReport->processname = "إضافة منتج";
                $storeReport->productafter = 0;
                $storeReport->productbefore = 0;
                $storeReport->productquantity = 0;
                $storeReport->storeid = 1;
                $storeReport->storereportdate = date('Y-m-d H:i:s');
                $storeReport->storereportmodelid = $productId;
                $storeReport->storereporttype = 0;
                $storeReport->tablename = "productController.php";
                $storeReport->userid =   1; // $this->user->id
                $storeReport->productid = $productId;

                // Save the store report
                $reportId = R::store($storeReport);
            }


            // Commit transaction
            R::commit();

            // Return success response
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $product);
        } catch (Exception $e) {
            // Rollback transaction on error
            // if (R::isInTransaction()) {
            R::rollback();
            //}

            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $e->getMessage());
        }
    }


    function update()
    {
        try {
            $allowed = ['id', 'productName', 'productNameE', 'productCatId', 'productCatIdERP', 'productBuyPrice', 'parcode', 'productSellAllPrice', 'productSellHalfPrice', 'productSellUnitPrice', 'productDescription', 'productDescriptionE', 'hasSizeAndColor', 'logo', 'limitamount'];
            $fields = [
                'id' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'productName' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'productNameE' => [
                    'rules' => 'required|text|min:1|max:255',
                    'type'  => 'string',
                ],
                'productCatId' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
                'productCatIdERP' => [
                    'rules' => 'required|integer|min:1',
                    'type'  => 'integer',
                ],
            ];

            $request = $this->cleanRequestInputs((array)$this->getrequest, $fields, $allowed);

            // Start transaction
            R::begin();

            // Load existing product
            $product = R::load('product', (int)$request['id']);
            if (!$product->productId) {
                throw new Exception('Product not found');
            }

            // Update product info
            $product->productName = $request['productName'];
            $product->productNameE = $request['productNameE'];
            $product->productCatId = (int)$request['productCatIdERP'];
            $product->productCatIdOnline = (int)$request['productCatId'];
            $product->productDescription = $request['productDescription'];
            $product->productDescriptionE = $request['productDescriptionE'];

            // Only update prices if provided
            if (isset($request['productBuyPrice'])) {
                $product->productBuyPrice = (float)$request['productBuyPrice'];
                // $product->lastbuyprice = $product->productBuyPrice;
                // $product->lastbuyprice_withDiscount = $product->productBuyPrice;
                // $product->meanbuyprice = $product->productBuyPrice;
                // $product->meanbuyprice_withDiscount = $product->productBuyPrice;
                // $product->lastbuyprice_withTax = $product->productBuyPrice;
                // $product->meanbuyprice_withTax = $product->productBuyPrice;
                // $product->overAllAveragePrice = $product->productBuyPrice;
                // $product->lastbuyprice_withDiscountAndTax = $product->productBuyPrice;
            }

            // Update other fields if provided
            if (isset($request['limitamount'])) $product->limitamount = (float)$request['limitamount'];
            if (isset($request['productSellAllPrice'])) $product->productSellAllPrice = (float)$request['productSellAllPrice'];
            if (isset($request['productSellHalfPrice'])) $product->productSellHalfPrice = (float)$request['productSellHalfPrice'];
            if (isset($request['productSellUnitPrice'])) $product->productSellUnitPrice = (float)$request['productSellUnitPrice'];
            if (isset($request['parcode'])) $product->parcode = $request['parcode'];
            if (isset($request['logo'])) $product->logo = $request['logo'];
            if (isset($request['hasSizeAndColor'])) $product->hasSizeAndColor = (int)$request['hasSizeAndColor'];
            if (isset($request['tagids'])) $product->tagids = $request['tagids'];

            // Save updated product
            R::store($product);

            // Commit transaction
            R::commit();

            // Return success response with updated product
            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], $product);
        } catch (Exception $e) {
            echo $e->getMessage();
            // Rollback transaction on error
            R::rollback();
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $e->getMessage());
        }
    }

    //tempdelete not final delete
    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, 'Validation Error', null, $request['validation_errors']);
            }

            // Start transaction
            R::begin();

            // Load the product
            $product = R::load('product', $request['id']);

            if (!$product->productId) {
                throw new Exception('Product not found');
            }

            // if ($productData->dailyentryId > 0) {
            //     $rid = reverseEntryWithItsID($productData->dailyentryId, 1);
            //     $productExt->updateDailyEntry($rid[1], $productId);
            // }
            R::exec('UPDATE product SET conditions =1 WHERE productId =' . $product->productId);

            // Commit transaction
            R::commit();

            $this->respond(200, true, $this->trans['httpStatusCodes']['200'], null, [], ['id' => $request['id']]);
        } catch (Exception $e) {
            // Rollback on error
            if (R::isInTransaction()) {
                R::rollback();
            }
            $this->respond(500, false, $this->trans['httpStatusCodes']['500'], $e->getMessage(), []);
        }
    }

    public function __destruct()
    {
        parent::__destruct();
    }
}
require_once("_master/fireApi.php");
