<?php
if (!defined( 'ABSPATH' )) exit;
class woo2app_core_api_coupon {
    public function __construct(){
        add_action( 'init', array( $this , 'woo2app_api_regular_url' ));
        add_filter( 'query_vars', array( $this , 'woo2app_api_query_vars' ));
        add_action( 'parse_request', array( $this , 'woo2app_api_parse_request' ));
    }
    function woo2app_api_regular_url(){
        add_rewrite_rule('', 'index.php?woo2app_coupon', 'top');
    }
    function woo2app_api_query_vars($query_vars){
        $query_vars[] = 'woo2app_coupon';
        return $query_vars;
    }
    function woo2app_api_parse_request(&$wp){
        if ( array_key_exists( 'woo2app_coupon', $wp->query_vars ) ) {
            $this->woo2app_coupon();
            exit();
        }
        return;
    }
    function woo2app_coupon(){
        header('Content-Type: application/json; charset=utf-8');
        if(isset($_POST['in'])){
            $in = $_POST['in'];
            $slashless = stripcslashes($in);
            $url_json = urldecode($slashless);
            $json = (array) json_decode($url_json);
	        $username = $json['user_login'] ? $json['user_login'] : $json['nameKarbari'];
	        $password = $json['user_password'] ? $json['user_password'] : $json['ramz'];
            WC()->cart->empty_cart();
            if (!isset($json["items"])) {
                wp_send_json_error(array('error' => 'Shopping cart is empty.'), 200);
            }
            $line_items = $json["items"];
            $total_price = 0;
            $qtt = 0;
            foreach ($line_items as $product) {
                WC()->cart->add_to_cart($product->product_id, $product->quantity,$product->variation_id);
            }
            $cart = wc()->cart->get_cart();
            if(isset($username) && isset($password) &&  !empty($password)){
                $user = $username;
                if(get_user_by( 'login', $user ) == true){
                    $u = get_user_by( 'login', $user );
                }
                elseif(get_user_by( 'email', $user ) == true ){
                    $u = get_user_by( 'email', $user );
                }
                //var_dump($u->ID);return;
            }
            foreach($cart as $index => $value){
                $qtt += $value["quantity"];
                $total_price += $value["line_subtotal"];
            }
            if (!isset($json["coupon_code"])) {
                wp_send_json_error(array('error' => 'Discount code is mandatory.'), 200);
            }
            $coupon_code = $json["coupon_code"];//$entity_body->coupon_code;
            $the_coupon = new WC_Coupon($coupon_code);
//-------------------------------------------------
            if (!$the_coupon->is_valid()) {
	            $err = $this->delete_all_between('&',';',strip_tags($the_coupon->get_error_message()));
	            wp_send_json_error(array('error' => __($err, 'woo2app')), 200); // recommended by abolahi
            } else {
                if($u){
                    //$coupon_code =  $json["coupon_code"];
                    $ids = $the_coupon->get_used_by();
                    $user_use = sizeof( array_keys( $ids, $u->ID ) );
                    if($user_use ){
                        if($user_use >= $the_coupon->get_usage_limit_per_user()
                            && $the_coupon->get_usage_limit_per_user() > 0){
                            wp_send_json_error(array('error' => __('Sorry, this coupon is invalid for you.', 'woo2app')), 200);
                            return;
                        }
                    }
                }
                WC()->cart->add_discount( $json["coupon_code"]);
                $price = (int)wc()->cart->discount_cart;
                wp_send_json_success(array('code' => $json["coupon_code"] , 'id' => $the_coupon->get_id(), 'amount' => $price));
            }
        }
        wp_send_json_error(array('error' => __('Invalid input.', 'woo2app')), 200);
        return;
    }
	public  function delete_all_between($beginning, $end, $string) {
		$beginningPos = strpos($string, $beginning);
		$endPos = strpos($string, $end);
		if ($beginningPos === false || $endPos === false) {
			return $string;
		}

		$textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

		return $this->delete_all_between($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced
	}
}