<?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 Coupons 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;
//        Utility::DebugObject($postdata);
        if ($this->functionalityType == "insert_coupons") {
//            Utility::DebugObject($postdata);
            $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'){
//
                $brand_id=$postdata['type_id'];
            }else {
                $brand_id ="0";

            }


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


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


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



            $queryDecorator = new QueryDecorator("INSERT INTO Coupon (brand_id,child_sub_category_id,name
            ,code,type,offer,nature,user_count,price_discount_value,start_date,end_date) 
            VALUES ('$brand_id','$abc_name','$name','$code','$type','$offer','$nature','$user_count','$price','$sdate','$edate')", new CustomQuery("0", ""));

            $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 retrieve()
    {
        $listOfData = [];
        $postdata = $this->postData;
        if ($this->functionalityType == "retrieve_all_coupons") {

            $search = $postdata['search'];

            $queryDecorator = new QueryDecorator("SELECT coupon.* , now() as time FROM Coupon as coupon",
                new CustomQuery("0", ""));

            if (!empty($search)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", " WHERE name LIKE '$search%' OR tagline 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['id'],
                    'name' => $row['name'],
                    'start_date' => $row['start_date'],
                    'end_date' => $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'],
                    'status' => $this->getcoupon($row['duration_limit'], $row['start_date'], $row['end_date'], $row['user_limit'], $row['usage_count'], $row['user_count'], $row['time'], $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);


        }

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

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

            $queryDecorator = new QueryDecorator("SELECT * ,now() as time FROM Coupon",
                new CustomQuery("0", ""));

            if (!empty($search)){

                $queryDecorator = new QueryDecorator($queryDecorator->getQuery(),
                    new CustomQuery("0", " WHERE name LIKE '$search%' OR tagline LIKE '$search%'"));

            }

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

            $result = queryRunner($queryDecorator->getQuery());
            while ($row = rowRetriever($result)) {
//                $total_count = $row['total_count'];
                array_push($listOfData, [
                    'id' => $row['id'],
                    'name' => $row['name'],
                    'start_date' => $row['start_date'],
                    'end_date' => $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'],
                    'status' => $this->getcoupon($row['duration_limit'], $row['start_date'], $row['end_date'], $row['user_limit'], $row['usage_count'], $row['user_count'], $row['time'], $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 Coupon 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_coupons_data"){
            $id=$postdata['id'];
            $queryDecorator = new QueryDecorator("DELETE FROM  Coupon",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;

    }




}