<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Coupons_model extends CI_Model
{

    function __construct()
    {
        parent::__construct();

    }

    public function applyCouponForOrder($invoice_id){

        $invoice = $this->mPaymentModel->getInvoice($invoice_id);

        //get items
        $items = json_decode($invoice->items,JSON_OBJECT_AS_ARRAY);

        //get linked order
        $order = $this->mOrderModel->getOrder($invoice->module_id);

        //get saved extras
        $discounts = json_decode($invoice->discounts,JSON_OBJECT_AS_ARRAY);


        $extrasDiscount = 0;

        foreach ($items as $item){

            if($order['coupon_id']>0){
                $result = $this->mCouponsModel->applyItemCoupon(
                    $order['coupon_id'],
                    $item['item_id'],
                    ($item['price']*$item['qty'])
                );
                if($result[Tags::SUCCESS]==1){
                    $extrasDiscount += $result['discountedAmount'];
                }
            }

        }

        if($extrasDiscount>0){
            $discounts['discount'] = $extrasDiscount * -1;
        }


        $this->db->where('id',$invoice->id);
        $this->db->update('invoice',array(
            'discounts' => json_encode($discounts,JSON_FORCE_OBJECT),
        ));



    }

    /*
     *  public function calculate_commission($invoice){

        $amount = $invoice->amount;

        $extras = array();

        if(ConfigManager::getValue('DELIVERY_FEES_TYPE') == "fixed"){

            $value = doubleval(ConfigManager::getValue('DELIVERY_FEES_VALUE'));

            $extras['delivery_fees'] = $value;


        }else if(ConfigManager::getValue('DELIVERY_FEES_TYPE') == "commission"){

            $value = doubleval(ConfigManager::getValue('DELIVERY_FEES_VALUE'));
            $value = ( ($value/100) * $amount );

            $extras['delivery_fees'] = $value;

        }


        $this->db->where('id',$invoice->id);
        $this->db->update('invoice',array(
            'extras' => json_encode($extras,JSON_FORCE_OBJECT)
        ));

        //add commission to an order
        if(isset($extras['delivery_fees'])){

            $this->db->where('id',$invoice->module_id);
            $this->db->update('order_list',array(
                'delivery_commission' => doubleval($extras['delivery_fees'])
            ));

            $this->db->where('id',$invoice->module_id);
            $this->db->update('order_list',array(
                'delivery_commission' => doubleval($extras['delivery_fees'])
            ));

        }

    }
     */

    public function getCoupon($cpId){

        $this->db->where('id',$cpId);
        $result = $this->db->get('coupons',1);
        $result = $result->result_array();

        if(!isset($result[0]))
            return NULL;

        return $result[0];
    }

    public function orderVerify($user_id, $couponCode){

        $device_date = date("Y-m-d H:i:s",time());
        $device_timzone = "UTC";
        $device_date_to_utc = MyDateUtils::convert($device_date, $device_timzone, "UTC", "Y-m-d H:i:s");

        $this->db->where('code',$couponCode);
        $this->db->where('expired_at >=',$device_date_to_utc);

        $result = $this->db->get('coupons',1);
        $result = $result->result_array();

        if(!isset($result[0]))
            return FALSE;


        $this->db->where('user_id',$user_id);
        $this->db->where('coupon_id',$result[0]['id']);
        $this->db->where('payment_status !=','unpaid');
        $this->db->where('status',1);
        $count = $this->db->count_all_results('order_list');

       /* if($count > 0)
            return FALSE;
*/

        return $result[0];
    }


    public function applyItemCoupon($coupon_id, $itemId,$amount){

        $device_date = date("Y-m-d H:i:s",time());
        $device_timzone = "UTC";
        $device_date_to_utc = MyDateUtils::convert($device_date, $device_timzone, "UTC", "Y-m-d H:i:s");

        $this->db->where('coupons.id',$coupon_id);
        $this->db->where('coupons.expired_at >=',$device_date_to_utc);

        $this->db->where('coupon_products.product_id',$itemId);
        $this->db->join('coupon_products','coupon_products.coupon_id=coupons.id');
        $this->db->join('product','product.id_product=coupon_products.product_id');

        $this->db->select('coupons.*');
        $coupon = $this->db->get('coupons');
        $coupon = $coupon->result_array();


        if(!isset($coupon[0]))
            return array(Tags::SUCCESS=>0,Tags::ERRORS=>array("err"=>_lang("The coupon is not exists or no longer valid")));

        $discount = $coupon[0]['coupon_value'];
        $discountedAmount = ($discount / 100 ) * $amount;

        return array(
            Tags::SUCCESS=>1,
            "discountedAmount"=> ($discountedAmount),
            "coupon_id"=> ($coupon[0]['id']),
            "discount"=> $discount
        );

    }

    public function calculateDiscountAmount($code, $itemId,$amount){

        $device_date = date("Y-m-d H:i:s",time());
        $device_timzone = "UTC";
        $device_date_to_utc = MyDateUtils::convert($device_date, $device_timzone, "UTC", "Y-m-d H:i:s");

        $this->db->where('coupons.code',$code);
        $this->db->where('coupons.expired_at >=',$device_date_to_utc);



        $this->db->where('coupon_products.product_id',$itemId);
        $this->db->join('coupon_products','coupon_products.coupon_id=coupons.id');
        $this->db->join('product','product.id_product=coupon_products.product_id');

        $this->db->select('coupons.*');
        $coupon = $this->db->get('coupons');
        $coupon = $coupon->result_array();

        if(!isset($coupon[0]))
            return array(Tags::SUCCESS=>0,Tags::ERRORS=>array("err"=>_lang("The coupon is not exists or no longer valid")));

        $discount = $coupon[0]['coupon_value'];
        $discountedAmount = ($discount / 100 ) * $amount;

        return array(
            Tags::SUCCESS=>1,
            "discountedAmount"=> ($discountedAmount),
            "coupon_id"=> ($coupon[0]['id']),
            "discount"=> $discount
        );

    }

    public function delete($cpId,$userId){


        $this->db->where('coupons.id',$cpId);
        $this->db->where('store.user_id',$userId);
        $this->db->join("store","store.id_store=coupons.store_id");
        $this->db->join("user","user.id_user=store.user_id");

        $count = $this->db->count_all_results('coupons');

        if($count == 0)
            return FALSE;


        $this->db->where('id',$cpId);
        $this->db->delete('coupons');

        return TRUE;
    }

    public function add($params=array()){

        $errors = array();
        $data = array();

        if(isset($params['store_id']) && $params['store_id'] > 0){
            $data["store_id"] = intval($params['store_id']);
        }else{
            $errors["label"] = _lang("Store ID field is not valid");
        }

        if(isset($params['label']) && $params['label']!=""){
            $data["label"] = trim($params['label']);
        }else{
            $errors["label"] = _lang("Label field is not valid");
        }

        if(isset($params['coupon_value']) && $params['coupon_value'] > 0){
            $data["coupon_value"] = trim($params['coupon_value']);
        }else{
            $errors["coupon_value"] = _lang("Discount value field is not valid");
        }

        if(isset($params['expired_at']) && Text::isRealDate($params['expired_at'])){
            $data["expired_at"] = trim($params['expired_at']);
        }else{
            $errors["expired_at"] = _lang("Expiration date field is not valid");
        }

        if(isset($params['linkedProducts']) && !empty($params['linkedProducts'])){
            $linkedProducts = $params['linkedProducts'];
        }else{
            $errors["expired_at"] = _lang("No product selected");
        }

        if(isset($linkedProducts)){
            $products = array();
            foreach ($linkedProducts as $item_id){
                $this->db->where('id_product',$item_id);
                $count =  $this->db->count_all_results('product');
                if($count == 0){
                    $errors['linkedProducts'] = _lang("A product is not exists or not valid");
                    break;
                }
                $products[] = $item_id;
            }
        }

        if(isset($params['label']) && trim($params['label'])!= ""){
            $data["label"] = trim($params['label']);
        }else{
            $errors["label"] = _lang("Label field is not valid");
        }

        //verify store
        if(isset($data["store_id"])){
            $this->db->where('id_store', $data["store_id"]);
            $this->db->where('status >=', 0);
            $this->db->where('hidden', 0);
            if(isset($params['user_id']) && $params['user_id']>0){
                $this->db->where('user_id', $params['user_id']);
            }
            $count = $this->db->count_all_results('store');
            if($count == 0)
                $errors['store'] = _lang("Store is not valid");
        }

        if(isset($params['user_id'])){
                if(!$this->verifySubscription($params['user_id']))
                    $errors['verifySubscription'] = _lang("You have exceeded the maximum number of coupons");
        }

        if(!empty($errors)){
            return array(Tags::SUCCESS=>0,Tags::ERRORS=>$errors);
        }

        $data['code'] = strtoupper(coupon::generate(6, "", "", true, true, false, true));

        $data['created_at'] = date("Y-m-d h:i:s",time());
        $data['updated_at'] = date("Y-m-d h:i:s",time());

        $this->db->insert('coupons',$data);

        $id = $this->db->insert_id();

        foreach ($products as $product){
            $this->db->insert('coupon_products',array(
                'coupon_id' => $id,
                'product_id' => $product,
                'created_at' =>  date("Y-m-d h:i:s",time()),
                'updated_at' =>  date("Y-m-d h:i:s",time()),
            ));
        }

        if(isset($params['user_id'])){
            $this->descreaseSubscription($params['user_id']);
        }

        return array(Tags::SUCCESS=>1);
    }


    private function verifySubscription($userId){

        $nbr_coupons_monthly = UserSettingSubscribe::getUDBSetting($userId, KS_NBR_COUPONS_MONTHLY);
        if ($nbr_coupons_monthly > 0 || $nbr_coupons_monthly == -1) {
           return TRUE;

        } else {
            return FALSE;
        }

    }

    private function descreaseSubscription($userId){

        $nbr_coupons_monthly = UserSettingSubscribe::getUDBSetting($userId, KS_NBR_COUPONS_MONTHLY);
        if ($nbr_coupons_monthly > 0 || $nbr_coupons_monthly == -1) {

            if ($nbr_coupons_monthly > 0) {
                $nbr_coupons_monthly--;
                UserSettingSubscribe::refreshUSetting($userId, KS_NBR_COUPONS_MONTHLY, $nbr_coupons_monthly);
            }

            return TRUE;
        } else {
            return FALSE;
        }

    }


    public function getCoupons($params = array(),$whereArray=array()){

        extract($params);

        if (!isset($page))
            $page = 1;

        if (!isset($limit))
            $limit = 20;

        if (isset($coupon_id) && $coupon_id>0)
            $this->db->where("coupons.id", $coupon_id);


        if (isset($user_id) and $user_id >0)
            $this->db->where("store.user_id", $user_id);

        if (!empty($whereArray))
            $this->db->where($whereArray);

        $this->db->join("store","store.id_store=coupons.store_id");
        $this->db->join("user","user.id_user=store.user_id");

        $count = $this->db->count_all_results("coupons");

        $pagination = new Pagination();
        $pagination->setCount($count);
        $pagination->setCurrent_page($page);
        $pagination->setPer_page($limit);
        $pagination->calcul();

        if (isset($coupon_id) && $coupon_id>0)
            $this->db->where("coupons.id", $coupon_id);

        if (isset($user_id) and $user_id >0)
            $this->db->where("store.user_id", $user_id);


        $this->db->join("store","store.id_store=coupons.store_id");
        $this->db->join("user","user.id_user=store.user_id");


        $this->db->select("coupons.*, store.name as 'store_name', store.id_store as 'store_id'");
        $this->db->from("coupons");
        $this->db->limit($pagination->getPer_page(), $pagination->getFirst_nbr());

        $this->db->order_by("coupons.id", "DESC");

        $results = $this->db->get();
        $results = $results->result_array();


        foreach ($results as $key => $value){

            $this->db->where('coupon_id',$value['id']);
            $coupon_products = $this->db->get('coupon_products');
            $coupon_products = $coupon_products->result_array();

            $results[$key]['products'] = array();

            foreach ($coupon_products as $val){

                $callback = NSModuleLinkers::find('product','getData');
                if($callback != NULL){
                    $result = call_user_func($callback,array(
                        'id' => $val['product_id']
                    ));
                    $results[$key]['products'][] = array(
                        'label' => $result['label'],
                        'id' => $val['product_id']
                    );
                }
            }

        }

        return array(Tags::SUCCESS => 1, "pagination" => $pagination, Tags::COUNT => $count, Tags::RESULT => $results);
    }


    public function createTableDFCoupon()
    {

        //create coupons
        $this->load->dbforge();
        $this->dbforge->add_field(array(
            'id' => array(
                'type' => 'INT',
                'constraint' => 11,
                'auto_increment' => TRUE
            ),
            'store_id' => array(
                'type' => 'INT',
                'default' => NULL
            ),
            'label' => array(
                'type' => 'VARCHAR(100)',
                'default' => NULL
            ),
            'code' => array(
                'type' => 'VARCHAR(30)',
                'default' => NULL
            ),
            'coupon_value' => array(
                'type' => 'DOUBLE',
                'default' => NULL
            ),
            'expired_at' => array(
                'type' => 'DATETIME'
            ),
            'updated_at' => array(
                'type' => 'DATETIME'
            ),
            'created_at' => array(
                'type' => 'DATETIME'
            ),
        ));

        $attributes = array('ENGINE' => 'InnoDB');
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('coupons', TRUE, $attributes);


        //create coupon_products
        $this->dbforge->add_field(array(
            'id' => array(
                'type' => 'INT',
                'constraint' => 11,
                'auto_increment' => TRUE
            ),
            'coupon_id' => array(
                'type' => 'INT',
                'default' => NULL
            ),
            'product_id' => array(
                'type' => 'INT',
                'default' => NULL
            ),
            'updated_at' => array(
                'type' => 'DATETIME'
            ),
            'created_at' => array(
                'type' => 'DATETIME'
            ),
        ));

        $attributes = array('ENGINE' => 'InnoDB');
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('coupon_products', TRUE, $attributes);


        //create coupon_products
        $this->dbforge->add_field(array(
            'id' => array(
                'type' => 'INT',
                'constraint' => 11,
                'auto_increment' => TRUE
            ),
            'coupon_id' => array(
                'type' => 'INT',
                'default' => NULL
            ),
            'product_id' => array(
                'type' => 'INT',
                'default' => NULL
            ),
            'user_id' => array(
                'type' => 'INT',
                'default' => NULL
            ),
            'updated_at' => array(
                'type' => 'DATETIME'
            ),
            'created_at' => array(
                'type' => 'DATETIME'
            ),
        ));

        $attributes = array('ENGINE' => 'InnoDB');
        $this->dbforge->add_key('id', TRUE);
        $this->dbforge->create_table('coupon_users', TRUE, $attributes);


    }

}