<?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 Orders 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(){


    }

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

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

            $search = $postdata['search'];

            $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 UserMeta as user_address ON user_address.id = list_of_orders.address_id
         where list_of_orders.enable = '0'", 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']),
                    'enble' => $row['enble'],


                ]);
            }

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

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

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

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

            $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 UserMeta as user_address ON user_address.id = list_of_orders.address_id
         where list_of_orders.enable = '0'", 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']),
                    'enble' => $row['enble'],


                ]);
            }

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

            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 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_data") {
            $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,'');

        }

    }

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

        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 getOrderDetail($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'";
        $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;


    }


}