<?php


namespace Elex\MultiVendor\Model;

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

use WC_Coupon;

class Coupon {
   
	public function save( $coupon, $data, $store_id ) {
		
		$defaults = array(
			'discount_type'                => 'fixed_cart',
			'amount'                       => 0,
			'individual_use'               => false,
			'product_ids'                  => array(),
			'exclude_product_ids'          => array(),
			'usage_limit'                  => '',
			'usage_limit_per_user'         => '',
			'limit_usage_to_x_items'       => '',
			'usage_count'                  => '',
			'expiry_date'                  => '',
			'enable_free_shipping'         => false,
			'product_category_ids'         => array(),
			'exclude_product_category_ids' => array(),
			'exclude_sale_items'           => false,
			'minimum_amount'               => '',
			'maximum_amount'               => '',
			'customer_emails'              => array(),
			'description'                  => '',
		);
	 
		$coupon_data = wp_parse_args( $data, $defaults );
		
		$coupon->set_code( $coupon_data['code'] );

		$coupon->set_description( $coupon_data['description'] );

		$coupon->set_discount_type( $coupon_data['discount_type'] );

		// discount amount
		$coupon->set_amount( $coupon_data['amount'] );

		// allow free shipping
		$coupon->set_free_shipping( $coupon_data['enable_free_shipping'] );

		// coupon expiry date
		$coupon->set_date_expires( $coupon_data['valid_till'] );


		// Usage Restriction

		// minimum spend
		$coupon->set_minimum_amount( $coupon_data['min_cart_spending'] );

		// maximum spend
		$coupon->set_maximum_amount( $coupon_data['max_cart_spending'] );

		// individual use only
		$coupon->set_individual_use( $coupon_data['individual_coupon_use'] );

		// exclude sale items
		$coupon->set_exclude_sale_items( $coupon_data['exclude_on_sale_item'] );

		// products
		$coupon->set_product_ids( $coupon_data['mv-coupon-product'] );

		// exclude products
		$coupon->set_excluded_product_ids( $coupon_data['exclude_product'] );

		// categories
		$coupon->set_product_categories( $coupon_data['product_category'] );

		// exclude categories
		$coupon->set_excluded_product_categories( $coupon_data['exclude_product_category'] );

		// allowed emails
		$coupon->set_email_restrictions( 
			$coupon_data['allowed_emails']
		);


		// Usage limit tab

		// usage limit per coupon
		$coupon->set_usage_limit( $coupon_data['usage_limit_per_coupon'] );
		// limit usage to X items
		
		$coupon->set_limit_usage_to_x_items( $coupon_data['usage_limit_x_items'] );
			
		// usage limit per user
		$coupon->set_usage_limit_per_user( $coupon_data['usage_limit_per_user'] );
		$meta_data_to_update = array(
			'elex_mv_validity_from' => $coupon_data['valid_from'],
			'elex_mv_coupon_title'  => $coupon_data['title'],
			'elex_mv_store_id'      => $store_id,
			'elex_mv_vendor_id'     => get_current_user_id(),
		);

		foreach ( $meta_data_to_update as $meta_key => $meta_value ) {
			if ( metadata_exists( 'post', $coupon->get_id() , $meta_key ) ) {
				$coupon->update_meta_data( $meta_key, $meta_value );
			} else {
				$coupon->add_meta_data( $meta_key, $meta_value );
			}
		}
		$coupon->save_meta_data();
		$coupon->save();
	
		if ( ! empty( $coupon_data['valid_from'] ) ) {
			$date = date_create( $coupon_data['valid_from'] );
			wp_update_post(
				array(
					'ID'        => $coupon->get_id(),
					'post_date' => date_format( $date, 'Y-m-d H:i:s' ),
				)
			);
		}
	}
	
	public function products( $coupon_product ) {
		$product_array     = array();
		$product_ids_value = array();
		if ( ! empty( $coupon_product ) ) {
			foreach ( $coupon_product as $id ) {
				$productname         = get_the_title( $id );
				$product_array       = array(
					'id'   => $id,
					'text' => $productname,
				);
				$product_ids_value[] = $product_array;
			}
		}
		return $product_ids_value;
	}

	public function categories( $coupon_category ) {
		$category_array     = array();
		$category_ids_value = array();
		if ( ! empty( $coupon_category ) ) {
			foreach ( $coupon_category as $id ) {
				$categoryname         = get_the_category_by_ID( $id );
				$category_array       = array(
					'id'   => $id,
					'text' => $categoryname,
				);
				$category_ids_value[] = $category_array;
			}
		}
		return $category_ids_value;
	}

	public function load_coupon_by_store( $store_id, $filters = array() ) {

		$filters = wp_parse_args(
			$filters,
			array(
				'meta_key'    => 'elex_mv_store_id',
				'meta_value'  => $store_id,
				'post_type'   => 'shop_coupon',
				'post_status' => 'publish', 
				'orderby'     => 'ID',
				'order'       => 'DESC',
				
			)
		);
		/**
		* Fires filter hook to filter coupon 
		* 
		* @since 1.0.0
		* @param $filters
		*/
		$filters      = apply_filters( 'elex_mv_coupons_filter', $filters );
		$coupon_posts = get_posts( $filters );
		return $coupon_posts;
	}

	public function coupon_date( $coupon_date ) {
		if ( ! empty( $coupon_date ) ) {
			$date = strtotime( $coupon_date );
			return gmdate( 'd-M-Y', $date );
		}
	}

	public function coupon_discount_type( $discount_type ) {

		if ( 'fixed_product' === $discount_type ) {
			$discount_type = 'Fixed product discount';
		} elseif ( 'percent' === $discount_type ) {
			$discount_type = 'Percentage discount';
		} else {
			$discount_type = '';
		}

		return $discount_type;
	}

	public function coupon_total_count( $store_id, $filters ) {
		$query = wpFluent()->table( 'posts' );
		$query->join( 'postmeta', 'postmeta.post_id', '=' , 'posts.ID' );
		$query->where( 'postmeta.meta_key' , 'elex_mv_store_id' );
		if ( isset( $store_id ) && ! empty( $store_id ) ) {
			$query->where( 'postmeta.meta_value' , $store_id );
		}
		$query->where( 'posts.post_status' , 'publish' );
		$query->where( 'posts.post_type' , 'shop_coupon' );

		if ( isset( $filters['s'] ) && ! empty( $filters['s'] ) ) {
			$query->where( 'post_title', 'like', '%' . $filters['s'] . '%' );
		}

		$query->orderBy( 'posts.ID', 'DESC' );
		return $query->count();
	}
}
