<?php
require_once('Model/Queries.php');
require_once('Model/Constant.php');
require_once('Utility/Utility.php');
require_once('Object/DataObject.php');
require_once('Object/ResponseObject.php');
require_once('QueryBuilder/QueryDecorator.php');
require_once('QueryBuilder/CustomQuery.php');
require_once('../../config.php');

class StorePanel extends Constant implements Queries
{
    private $dtObject;
    private $actionType = "";
    private $functionalityType = "";
    public $postData = [];
    public $fileData;


    function __construct(DataObject $dtObject)
    {

        parent::__construct();
        $this->dtObject = $dtObject;
        $this->actionType = $dtObject->getActionType();
        $this->functionalityType = $dtObject->getFunctionalityType();
        $this->postData = $dtObject->getPostData();
        $this->fileData = $dtObject->getFileData();
        $this->getData = $dtObject->getGetData();
        $this->getRandom = $dtObject->getRandomId();




    }


    public function create()
    {
        $listOfData = [];
        $postdata = $this->postData;
        $file = $this->fileData;
        //Utility::DebugObject($postdata);

        if ($this->functionalityType == "insert_add_products") {
//            Utility::DebugObject($postdata);
            $random = $postdata['random-no'];
            $cat_id = isEmpty($postdata['cat-id']);
            $sub_cat_id = isEmpty($postdata['sub-cat-id']);
            $child_cat_id = isEmpty($postdata['child-cat-id']);
            $brand_id = isEmpty($postdata['brand_id']);
            $name = isEmpty($postdata['pro']);
            $description = $postdata['ckeditor'];
            $cover_image = $postdata['cover_image'];
            if (empty($cover_image)) {
                $image = null;

            } else {

                $image = convert_save_image_from_base64("ic_product_picture" . rand() . ".webp", $cover_image, $this->products_images);
            }

            $price = $postdata['propri'];
            $processing_time = $postdata['processing_time'];
            $weight = $postdata['proWeight'];
            $tags = $postdata['example'];
            $tags2 = explode(",", $tags);




            $shipping = $postdata['shipping'];


            $queryDecorator = new QueryDecorator("INSERT INTO product (category_id,sub_category_id,child_category_id,brand_id
            ,image,name,description,processing_time,price,weight) 
            VALUES ('$cat_id','$sub_cat_id','$child_cat_id','$brand_id','$image','$name','$description','$processing_time','$price','$weight')", new CustomQuery("0", ""));
//            Utility::Logger($queryDecorator->getQuery());
            $result = queryRunner($queryDecorator->getQuery());
            $last_id = findLastInsertId();
            if (is_array($tags2)) {

                foreach ($tags2 as $value) {
                    $queryDecorator = new QueryDecorator("INSERT INTO tags(product_id,name)VALUES('$last_id','$value')", new CustomQuery("0", ""));

                    $result = queryRunner($queryDecorator->getQuery());


                }
            }

            if (is_array($shipping)) {
//                Utility::Logger("hello yes this shipping array");

                foreach ($shipping as $value) {
                    $queryDecorator = new QueryDecorator("INSERT INTO ProductShipping(product_id,shipping_id)VALUES('$last_id','$value')", new CustomQuery("0", ""));

                    $result = queryRunner($queryDecorator->getQuery());
                }
            }
            $queryDecorator = new QueryDecorator("UPDATE ProductAttribute SET product_id ='$last_id'", new CustomQuery("0", " WHERE product_id = '$random'"));
//            Utility::Logger($queryDecorator->getQuery());
            $result = queryRunner($queryDecorator->getQuery());
            $queryDecorator = new QueryDecorator("UPDATE ProductPicture SET product_id ='$last_id'", new CustomQuery("0", " WHERE product_id = '$random'"));
            $result = queryRunner($queryDecorator->getQuery());
            if ($result != null) {
                session_start();
                header("location:../store_panel/list_of_products.php");

            }

            return $this->getResponseObject("202", "Data insert Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "insert_product_attribute") {
            $id = $postdata['id'];
            $name = $postdata['name'];
            $queryDecorator = new QueryDecorator("INSERT INTO ProductAttribute(product_id,name)VALUES('$id','$name')", new CustomQuery("0", ""));

            $result = queryRunner($queryDecorator->getQuery());
//            $last = findLastInsertId();
            /*array_push( $listOfData,
                ['last_id' =>  $last ]);*/
            return $this->getResponseObject($this->getSuccess_code(), "Data INSERT Successfully", findLastInsertId(), "0", $listOfData, '');

        }
        else if ($this->functionalityType == "insert_attributeitem") {
            $attr_id = $postdata['attr_id'];
            $name = $postdata['name'];
            $price = $postdata['price'];
            $image = $postdata['image'];
            if (empty($image)) {
                $attr_image = null;

            } else {

                $attr_image = convert_save_image_from_base64("ic_product_picture" . rand() . ".webp", $image, $this->products_images);
            }


            $queryDecorator = new QueryDecorator("INSERT INTO AttributeItem(attribute_id,name,price,image)VALUES('$attr_id','$name','$price','$attr_image')", new CustomQuery("0", ""));

            $result = queryRunner($queryDecorator->getQuery());
//            $last = findLastInsertId();
            /*array_push( $listOfData,
                ['last_id' =>  $last ]);*/
            return $this->getResponseObject($this->getSuccess_code(), "Data INSERT Successfully", findLastInsertId(), "0", $listOfData, '');

        }
        else if ($this->functionalityType == "insert_picture") {
            /*Utility::DebugObject("this is file Data:  " . count($file));
            Utility::DebugObject($file['file']);*/
            ////$getdata = $this->getRandom;
//            Utility::Logger("Random ID = "+$this->getRandom);


            $count=0;
            foreach ($_FILES['file']['name'] as $filename)
            {
                $temp="";
                $tmp=file_get_contents($_FILES['file']['tmp_name'][$count]);
//                Utility::Logger($tmp);
                $data = base64_encode($tmp);
                $image = convert_save_image_from_base64($filename . ".webp", $data, $this->products_images);
                $queryDecorator = new QueryDecorator("INSERT INTO ProductPicture(product_id,image)VALUES('$this->getRandom','$image')", new CustomQuery("0", ""));
//                Utility::Logger($queryDecorator->getQuery());
                $result = queryRunner($queryDecorator->getQuery());

                array_push($listOfData, [
                    'id' => findLastInsertId(),
                    'name' => $filename

                ]);


                $count=$count + 1;
                $temp=$temp.basename($filename);
//                Utility::Logger($temp);

                //move_uploaded_file($tmp,$temp);
                $temp='';
                $tmp='';

            }



            return $this->getResponseObject($this->getSuccess_code(), "Data INSERT Successfully", findLastInsertId(), "0", $listOfData, '');


        }


    }

    public function retrieve()
    {
        $listOfData = [];
        $postdata = $this->postData;
        if ($this->functionalityType == "retrieve_all_products") {

            $brand_id = $postdata['brand_id'];
            $search = $postdata['search'];

            $queryDecorator = new QueryDecorator("
            SELECT product.* ,IF(total_sales.sales IS NOT NULL, total_sales.sales , '0') as sales ,  total_rating.total_rating_count ,  IF(avg_rating.rating IS NOT NULL, avg_rating.rating , '0.0') as avg_ratings
                  FROM Product  as product 
                        
                  LEFT JOIN (
                     SELECT product_id as id , SUM(price) as sales FROM OrderMeta WHERE enable = '0'  GROUP BY product_id 
                  ) total_sales ON total_sales.id = product.id 
                 
                  LEFT JOIN (

                      SELECT product_id  , COUNT(*) as total_rating_count FROM Rating WHERE enable = '0' 
                      GROUP BY product_id

                    ) total_rating ON total_rating.product_id = product.id  
                    
                    LEFT JOIN (

                      SELECT product_id  , AVG(rating) as rating FROM Rating WHERE enable = '0' 
                        GROUP BY product_id

                    ) avg_rating ON avg_rating.product_id = product.id
                    
                    WHERE product.brand_id = '$brand_id'
                    
            
            ", new CustomQuery("0", ""));



            if (!empty($search)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", " AND product.name LIKE '$search%'"));

            }


            //<editor-fold desc="Total Data Counting functionality">

            $queryDecoratorCount = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("1", "SELECT count(*) as total_count ,"));
            $result = queryRunner($queryDecoratorCount->getQuery());
            $rowObject = rowRetrieverObject($result);
            $rowCount = $rowObject->total_count;
            if ($rowCount > 10) {
                $rowCount = ceil($rowCount / 10);
            }
            else{
                $rowCount = 1;
            }


            //</editor-fold>



            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("0", " LIMIT 10  "));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' => $row['name'],
                    'images' => $this->products_images . $row['image'],
                    'sales' => ceil($row['sales']),
                    'rating' => $row['avg_ratings'],
                    'enable' => $row['enable'],


                ]);
            }

            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData,Utility::getPaginationCssCode($rowCount));

        }
        else if ($this->functionalityType == "retrieve_child_categories") {
            $id = $postdata['category_id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM ChildSubCategories", new CustomQuery("0", " WHERE sub_category_id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' => $row['name'],


                ]);

            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "retrieve_sub_categories") {
            $id = $postdata['category_id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM SubCategories", new CustomQuery("0", " WHERE category_id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' => $row['name'],
                ]);

            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "retrieve_products_data") {
            $queryDecorator = new QueryDecorator("SELECT * FROM product", new CustomQuery("0", ""));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' => $row['name'],
                ]);

            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "retrieve_product_data_edit") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM Product", new CustomQuery("0", " WHERE id='$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'category_id' => $row['category_id'],
                    'sub_category_id' => $row['sub_category_id'],
                    'child_category_id' => $row['child_category_id'],
                    'brand_id' => $row['brand_id'],
                    'image' => $this->products_images.$row['image'],
                    'name' => $row['name'],
                    'description' => $row['description'],

