<?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 Brand extends Constant implements Queries
{
    private $dtObject;
    private $actionType = "";
    private $functionalityType = "";
    public $postData = [];


    function __construct(DataObject $dtObject)
    {

        parent::__construct();
        $this->dtObject = $dtObject;
        $this->actionType = $dtObject->getActionType();
        $this->functionalityType = $dtObject->getFunctionalityType();
        $this->postData = $dtObject->getPostData();


    }


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

        if ($this->functionalityType == "insert_add_brand") {

            $brand_owner_email = isEmpty($postdata['brand_crandential_email']);
            $brand_owner_password = $postdata['brand_crandential_password'];

            $brand_cat_id = isEmpty($postdata['cat-id']);
            $brand_sub_arry = $postdata['get-array'];
            $brand_name = isEmpty($postdata['brand_name']);
            $brand_address = isEmpty($postdata['brand_address']);
            $brand_logo = isEmpty($postdata["brand_logo"]);
            $brand_cover_photo = isEmpty($postdata['brand_cover_photo']);
            $bank_name = isEmpty($postdata['bank_name']);
            $branch_code = isEmpty($postdata['branch_code']);
            $BanK_holder_name = isEmpty($postdata['BanK_holder_name']);
            $bank_account_no = isEmpty($postdata['bank_account_no']);
            $bank_iban_no = isEmpty($postdata['bank_iban_no']);
            $bank_checque_pic = isEmpty($postdata['bank_cheque_pic']);
            $personal_first_name = isEmpty($postdata['personal_first_name']);
            $personal_last_name = isEmpty($postdata['personal_last_name']);
            $personal_cnic = isEmpty($postdata['personal_cnic']);
            $personal_phone_no = isEmpty($postdata['personal_phone_no']);
            $personal_address = isEmpty($postdata['personal_address']);
            $persoanl_city = isEmpty($postdata['persoanl_city']);
            $personal_country = isEmpty($postdata['personal_country']);
            $personal_postal_code = isEmpty($postdata['personal_postal_code']);

            $brand_image=convert_save_image_from_base64("ic_brand_logo_picture".rand().".webp",$brand_logo,$this->brand_image_path);
            $brand_cover=convert_save_image_from_base64("ic_brand_cover_picture".rand().".webp",$brand_cover_photo,$this->brand_image_path);
            $brand_cheque=convert_save_image_from_base64("ic_bank_checque_picture".rand().".webp",$bank_checque_pic,$this->brand_image_path);



            $queryDecorator = new QueryDecorator("INSERT INTO Brand (category_id,sub_category_id,name,cover_photo,image,address)
         VALUES('$brand_cat_id','$brand_sub_arry','$brand_name','$brand_cover','$brand_image',' $brand_address')", new CustomQuery("0", ""));

            $result = queryRunner($queryDecorator->getQuery());
            $brand_id=findLastInsertId();
            $queryDecorator = new QueryDecorator("INSERT INTO BankingDetail (term_id,meta_key,bank_name,branch_code,account_holder_name,account_no,iban_no,cheque_picture)
        VALUES('$brand_id','brand detail','$bank_name','$branch_code','$BanK_holder_name',' $bank_account_no','$bank_iban_no','$brand_cheque')", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            $queryDecorator = new QueryDecorator("INSERT INTO PersonalDetail (term_id,first_name,last_name,cnic,phone_no,address,city,postal_code,country)
        VALUES('$brand_id','$personal_first_name','$personal_last_name','$personal_cnic','$personal_phone_no',' $personal_address','$persoanl_city','$personal_country','$personal_postal_code')", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());

            $queryDecorator = new QueryDecorator("INSERT INTO BrandCredentials (term_id,meta_key,email,password,enable)
        VALUES('$brand_id','brand_admin','$brand_owner_email','$brand_owner_password','0')", new CustomQuery("0", ""));
            $result = queryRunner($queryDecorator->getQuery());
            if($result!=null) {
                session_start();
                header("location:../admin_panel/list_of_brands.php");

            }

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

        }

    }

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

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

            $queryDecorator = new QueryDecorator("SELECT brand.* , ctg.name as category_name ,IF(total_sales.sales IS NOT NULL, total_sales.sales , '0') as sales ,IF(total_products.items IS NOT NULL, total_products.items , '0') as product_count ,  total_rating.total_rating_count ,  IF(avg_rating.rating IS NOT NULL, avg_rating.rating , '0.0') as avg_ratings    ,IF(count_follwer.total_follwer IS NOT NULL, count_follwer.total_follwer , '0') as total_follwers
                  FROM Brand  as brand 
                  
                  INNER JOIN Categories as ctg on ctg.id = brand.category_id
                        
                  LEFT JOIN (
                     SELECT brand_id as id , SUM(price) as sales FROM OrderMeta WHERE enable = '0'  GROUP BY brand_id 
                  ) total_sales ON total_sales.id = brand.id 

                  LEFT JOIN (
                     SELECT brand_id as id , COUNT(*) as items FROM Product WHERE enable = '0'
                      GROUP BY brand_id 
                  ) total_products ON total_products.id = brand.id  

                  LEFT JOIN (

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

                    ) total_rating ON total_rating.brand_id = brand.id  
                    
                    LEFT JOIN (

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

                    ) avg_rating ON avg_rating.brand_id = brand.id
                    LEFT JOIN (

                      SELECT meta_value  , COUNT(*) as total_follwer FROM  Following WHERE meta_key = 'favourite_store'  GROUP BY meta_value

                      ) count_follwer ON count_follwer.meta_value = brand.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", " brand.category_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." brand.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->brand_image_path.$row['image'],
                    'category_name' => $row['category_name'],
                    'total_follwers' => $row['total_follwers'],
                    'product_count' => $row['product_count'],
                    'sales' => ceil($row['sales']),
                    'avg_ratings' => $row['avg_ratings'],

                    'enable' => $row['enable'],


                ]);
            }

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

        }
        else if($this->functionalityType == "retrieve_brand_data"){
            $queryDecorator = new QueryDecorator("SELECT * FROM Brand", 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_allCategory_data"){
            $queryDecorator = new QueryDecorator("SELECT * FROM ChildSubCategories", 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_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_coupon_data_edit") {
            $id=$postdata['id'];
            $queryDecorator = new QueryDecorator("SELECT * FROM Coupon", 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'],
                    'name' => $row['name'],
                    'code' => $row['code'],
                    'type' => $row['type'],
                    'dvalue' => $row['offer'],
                    'price' => $row['price_discount_value'],
                    'nature_type' => $row['nature'],
                    'child_sub_category_id' => $row['child_sub_category_id'],
                    'brand_id' => $row['brand_id'],
                    'start_date' => $this->gettimelocal($row['start_date']),
                    'end_date' => $this->gettimelocal($row['end_date']),
                    'user_count' => $row['user_count'],
                    'usage_count' => $row['usage_count'],
                    'duration_limit' => $row['duration_limit'],
                    'user_limit' => $row['user_limit'],
                    'enable' => $row['enable'],



                ]);
            }
            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);


        }

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

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

            $queryDecorator = new QueryDecorator("SELECT brand.* , ctg.name as category_name ,IF(total_sales.sales IS NOT NULL, total_sales.sales , '0') as sales ,IF(total_products.items IS NOT NULL, total_products.items , '0') as product_count ,  total_rating.total_rating_count ,  IF(avg_rating.rating IS NOT NULL, avg_rating.rating , '0.0') as avg_ratings    ,IF(count_follwer.total_follwer IS NOT NULL, count_follwer.total_follwer , '0') as total_follwers
                  FROM Brand  as brand 
                  
                  INNER JOIN Categories as ctg on ctg.id = brand.category_id
                        
                  LEFT JOIN (
                     SELECT brand_id as id , SUM(price) as sales FROM OrderMeta WHERE enable = '0'  GROUP BY brand_id 
                  ) total_sales ON total_sales.id = brand.id 

                  LEFT JOIN (
                     SELECT brand_id as id , COUNT(*) as items FROM Product WHERE enable = '0'
                      GROUP BY brand_id 
                  ) total_products ON total_products.id = brand.id  

                  LEFT JOIN (

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

                    ) total_rating ON total_rating.brand_id = brand.id  
                    
                    LEFT JOIN (

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

                    ) avg_rating ON avg_rating.brand_id = brand.id
                    LEFT JOIN (

                      SELECT meta_value  , COUNT(*) as total_follwer FROM  Following WHERE meta_key = 'favourite_store'  GROUP BY meta_value

                      ) count_follwer ON count_follwer.meta_value = brand.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", " brand.category_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." brand.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->brand_image_path.$row['image'],
                    'category_name' => $row['category_name'],
                    'total_follwers' => $row['total_follwers'],
                    'product_count' => $row['product_count'],
                    'sales' => ceil($row['sales']),
                    'avg_ratings' => $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 Brand 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);

        }


    }

    public function delete()
    {
        $listOfData = [];
        $postdata = $this->postData;
        if($this->functionalityType == "delete_brand_data"){
            $id=$postdata['id'];
            $queryDecorator = new QueryDecorator("DELETE FROM  Brand",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;

    }
}