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

class Api extends API_Controller
{

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

    }


    public function applyCoupon(){

        $coupon = trim(RequestInput::post("code"));
        $cart = trim(RequestInput::post("cart"));


        if(is_string($cart))
            $cart = json_decode($cart,JSON_OBJECT_AS_ARRAY);


        foreach ($cart as $k => $c){

            $result = $this->mCouponsModel->calculateDiscountAmount(
                $coupon,
                $c['item_id'],
                $c['amount']
            );

            if($result[Tags::SUCCESS]==0){
                echo json_encode($result);
                return;
            }

            if($result[Tags::SUCCESS]==1){
                $cart[$k]['coupon_id'] = $result["coupon_id"];
                $cart[$k]['discountedAmount'] = $result["discountedAmount"];
                $cart[$k]['discount'] = $result["discount"];
            }else{
                $cart[$k]['coupon_id'] = 0;
                $cart[$k]['discountedAmount'] = 0;
                $cart[$k]['discount'] = 100;
            }

        }

        echo json_encode(array(Tags::SUCCESS=>1,Tags::RESULT=>$cart));
        return;

    }


}