//                    'start_date' => $this->gettimelocal($row['start_date']),
//                    'end_date' => $this->gettimelocal($row['end_date']),
                    'processing_time' => $row['processing_time'],
                    'price' => $row['price'],
                    'weight' => $row['weight'],
                    'enable' => $row['enable'],



                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "retrieve_tags_data_edit") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM tags", new CustomQuery("0", " WHERE product_id='$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' => $row['name'],




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "retrieve_sale_data_edit") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM Sale", new CustomQuery("0", " WHERE product_id='$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'sale_type' => $row['sale_type'],
                    'discount' => $row['discount'],
                    'start_date' => $this->gettimelocal($row['start_date']),
                    'end_date' => $this->gettimelocal($row['end_date']),




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "retrieve_shipping_data_edit") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM ProductShipping", new CustomQuery("0", " WHERE product_id='$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'shipping_id' => $row['shipping_id'],





                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "get_data_edit_picture") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM ProductPicture", new CustomQuery("0", " WHERE product_id='$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' =>$row['image'],
                    'image' =>$this->products_images.$row['image'],





                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "get_product_attribute") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM ProductAttribute", new CustomQuery("0", " WHERE product_id='$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' =>$row['name'],





                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "get_attributeitem") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM AttributeItem", new CustomQuery("0", " WHERE attribute_id='$id'"));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' =>$row['name'],
                    'price' =>$row['price'],
                    'image' =>$this->products_images.$row['image'],






                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "abc") {
            Utility::Logger("total ");
            $queryDecorator = new QueryDecorator("SELECT COUNT(*) as total_data FROM Coupon", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            $row = rowRetrieverArray($result);
            if ($row > 10) {
                $page = $row['total_data'] / 10;
            } else {
                $page = $row['total_data'];
            }

            Utility::Logger("total : " . $page);
            Utility::getPaginationCssCode($page);


        }
        else if ($this->functionalityType == "pagination") {

            $brand_id = $postdata['brand_id'];
            $search = $postdata['search'];
            $offset = $postdata['offset'];

            $queryDecorator = new QueryDecorator("
            SELECT product.* ,IF(total_sales.sales IS NOT NULL, total_sales.sales , '0') as sales ,  total_rating.total_rating_count ,  IF(avg_rating.rating IS NOT NULL, avg_rating.rating , '0.0') as avg_ratings
                  FROM product  as product 
                        
                  LEFT JOIN (
                     SELECT product_id as id , SUM(price) as sales FROM OrderMeta WHERE enable = '0'  GROUP BY product_id 
                  ) total_sales ON total_sales.id = product.id 
                 
                  LEFT JOIN (

                      SELECT product_id  , COUNT(*) as total_rating_count FROM Rating WHERE enable = '0' 
                      GROUP BY product_id

                    ) total_rating ON total_rating.product_id = product.id  
                    
                    LEFT JOIN (

                      SELECT product_id  , AVG(rating) as rating FROM Rating WHERE enable = '0' 
                        GROUP BY product_id

                    ) avg_rating ON avg_rating.product_id = product.id
                     
                     WHERE product.brand_id = '$brand_id'
                    
            
            ", new CustomQuery("0", ""));



            if (!empty($search)){


                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", " AND  product.name LIKE '$search%'"));

            }

            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("0", " LIMIT 10 OFFSET  ".$offset));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
                //  $pic_path = image_resize(, 40, 40);
                //                //  echo $pic_path;
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' => $row['name'],
                    'images' => $this->products_images . $row['image'],
                    'sales' => ceil($row['sales']),
                    'rating' => $row['avg_ratings'],
                    'enable' => $row['enable'],


                ]);
            }

            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);



        }

        //        this is overview functionality

        else if ($this->functionalityType == "total_revenue") {


            $queryDecorator = new QueryDecorator(" SELECT  order_meta.*
         , SUM(CASE
                WHEN order_meta.discounted_amount <= '0' THEN order_meta.quantity * order_meta.price
                ELSE order_meta.discounted_amount
                END
             ) as total_amount , (SELECT meta_value_02 FROM Configuration ) as currency_symbol  
         FROM OrderMeta as order_meta
         INNER JOIN ListOfOrders as list_of_orders ON list_of_orders.id = order_meta.term_id
        
         WHERE list_of_orders.status= '2'
        
      

            ", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
//                    'id' => $row['order_id'],
//                    'user_name' => $row['user_name'],
//                    'user_image' => $this->userimages.$row['user_image'],
//                    'sale' => $row['t_sale'],
                    'total_amount' => ceil($row['total_amount']),
                    'currency_symbol' => $row['currency_symbol'],
//                    'avg' => $row['t_avg'],




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }
        else if ($this->functionalityType == "total_order") {


            $queryDecorator = new QueryDecorator(" SELECT  order_meta.*,count(*) as total_order
         
         FROM OrderMeta as order_meta
         INNER JOIN ListOfOrders as list_of_orders ON list_of_orders.id = order_meta.term_id
        
         WHERE list_of_orders.status= '2'
        
      

            ", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
//                    'id' => $row['order_id'],
//                    'user_name' => $row['user_name'],
//                    'user_image' => $this->userimages.$row['user_image'],
//                    'sale' => $row['t_sale'],
                    'total_order' => ceil($row['total_order']),
//                    'currency_symbol' => $row['currency_symbol'],
//                    'avg' => $row['t_avg'],




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }
        else if ($this->functionalityType == "total_brands") {


            $queryDecorator = new QueryDecorator(" SELECT  count(*) as total_brand FROM Brand as brand
         
        
      

            ", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
//                    'id' => $row['order_id'],
//                    'user_name' => $row['user_name'],
//                    'user_image' => $this->userimages.$row['user_image'],
//                    'sale' => $row['t_sale'],
                    'total_brand' => ceil($row['total_brand']),
//                    'currency_symbol' => $row['currency_symbol'],
//                    'avg' => $row['t_avg'],




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }
        else if ($this->functionalityType == "no_of_users") {


            $queryDecorator = new QueryDecorator(" SELECT  count(*) as total_user FROM User as user
         
        
      

            ", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
//                    'id' => $row['order_id'],
//                    'user_name' => $row['user_name'],
//                    'user_image' => $this->userimages.$row['user_image'],
//                    'sale' => $row['t_sale'],
                    'total_user' => ceil($row['total_user']),
//                    'currency_symbol' => $row['currency_symbol'],
//                    'avg' => $row['t_avg'],




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }
        else if ($this->functionalityType == "retrieve_top_customer") {


            $queryDecorator = new QueryDecorator(" SELECT  user.*,user.first_name as user_name,user.picture as user_image , sales.total_sales as t_sale , rating.avg_rating as t_avg,
SUM(CASE
                WHEN list_of_orders.discounted_amount <= '0' THEN list_of_orders.shipping_fee + list_of_orders.total_amount
                ELSE list_of_orders.discounted_amount
                END
             ) as total_amount , (SELECT meta_value_02 FROM Configuration ) as currency_symbol  
         FROM ListOfOrders as list_of_orders 
         INNER JOIN User as user ON user.id = list_of_orders.user_id
         LEFT JOIN (
         
            SELECT user_id  , count(*) as total_sales FROM ListOfOrders
         
         ) sales ON sales.user_id = list_of_orders.user_id
         LEFT JOIN (
         
            SELECT user_id  , AVG(rating) as avg_rating FROM Rating
         
         ) rating ON rating.user_id = list_of_orders.user_id
         
         WHERE DATE(list_of_orders.date_created) >= DATE_SUB(CURDATE(), INTERVAL 2 MONTH) 
         GROUP BY user.id
         LIMIT 10

            ", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
//                    'id' => $row['order_id'],
                    'user_name' => $row['user_name'],
                    'user_image' => $this->userimages.$row['user_image'],
                    'sale' => $row['t_sale'],
                    'total_amount' => ceil($row['total_amount']),
                    'currency_symbol' => $row['currency_symbol'],
                    'avg' => $row['t_avg'],




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }
        else if ($this->functionalityType == "retrieve_ten_products") {


            $queryDecorator = new QueryDecorator("SELECT  product.*,product.name as pro_name,product.image as pro_image , sales.total_sales as t_sale , rating.avg_rating as t_avg
         , SUM(CASE
                WHEN order_meta.discounted_amount <= '0' THEN order_meta.quantity * order_meta.price
                ELSE order_meta.discounted_amount
                END
             ) as total_amount , (SELECT meta_value_02 FROM Configuration ) as currency_symbol  
         FROM OrderMeta as order_meta
         INNER JOIN Product as product ON product.id = order_meta.product_id
         INNER JOIN Brand as brand ON brand.id = order_meta.brand_id
         INNER JOIN ListOfOrders as list_of_orders ON list_of_orders.id = order_meta.term_id
         LEFT JOIN (

            SELECT brand_id  , count(*) as total_sales FROM OrderMeta

         ) sales ON sales.brand_id = order_meta.brand_id
         LEFT JOIN (

            SELECT product_id  , AVG(rating) as avg_rating FROM Rating

         ) rating ON rating.product_id = order_meta.product_id

         WHERE DATE(list_of_orders.date_created) >= DATE_SUB(CURDATE(), INTERVAL 2 MONTH)
         GROUP BY product.id
         LIMIT 10

            ", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
//                    'id' => $row['order_id'],
                    'pro_name' => $row['pro_name'],
                    'pro_image' => $this->products_images.$row['pro_image'],
                    'sale' => $row['t_sale'],
                    'total_amount' => ceil($row['total_amount']),
                    'currency_symbol' => $row['currency_symbol'],
                    'avg' => $row['t_avg'],




                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }


        //        this is payment request functioanlity

        else if ($this->functionalityType == "retrieve_all_payment_request") {

            $search = $postdata['search'];
            $store_id = $postdata['store_id'];

            $queryDecorator = new QueryDecorator("SELECT request.*,request.id as req_id,
            request.total_sales as t_sales,request.total_earning as t_earning,request.status as req_status,branddata.*,branddata.name as brand_name
        ,bank_detail.*,bank_detail.bank_name as b_name,bank_detail.iban_no as b_iban
            FROM BrandMonthlyEarning as request
            INNER JOIN Brand as branddata ON branddata.id = request.brand_id
            INNER JOIN BankingDetail as bank_detail  ON bank_detail.term_id = branddata.id
            WHERE bank_detail.meta_key = 'brand detail' AND branddata.id = '$store_id'
            ", new CustomQuery("0", ""));

            if (!empty($search)){
                $and_condition= "AND";

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", $and_condition." branddata.name LIKE '$search%'"));

            }

            //<editor-fold desc="Total Data Counting functionality">

            $queryDecoratorCount = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("1", "SELECT count(*) as total_count ,"));

            $resultCount = queryRunner($queryDecoratorCount->getQuery());
            $rowObject = rowRetrieverObject($resultCount);
            $rowCount = $rowObject->total_count;
            if ($rowCount > 10) {
                $rowCount = ceil($rowCount / 10);
            }
            else{
                $rowCount = 1;
            }


            //</editor-fold>
            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                new CustomQuery("0", " LIMIT 10 "));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
                    'id' => $row['req_id'],
                    't_sales' => $row['t_sales'],
                    't_earning' => $row['t_earning'],
                    'req_status' => $row['req_status'],
                    'brand_name' => $row['brand_name'],
                    'bank_name' => $row['b_name'],
                    'band_iban' => $row['b_iban'],



                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData,Utility::getPaginationCssCode($rowCount));
        }
        else if ($this->functionalityType == "paymentpagination") {

            $search = $postdata['search'];
            $offset = $postdata['offset'];
            $store_id = $postdata['store_id'];

            $queryDecorator = new QueryDecorator("SELECT request.*,request.id as req_id,
            request.total_sales as t_sales,request.total_earning as t_earning,request.status as req_status,branddata.*,branddata.name as brand_name
        ,bank_detail.*,bank_detail.bank_name as b_name,bank_detail.iban_no as b_iban
            FROM BrandMonthlyEarning as request
            INNER JOIN Brand as branddata ON branddata.id = request.brand_id
            INNER JOIN BankingDetail as bank_detail  ON bank_detail.term_id = branddata.id
            WHERE bank_detail.meta_key = 'brand detail' AND branddata.id = '$store_id'
            ", new CustomQuery("0", ""));

            if (!empty($search)){
                $and_condition= "AND";

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", $and_condition." branddata.name LIKE '$search%'"));

            }


            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                new CustomQuery("0", " LIMIT 10 OFFSET ".$offset));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
                    'id' => $row['req_id'],
                    't_sales' => $row['t_sales'],
                    't_earning' => $row['t_earning'],
                    'req_status' => $row['req_status'],
                    'brand_name' => $row['brand_name'],
                    'bank_name' => $row['b_name'],
                    'band_iban' => $row['b_iban'],



                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }


        //        this is orders functionality

        else if ($this->functionalityType == "retrieve_all_orders") {

            $search = $postdata['search'];
            $store_id = $postdata['store_id'];

            $queryDecorator = new QueryDecorator("SELECT list_of_orders.*,list_of_orders.id as order_id,list_of_orders.transaction_token as token ,list_of_orders.status as stus,list_of_orders.enable as enble,
            user.*,user.first_name as names ,  user_address.*,user_address.address as user_adress, user_address.apartment as user_apart, user_address.city as user_city,user_address.postal_code as user_postal_code
            ,user_address.phone as user_contact,user_address.country as user_country
          FROM ListOfOrders as list_of_orders 
         INNER JOIN User as user ON user.id = list_of_orders.user_id
        INNER JOIN OrderMeta as order_meta ON order_meta.term_id = list_of_orders.id

         INNER JOIN UserMeta as user_address ON user_address.id = list_of_orders.address_id
         where list_of_orders.enable = '0' AND order_meta.brand_id = '$store_id' ", new CustomQuery("0", ""));
            if (!empty($search)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", " AND user.first_name LIKE '$search%' OR order_no LIKE '$search%'"));

            }

            //<editor-fold desc="Total Data Counting functionality">

            $queryDecoratorCount = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("1", "SELECT count(*) as total_count ,"));
            $resultCount = queryRunner($queryDecoratorCount->getQuery());
            $rowObject = rowRetrieverObject($resultCount);
            $rowCount = $rowObject->total_count;
            if ($rowCount > 10) {
                $rowCount = ceil($rowCount / 10);
            }
            else{
                $rowCount = 1;
            }


            //</editor-fold>
            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                new CustomQuery("0", " LIMIT 10 "));
//            Utility::Logger($queryDecorator->getQuery());

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
                    'id' => $row['order_id'],
                    'order_no' => $row['order_no'],
                    'total_amount' => $row['total_amount'],
                    'shipping_fee' => $row['shipping_fee'],
                    'discounted_amount' => ceil($row['discounted_amount']),
                    'status' => $row['stus'],
                    'name' => $row['names'],
                    'user_adress' => $row['user_adress'],
                    'user_apart' => $row['user_apart'],
                    'user_city' => $row['user_city'],
                    'user_postal_code' => $row['user_postal_code'],
                    'user_contact' => $row['user_contact'],
                    'user_country' => $row['user_country'],
                    'token' => $row['token'],



                    'detail' => $this->getOrderDetail($row['order_id'],$store_id),
                    'enble' => $row['enble'],


                ]);
            }

            ///Utility::DebugObject($listOfData);

            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData,Utility::getPaginationCssCode($rowCount));

        }
        else if ($this->functionalityType == "orderpagination") {

            $offset = $postdata['offset'];
            $search = $postdata['search'];
            $store_id = $postdata['store_id'];

            $queryDecorator = new QueryDecorator("SELECT list_of_orders.*,list_of_orders.id as order_id,list_of_orders.transaction_token as token ,list_of_orders.status as stus,list_of_orders.enable as enble,
            user.*,user.first_name as names ,  user_address.*,user_address.address as user_adress, user_address.apartment as user_apart, user_address.city as user_city,user_address.postal_code as user_postal_code
            ,user_address.phone as user_contact,user_address.country as user_country
          FROM ListOfOrders as list_of_orders 
         INNER JOIN User as user ON user.id = list_of_orders.user_id
          INNER JOIN OrderMeta as order_meta ON order_meta.term_id = list_of_orders.id
         INNER JOIN UserMeta as user_address ON user_address.id = list_of_orders.address_id
         where list_of_orders.enable = '0' AND order_meta.brand_id = '$store_id'", new CustomQuery("0", ""));
            if (!empty($search)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", " AND user.first_name LIKE '$search%' OR order_no LIKE '$search%'"));

            }

            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                new CustomQuery("0", " LIMIT 10 OFFSET ".$offset));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
                    'id' => $row['order_id'],
                    'order_no' => $row['order_no'],
                    'total_amount' => $row['total_amount'],
                    'shipping_fee' => $row['shipping_fee'],
                    'discounted_amount' => ceil($row['discounted_amount']),
                    'status' => $row['stus'],
                    'name' => $row['names'],
                    'user_adress' => $row['user_adress'],
                    'user_apart' => $row['user_apart'],
                    'user_city' => $row['user_city'],
                    'user_postal_code' => $row['user_postal_code'],
                    'user_contact' => $row['user_contact'],
                    'user_country' => $row['user_country'],
                    'token' => $row['token'],



                    'detail' => $this->getOrderDetail($row['order_id'],$store_id),
                    'enble' => $row['enble'],


                ]);
            }

            ///Utility::DebugObject($listOfData);

            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData );

        }

        // this is refund request functionality

        else if ($this->functionalityType == "retrieve_all_refund") {

            $search = $postdata['search'];
            $store_id = $postdata['store_id'];

            $queryDecorator = new QueryDecorator("SELECT refundrequest.* ,refundrequest.id as refunds_id,refundrequest.response as refund_response,refundrequest.reason as refund_reason,
            refundrequest.status as refund_status,orderdetail.*,orderdetail.price as order_price
        ,orderdetail.coupon_id as coupons,orderdetail.discounted_amount as discount,productdata.*,productdata.name as pro_name,productdata.image as pro_image,branddata.*,branddata.name as brand_name
        ,users.*,users.first_name as user_name
            FROM Refund as refundrequest
            INNER JOIN OrderMeta as orderdetail ON orderdetail.id = refundrequest.term_id
            INNER JOIN Product as productdata ON productdata.id = orderdetail.product_id
            INNER JOIN Brand as branddata ON branddata.id = refundrequest.brand_id
            INNER JOIN User as users  ON users.id = refundrequest.user_id
            WHERE branddata.id = $store_id
            ", new CustomQuery("0", ""));

            if (!empty($search)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", " AND productdata.name LIKE '$search%' OR users.first_name LIKE '$search%'"));

            }

            //<editor-fold desc="Total Data Counting functionality">

            $queryDecoratorCount = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("1", "SELECT count(*) as total_count ,"));
            $resultCount = queryRunner($queryDecoratorCount->getQuery());
            $rowObject = rowRetrieverObject($resultCount);
            $rowCount = $rowObject->total_count;
            if ($rowCount > 10) {
                $rowCount = ceil($rowCount / 10);
            }
            else{
                $rowCount = 1;
            }


            //</editor-fold>
            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                new CustomQuery("0", " LIMIT 10 "));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
                    'id' => $row['refunds_id'],
                    'user_name' => $row['user_name'],
                    'product_name' => $row['pro_name'],
                    'pro_image' => $this->products_images.$row['pro_image'],

                    'brand_name' => $row['brand_name'],
                    'discounted_amount' => ceil($row['discount']),
                    'order_price' => $row['order_price'],
                    'coupons_id' => $row['coupons'],
                    'refund_response' => $row['refund_response'],
                    'refund_status' => $row['refund_status'],
                    'refund_reason' => $row['refund_reason'],
                    'detail' => $this->getRefundDetail($row['refunds_id']),


                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData,Utility::getPaginationCssCode($rowCount));
        }
        else if ($this->functionalityType == "refundpagination") {

            $search = $postdata['search'];
            $offset = $postdata['offset'];
            $store_id = $postdata['store_id'];

            $queryDecorator = new QueryDecorator("SELECT refundrequest.* ,refundrequest.id as refunds_id,refundrequest.response as refund_response,refundrequest.reason as refund_reason,
            refundrequest.status as refund_status,orderdetail.*,orderdetail.price as order_price
        ,orderdetail.coupon_id as coupons,orderdetail.discounted_amount as discount,productdata.*,productdata.name as pro_name,productdata.image as pro_image,branddata.*,branddata.name as brand_name
        ,users.*,users.first_name as user_name
            FROM Refund as refundrequest
            INNER JOIN OrderMeta as orderdetail ON orderdetail.id = refundrequest.term_id
            INNER JOIN Product as productdata ON productdata.id = orderdetail.product_id
            INNER JOIN Brand as branddata ON branddata.id = refundrequest.brand_id
            INNER JOIN User as users  ON users.id = refundrequest.user_id
             WHERE branddata.id = $store_id
            ", new CustomQuery("0", ""));

            if (!empty($search)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", " AND productdata.name LIKE '$search%' OR users.first_name LIKE '$search%'"));

            }


            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                new CustomQuery("0", " LIMIT 10 OFFSET ".$offset));

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {

                array_push($listOfData, [
                    'id' => $row['refunds_id'],
                    'user_name' => $row['user_name'],
                    'product_name' => $row['pro_name'],
                    'pro_image' => $this->products_images.$row['pro_image'],

                    'brand_name' => $row['brand_name'],
                    'discounted_amount' => ceil($row['discount']),
                    'order_price' => $row['order_price'],
                    'coupons_id' => $row['coupons'],
                    'refund_response' => $row['refund_response'],
                    'refund_status' => $row['refund_status'],
                    'refund_reason' => $row['refund_reason'],
                    'detail' => $this->getRefundDetail($row['refunds_id']),


                ]);
            }
            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);
        }


    }

    public function update()
    {
        $listOfData = [];
        $postdata = $this->postData;

        if ($this->functionalityType == "update_enable_data") {
            $id = $postdata['id'];
            $enable = $postdata['enable_val'];


            $queryDecorator = new QueryDecorator("UPDATE product SET enable='$enable'", new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data update Successfully", "1", "0", $listOfData, '');

        }
        else if ($this->functionalityType == "update_coupons") {
            Utility::DebugObject($postdata);
            $id = $postdata['coupon_id'];
            $code = $postdata['ccode'];
            $name = $postdata['cname'];
            $type = $postdata['coupon_type'];
            $offer = $postdata['dvalue'];
            Utility::DebugObject($postdata['dvalue']);
            if (empty($postdata['dvalue'])) {

                $offer = $postdata['dvalue2'];
//                Utility::DebugObject($offer);
            }

            if (empty($postdata['price'])) {
                $price = "0";
                Utility::DebugObject($price);
            } else {
                $price = $postdata['price'];
            }
            if ($postdata['type_id'] == '1') {
                Utility::DebugObject("store");
                $brand_id = $postdata['type_id'];
            } else {
                $brand_id = "0";
                Utility::DebugObject("$brand_id");
            }


            $nature = $postdata['type_id'];
            $abc_name = $postdata['abc_name'];
            if (empty($postdata['startduration'])) {
                $sdate = "0";
            } else {
                $sdate = strtotime($postdata['startduration']);
                $sdate = gmdate("Y-m-d\ G:i:s", $sdate);
            }

            Utility::DebugObject($sdate);
            if (empty($postdata['duration'])) {
                $edate = "0";
            } else {
                $edate = strtotime($postdata['duration']);
                $edate = gmdate("Y-m-d\ G:i:s", $edate);
            }

            Utility::DebugObject($edate);
            if (empty($postdata['ulimit'])) {
                $user_count = "0";
            } else {
                $user_count = $postdata['ulimit'];
            }


            $queryDecorator = new QueryDecorator("UPDATE Coupon SET brand_id ='$brand_id',child_sub_category_id = '$abc_name',
            name ='$name', code = '$code', type = '$type', offer ='$offer', nature = '$nature', user_count = '$user_count',
            price_discount_value ='$price', start_date ='$sdate',end_date='$edate'", new CustomQuery("0", " WHERE id='$id'"));
            Utility::Logger($queryDecorator->getQuery());
            $result = queryRunner($queryDecorator->getQuery());
            if ($result != null) {
                session_start();
                header("location:../admin_panel/list_of_coupon.php");

            }

            return $this->getResponseObject("202", "Data Retrieve Successfully", "1", "0", $listOfData);

        }
        else if ($this->functionalityType == "update_product_attribute") {
            $id = $postdata['id'];
            $name = $postdata['name'];


            $queryDecorator = new QueryDecorator("UPDATE ProductAttribute SET name='$name'", new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data update Successfully", "1", "0", $listOfData, '');

        }
        else if ($this->functionalityType == "update_attributeitem") {
            $id = $postdata['id'];
            $name = $postdata['name'];
            $price = $postdata['price'];

            $img = $postdata['image'];


            $queryDecorator = new QueryDecorator("UPDATE AttributeItem SET  name ='$name', price='$price' ", new CustomQuery("0", ""));

            if (!isPath($img)) {

                $pro_image = convert_save_image_from_base64("ic_product_picture" . rand() . ".webp", $img, $this->products_images);
                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", " , image ='$pro_image'"));


            }
            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data update Successfully", "1", "0", $listOfData, '');

        }
        else if ($this->functionalityType == "update_products") {
//            Utility::DebugObject($postdata);
            $product_id = $postdata['product_id'];
            $cat_id = isEmpty($postdata['cat-id']);
            $sub_cat_id = isEmpty($postdata['sub-cat-id']);
            $child_cat_id = isEmpty($postdata['child-cat-id']);
            $brand_id = isEmpty($postdata['brand_id']);
            $name = isEmpty($postdata['pro']);
            $description = $postdata['ckeditor'];
            $price = $postdata['propri'];
            $processing_time = $postdata['processing_time'];
            $weight = $postdata['proWeight'];
            $cover_image = $postdata['cover_image'];
            $tags = $postdata['example'];
            $tags2 = explode(",",$tags);
            $shipping = $postdata['shipping'];
            if(empty($postdata['sale_start'])){
                $sale_start = "0";
            }else {

                $sale_start  = strtotime($postdata['sale_start']);
                $sale_start = gmdate("Y-m-d\ G:i:s", $sale_start);
            }
            if(empty($postdata['sale_end'])){
                $sale_end = "0";
            }else {
                $sale_end  = strtotime($postdata['sale_end']);
                $sale_end = gmdate("Y-m-d\ G:i:s", $sale_end);
            }
            $sale_type = $postdata['sale_type'];
            if(empty($postdata['sale_dis'])){
                $sale_dis = "0";
            }else {
                $sale_dis  = $postdata['sale_dis'];

            }
            $sale_id =$postdata['sale_id'];
            if($sale_id == '0'){
                $queryDecorator = new QueryDecorator("INSERT INTO Sale(brand_id,product_id,sale_type,discount,start_date,end_date) VALUES ('$brand_id','$product_id','$sale_type','$sale_dis','$sale_start','$sale_end')", new CustomQuery("0", ""));
                $result = queryRunner($queryDecorator->getQuery());
            }else {
                $queryDecorator = new QueryDecorator("UPDATE Sale SET brand_id ='$brand_id', sale_type = '$sale_type',discount ='$sale_dis',
                start_date= '$sale_start', end_date = '$sale_end' ", new CustomQuery("0", " WHERE product_id = '$product_id'"));
                $result = queryRunner($queryDecorator->getQuery());
            }

            $queryDecorator = new QueryDecorator("UPDATE Product SET 
            category_id ='$cat_id', sub_category_id='$sub_cat_id', child_category_id = '$child_cat_id', brand_id = '$brand_id', name = '$name' , description = '$description' 
            ,processing_time = '$processing_time' ,price = '$price',weight = '$weight'
           ",new CustomQuery("0",""));

            if (!isPath($cover_image)) {

                $pro_image=convert_save_image_from_base64("ic_category_picture".rand().".webp",$cover_image,$this->products_images);
                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("0"," , image ='$pro_image'"));


            }
            $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),new CustomQuery("0"," WHERE id = '$product_id'"));

            $result = queryRunner($queryDecorator->getQuery());



            $queryDecorator = new QueryDecorator("DELETE FROM  Tags", new CustomQuery("0", " WHERE product_id = '$product_id'"));

            $result = queryRunner($queryDecorator->getQuery());


                if (is_array($tags2)) {

                    foreach ($tags2 as $value) {
                        $queryDecorator = new QueryDecorator("INSERT INTO Tags(product_id,name)VALUES('$product_id','$value')", new CustomQuery("0", ""));

                        $result = queryRunner($queryDecorator->getQuery());
//                        $result = queryRunner($queryDecorator->getQuery());
//                        Utility::Logger($queryDecorator->getQuery());


                    }
                }




            if (is_array($shipping)) {
//                Utility::Logger("hello yes this shipping array");

                foreach ($shipping as $value) {
                    $queryDecorator = new QueryDecorator("UPDATE ProductShipping SET shipping_id ='$value'", new CustomQuery("0", " WHERE product_id = '$product_id'"));
                    $result = queryRunner($queryDecorator->getQuery());

                }
            }


            if ($result != null) {
                session_start();
                header("location:../store_panel/list_of_products.php");

            }

            return $this->getResponseObject("202", "Data Update Successfully", "1", "0", $listOfData);

        }

//        this is payment request functionality
        else if ($this->functionalityType == "update_enable_payment") {
            $id = $postdata['id'];
            $enable = $postdata['enable_val'];


            $queryDecorator = new QueryDecorator("UPDATE BrandMonthlyEarning SET status='$enable'", new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data update Successfully", "1", "0", $listOfData, '');

        }

        //        this is orders functionality

        else if($this->functionalityType == "update_enable_orders") {
            $id=$postdata['id'];
            $enable=$postdata['enable_val'];



            $queryDecorator = new QueryDecorator("UPDATE ListOfOrders SET enable='$enable'",new CustomQuery("0"," WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(),"Data update Successfully","1","0",$listOfData,'');

        }
        else if($this->functionalityType == "update_status_orders") {
            $id=$postdata['id'];
            $status=$postdata['status'];



            $queryDecorator = new QueryDecorator("UPDATE ListOfOrders SET status='$status'",new CustomQuery("0"," WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(),"Data update Successfully","1","0",$listOfData,'');

        }

        // this is refund request functionality

        else if ($this->functionalityType == "update_accept_data") {
            $id=$postdata['id'];
            $responce=$postdata['status'];



            $queryDecorator = new QueryDecorator("UPDATE refund SET response='$responce',status='1'",new CustomQuery("0"," WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(),"Data update Successfully","1","0",$listOfData,'');
        }
        else if ($this->functionalityType == "update_reject_data") {
            $id=$postdata['id'];
            $responce=$postdata['status'];



            $queryDecorator = new QueryDecorator("UPDATE refund SET response='$responce',status='2'",new CustomQuery("0"," WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(),"Data update Successfully","1","0",$listOfData,'');
        }


    }

    public function delete()
    {
        $listOfData = [];
        $postdata = $this->postData;
        if ($this->functionalityType == "delete_products_data") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("DELETE FROM  product", new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data Delete Successfully", "1", "0", $listOfData, '');

        }
        else if ($this->functionalityType == "delete_product_attribute") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("DELETE FROM  ProductAttribute", new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data Delete Successfully", "1", "0", $listOfData, '');

        }
        else if ($this->functionalityType == "delete_attributeitem") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("DELETE FROM  AttributeItem", new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data Delete Successfully", "1", "0", $listOfData, '');

        }
        else if ($this->functionalityType == "delete_products_picture") {
            $id = $postdata['id'];
            $queryDecorator = new QueryDecorator("DELETE FROM  ProductPicture", new CustomQuery("0", " WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(), "Data Delete Successfully", "1", "0", $listOfData, '');

        }

        //        this is orders functionality

        else if($this->functionalityType == "delete_order_data"){
            $id=$postdata['id'];
            $queryDecorator = new QueryDecorator("DELETE FROM  ListOfOrders",new CustomQuery("0"," WHERE id = '$id'"));

            $result = queryRunner($queryDecorator->getQuery());

            return $this->getResponseObject($this->getSuccess_code(),"Data Delete Successfully","1","0",$listOfData,'');

        }


    }


    public function getResponseObject($code, $message, $setId, $itemCount, $data, $pagination = null)
    {

        $responseObject = new ResponseObject();
        $responseObject->setCode($code);
        $responseObject->setMessage($message);
        $responseObject->setId($setId);
        $responseObject->setListOfData($data);
        $responseObject->setTotalCount($itemCount);
        $responseObject->setPagination($pagination);

        return $responseObject;

    }

    public function getcoupon($dlimit, $stime, $etime, $userlimit, $usagecount, $usercount, $currenttime, $enable)
    {

        $status = "";
        $duration = true;
        $ctime = strtotime($currenttime);
        $sdate = strtotime($stime);
        $edate = strtotime($etime);

        if ($userlimit == '1' && $dlimit == '1') {
            if ($enable == '0') {
                $status = "Active";
            } else {
                $status = "Disable";
            }
        } else {

            if ($dlimit == '0') {


                if ($ctime > $sdate && $ctime < $edate) {
                    $status = "Active";


                } else {
                    $status = "Time Exceded";

                    $duration = false;
                }
            }

            if ($userlimit == '0' && ($usercount > $usagecount) && $duration) {
                $status = "Active";


            } else if ($duration) {
                $status = "Limit Exceded";


            }
        }
        return $status;

    }

    public function gettimelocal($date)
    {
        $time = strtotime($date);
        $time = gmdate("Y-m-d\Th:i", $time);
        return $time;

    }

    public function getOrderDetail($id,$store_id){

        ///Utility::Logger("Meta Id = ".$id);
        $listOfData = [];

        $query = " SELECT order_detail.*,order_detail.discounted_amount as dicuont_amt ,order_detail.id as order_id,order_detail.quantity as qunty,order_detail.price as prices ,brand.*,brand.id as brand_id,brand.name as brand_name,brand.image as brand_image ,brand.address as brand_adrs,  product.*, product.id 
        as pro_id,product.image as pro_image,product.name as pro_name,product.processing_time as pro_time,product.price as pro_price , shipping.* ,shipping.estimated_delivery_days as ship_days,
  shipping.name as shipping_name,shipping.id as shipping_id ,shipping.logo as ship_image, packages.name as packages_name , packages.* , 
        coupon.name as cou_name , coupon_detail.* 
          FROM OrderMeta as order_detail 
         INNER JOIN Brand as brand ON brand.id = order_detail.brand_id
         INNER JOIN Product as product ON product.id = order_detail.product_id
          INNER JOIN CustomizedShipping as shipping ON shipping.id = order_detail.shipping_id
           INNER JOIN ShippingPackages as packages ON packages.id = order_detail.package_id AND packages.customized_shipping_id = shipping.id
         LEFT JOIN Coupon as coupon ON coupon.id = order_detail.coupon_id 
         LEFT JOIN CouponMeta as coupon_detail ON coupon_detail.id = coupon.type
        
         where order_detail.term_id = '$id' AND order_detail.brand_id = '$store_id'";
        $result = queryRunner($query);
        while ($row = rowRetriever($result)) {

            ////Utility::Logger("Coupon Name ="+$row['coupons_name']);

            array_push($listOfData, [
                'id' => $row['order_id'],
                'brand_id' => $row['brand_id'],
                'brand_adrsess' => $row['brand_adrs'],

                'brand_name' => $row['brand_name'],
                'image' => $this->brand_image_path.$row['brand_image'],
                'quanty' => $row['qunty'],
                'price' => $row['prices'],
                'dicuont_amt' => ceil($row['dicuont_amt']),

                'shipping_name' => $row['shipping_name'],
                'packages_name' => $row['packages_name'],
                'ship_days' => $row['ship_days'],

                'shipping_id' => $row['shipping_id'],
                'ship_logo' => $this->shippingimages.$row['ship_image'],

                'pro_id' => $row['pro_id'],
                'pro_image' => $this->products_images.$row['pro_image'],
                'pro_name' => $row['pro_name'],
                'pro_time' => $row['pro_time'],
                'pro_price' => $row['pro_price'],
                'coupon_name' => $row['cou_name'] ,
                'attributes' => $this->getProductAttribute($row['attribute_id'])


            ]);
        }

        return $listOfData;


    }

    public function getProductAttribute($id){

        ///Utility::Logger("Meta Id = ".$id);
        $listOfData = [];

        $query = " SELECT * FROM AttributeItem 
         where id IN('$id') ";
        $result = queryRunner($query);
        while ($row = rowRetriever($result)) {

            array_push($listOfData, [
                'id' => $row['id'],
                'name' => $row['name'],



            ]);
        }

        return $listOfData;


    }

    public function getRefundDetail($id){

        ///Utility::Logger("Meta Id = ".$id);
        $listOfData = [];

        $query = " SELECT * FROM RefundMeta 
         where term_id = '$id'";
        $result = queryRunner($query);
        while ($row = rowRetriever($result)) {

            array_push($listOfData, [
                'id' => $row['id'],
                'image' => $this->refundimages.$row['image'],
            ]);
        }

        return $listOfData;


    }
}