<?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 Products 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:../admin_panel/list_of_product.php");

            }

            return $this->getResponseObject("202", "Data Retrieve 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
                    
            
            ", new CustomQuery("0", ""));

            if (!empty($brand_id) || !empty($search)){

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

            }

            if (!empty($brand_id)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", " product.brand_id = '$brand_id'"));

            }

            if (!empty($search)){

                $and_condition = "";
                if (!empty($brand_id))
                    $and_condition= "AND";

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", $and_condition." 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']),
                    'enable' => $row['enable'],




                ]);
            }
            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
                    
            
            ", new CustomQuery("0", ""));

            if (!empty($brand_id) || !empty($search)){

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

            }

            if (!empty($brand_id)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", " product.brand_id = '$brand_id'"));

            }

            if (!empty($search)){

                $and_condition = "";
                if (!empty($brand_id))
                    $and_condition= "AND";

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(), new CustomQuery("0", $and_condition." 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);



        }



    }

    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'];
            $sale_enable =$postdata['sale_enable'];
            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', enable = '$sale_enable' ", 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());
            
            
            
            }
            }
            
            if (is_array($shipping)) {
            $queryDecorator = new QueryDecorator("DELETE FROM ProductShipping WHERE product_id ='$product_id'", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            
            foreach ($shipping as $value) {
                
            $queryDecorator = new QueryDecorator("INSERT INTO ProductShipping (product_id,shipping_id)VALUES('$product_id','$value')", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            
            }
            
            }

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

            }

            return $this->getResponseObject("202", "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, '');

        }

    }


    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;

    }

}