<?php
/**
 * CouponRepository class.
 *
 * @since 2.5.12
 *
 * @package Masteriyo\Addons\Coupons\Repository
 */

namespace Masteriyo\Addons\Coupons\Repository;

defined( 'ABSPATH' ) || exit;


use Masteriyo\Database\Model;
use Masteriyo\Enums\PostStatus;
use Masteriyo\PostType\PostType;
use Masteriyo\Addons\Coupons\Models\Coupon;
use Masteriyo\Repository\AbstractRepository;
use Masteriyo\Repository\RepositoryInterface;
use Masteriyo\Addons\Coupons\Enums\CouponStatus;

/**
 * CouponRepository class.
 */
class CouponRepository extends AbstractRepository implements RepositoryInterface {

	/**
	 * Data stored in meta keys, but not considered "meta".
	 *
	 * @since 2.5.12
	 * @var array
	 */
	protected $internal_meta_keys = array(
		'discount_type'          => '_discount_type',
		'discount_amount'        => '_discount_amount',
		'usage_limit_per_user'   => '_usage_limit_per_user',
		'usage_limit_per_coupon' => '_usage_limit_per_coupon',
		'usage_count'            => '_usage_count',
		'start_at'               => '_start_at',
		'expire_at'              => '_expire_at',
		'applies_to'             => '_applies_to',
		'method'                 => '_method',
		'stackable'              => '_stackable',
	);

	/**
	 * Create a coupon in the database.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 */
	public function create( Model &$coupon ) {
		if ( ! $coupon->get_created_at( 'edit' ) ) {
			$coupon->set_created_at( time() );
		}

		if ( ! $coupon->get_author_id( 'edit' ) ) {
			$coupon->set_author_id( get_current_user_id() );
		}

		$id = wp_insert_post(
			/**
			 * Filters new coupon data before creating.
			 *
			 * @since 2.5.12
			 *
			 * @param array $data New coupon data.
			 * @param Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
			 */
			apply_filters(
				'masteriyo_new_coupon_data',
				array(
					'post_type'      => PostType::COUPON,
					'post_status'    => $coupon->get_status() ? $coupon->get_status() : CouponStatus::ACTIVE,
					'post_author'    => $coupon->get_author_id( 'edit' ),
					'post_title'     => $coupon->get_code(),
					'post_content'   => $coupon->get_description(),
					'comment_status' => 'closed',
					'ping_status'    => 'closed',
					'post_date'      => gmdate( 'Y-m-d H:i:s', $coupon->get_created_at( 'edit' )->getOffsetTimestamp() ),
					'post_date_gmt'  => gmdate( 'Y-m-d H:i:s', $coupon->get_created_at( 'edit' )->getTimestamp() ),
				),
				$coupon
			)
		);

		if ( $id && ! is_wp_error( $id ) ) {
			$coupon->set_id( $id );
			$this->update_post_meta( $coupon, true );
			// TODO Invalidate caches.

			$coupon->save_meta_data();
			$coupon->apply_changes();

			/**
			 * Fires after creating a coupon.
			 *
			 * @since 2.5.12
			 *
			 * @param integer $id The coupon ID.
			 * @param \Masteriyo\Addons\Coupons\Models\Coupon $object The coupon object.
			 */
			do_action( 'masteriyo_new_coupon', $id, $coupon );
		}

	}

	/**
	 * Read a coupon.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @throws \Exception If invalid coupon.
	 */
	public function read( Model &$coupon ) {
		$coupon_post = get_post( $coupon->get_id() );

		if ( ! $coupon->get_id() || ! $coupon_post || PostType::COUPON !== $coupon_post->post_type ) {
			throw new \Exception( __( 'Invalid coupon.', 'learning-management-system' ) );
		}

		$coupon->set_props(
			array(
				'code'        => $coupon_post->post_title,
				'status'      => $coupon_post->post_status,
				'author_id'   => $coupon_post->post_author,
				'description' => $coupon_post->post_content,
				'created_at'  => $this->string_to_timestamp( $coupon_post->post_date_gmt ),
				'modified_at' => $this->string_to_timestamp( $coupon_post->post_modified_gmt ),
			)
		);

		$this->read_coupon_data( $coupon );
		$this->read_extra_data( $coupon );
		$coupon->set_object_read( true );

		/**
		 * Fires after reading a coupon from database.
		 *
		 * @since 2.5.12
		 *
		 * @param integer $id The coupon ID.
		 * @param \Masteriyo\Addons\Coupons\Models\Coupon $object The coupon object.
		 */
		do_action( 'masteriyo_coupon_read', $coupon->get_id(), $coupon );
	}

	/**
	 * Update a coupon in the database.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 *
	 * @return void
	 */
	public function update( Model &$coupon ) {
		$changes = $coupon->get_changes();

		$post_data_keys = array(
			'description',
			'code',
			'status',
			'author_id',
			'created_at',
			'modified_at',
		);

		// Only update the post when the post data changes.
		if ( array_intersect( $post_data_keys, array_keys( $changes ) ) ) {
			$post_data = array(
				'post_content'   => $coupon->get_description( 'edit' ),
				'post_title'     => $coupon->get_code( 'edit' ),
				'post_author'    => $coupon->get_author_id( 'edit' ),
				'comment_status' => 'closed',
				'post_status'    => $coupon->get_status(),
				'post_type'      => PostType::COUPON,
				'post_date'      => gmdate( 'Y-m-d H:i:s', $coupon->get_created_at( 'edit' )->getOffsetTimestamp() ),
				'post_date_gmt'  => gmdate( 'Y-m-d H:i:s', $coupon->get_created_at( 'edit' )->getTimestamp() ),
			);

			/**
			 * When updating this object, to prevent infinite loops, use $wpdb
			 * to update data, since wp_update_post spawns more calls to the
			 * save_post action.
			 *
			 * This ensures hooks are fired by either WP itself (admin screen save),
			 * or an update purely from CRUD.
			 */
			if ( doing_action( 'save_post' ) ) {
				// TODO Abstract the $wpdb WordPress class.
				$GLOBALS['wpdb']->update( $GLOBALS['wpdb']->posts, $post_data, array( 'ID' => $coupon->get_id() ) );
				clean_post_cache( $coupon->get_id() );
			} else {
				wp_update_post( array_merge( array( 'ID' => $coupon->get_id() ), $post_data ) );
			}
			$coupon->read_meta_data( true ); // Refresh internal meta data, in case things were hooked into `save_post` or another WP hook.
		} else { // Only update post modified time to record this save event.
			$GLOBALS['wpdb']->update(
				$GLOBALS['wpdb']->posts,
				array(
					'post_modified'     => current_time( 'mysql' ),
					'post_modified_gmt' => current_time( 'mysql', true ),
				),
				array(
					'ID' => $coupon->get_id(),
				)
			);
			clean_post_cache( $coupon->get_id() );
		}

		$this->update_post_meta( $coupon );

		$coupon->apply_changes();

		/**
		 * Fires after updating a coupon.
		 *
		 * @since 2.5.12
		 *
		 * @param integer $id The coupon ID.
		 * @param \Masteriyo\Addons\Coupons\Models\Coupon $object The coupon object.
		 */
		do_action( 'masteriyo_update_coupon', $coupon->get_id(), $coupon );
	}

	/**
	 * Delete a coupon from the database.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @param array $args   Array of args to pass.alert-danger.
	 */
	public function delete( Model &$coupon, $args = array() ) {
		$id          = $coupon->get_id();
		$object_type = $coupon->get_object_type();

		$args = array_merge(
			array(
				'force_delete' => false,
			),
			$args
		);

		if ( ! $id ) {
			return;
		}

		if ( $args['force_delete'] ) {
			/**
			 * Fires before deleting a coupon.
			 *
			 * @since 2.5.12
			 *
			 * @param integer $id The coupon ID.
			 * @param \Masteriyo\Addons\Coupons\Models\Coupon $object The coupon object.
			 */
			do_action( 'masteriyo_before_delete_' . $object_type, $id, $coupon );

			wp_delete_post( $id, true );
			$coupon->set_id( 0 );

			/**
			 * Fires after deleting a coupon.
			 *
			 * @since 2.5.12
			 *
			 * @param integer $id The coupon ID.
			 * @param \Masteriyo\Addons\Coupons\Models\Coupon $object The coupon object.
			 */
			do_action( 'masteriyo_after_delete_' . $object_type, $id, $coupon );
		} else {
			/**
			 * Fires before moving a coupon to trash.
			 *
			 * @since 2.5.12
			 *
			 * @param integer $id The coupon ID.
			 * @param \Masteriyo\Addons\Coupons\Models\Coupon $object The coupon object.
			 */
			do_action( 'masteriyo_before_trash_' . $object_type, $id, $coupon );

			wp_trash_post( $id );
			$coupon->set_status( PostStatus::TRASH );

			/**
			 * Fires after moving a coupon to trash.
			 *
			 * @since 2.5.12
			 *
			 * @param integer $id The coupon ID.
			 * @param \Masteriyo\Addons\Coupons\Models\Coupon $object The coupon object.
			 */
			do_action( 'masteriyo_after_trash_' . $object_type, $id, $coupon );
		}
	}

	/**
	 * Read coupon data. Can be overridden by child classes to load other props.
	 *
	 * @since 2.5.12
	 *
	 * @param Coupon $coupon Coupon object.
	 */
	protected function read_coupon_data( &$coupon ) {
		$id          = $coupon->get_id();
		$meta_values = $this->read_meta( $coupon );

		$set_props = array();

		$meta_values = array_reduce(
			$meta_values,
			function( $result, $meta_value ) {
				$result[ $meta_value->key ][] = $meta_value->value;
				return $result;
			},
			array()
		);

		foreach ( $this->internal_meta_keys as $prop => $meta_key ) {
			$meta_value         = isset( $meta_values[ $meta_key ][0] ) ? $meta_values[ $meta_key ][0] : null;
			$set_props[ $prop ] = maybe_unserialize( $meta_value ); // get_post_meta only unserializes single values.
		}

		$coupon->set_props( $set_props );
	}

	/**
	 * Read extra data associated with the coupon, like button text or coupon URL for external coupons.
	 *
	 * @since 2.5.12
	 *
	 * @param Coupon $coupon Coupon object.
	 */
	protected function read_extra_data( &$coupon ) {
		$meta_values = $this->read_meta( $coupon );

		foreach ( $coupon->get_extra_data_keys() as $key ) {
			$function = 'set_' . $key;

			if ( is_callable( array( $coupon, $function ) )
				&& isset( $meta_values[ '_' . $key ] ) ) {
				$coupon->{$function}( $meta_values[ '_' . $key ] );
			}
		}
	}

	/**
	 * Fetch coupons.
	 *
	 * @since 2.5.12
	 *
	 * @param array $query_vars Query vars.
	 * @return \Masteriyo\Addons\Coupons\Models\Coupon[]
	 */
	public function query( $query_vars ) {
		$args = $this->get_wp_query_args( $query_vars );

		if ( ! empty( $args['errors'] ) ) {
			$query = (object) array(
				'posts'         => array(),
				'found_posts'   => 0,
				'max_num_pages' => 0,
			);
		} else {
			$query = new \WP_Query( $args );
		}

		if ( isset( $query_vars['return'] ) && 'objects' === $query_vars['return'] && ! empty( $query->posts ) ) {
			// Prime caches before grabbing objects.
			update_post_caches( $query->posts, array( PostType::COUPON ) );
		}

		$coupons = ( isset( $query_vars['return'] ) && 'ids' === $query_vars['return'] ) ? $query->posts : array_filter( array_map( 'masteriyo_get_coupon', $query->posts ) );

		if ( isset( $query_vars['paginate'] ) && $query_vars['paginate'] ) {
			return (object) array(
				'coupons'       => $coupons,
				'total'         => $query->found_posts,
				'max_num_pages' => $query->max_num_pages,
			);
		}

		return $coupons;
	}

	/**
	 * Get valid WP_Query args from a CouponQuery's query variables.
	 *
	 * @since 2.5.12
	 * @param array $query_vars Query vars from a CouponQuery.
	 * @return array
	 */
	protected function get_wp_query_args( $query_vars ) {
		// Map query vars to ones that get_wp_query_args or WP_Query recognize.
		$key_mapping = array(
			'status' => 'post_status',
			'page'   => 'paged',
		);

		foreach ( $key_mapping as $query_key => $db_key ) {
			if ( isset( $query_vars[ $query_key ] ) ) {
				$query_vars[ $db_key ] = $query_vars[ $query_key ];
				unset( $query_vars[ $query_key ] );
			}
		}

		$query_vars['post_type'] = PostType::COUPON;

		$wp_query_args = parent::get_wp_query_args( $query_vars );

		if ( ! isset( $wp_query_args['date_query'] ) ) {
			$wp_query_args['date_query'] = array();
		}
		if ( ! isset( $wp_query_args['meta_query'] ) ) {
			$wp_query_args['meta_query'] = array(); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
		}

		// Handle date queries.
		$date_queries = array(
			'created_at'  => 'post_date',
			'modified_at' => 'post_modified',
		);
		foreach ( $date_queries as $query_var_key => $db_key ) {
			if ( isset( $query_vars[ $query_var_key ] ) && '' !== $query_vars[ $query_var_key ] ) {

				// Remove any existing meta queries for the same keys to prevent conflicts.
				$existing_queries = wp_list_pluck( $wp_query_args['meta_query'], 'key', true );
				foreach ( $existing_queries as $query_index => $query_contents ) {
					unset( $wp_query_args['meta_query'][ $query_index ] );
				}

				$wp_query_args = $this->parse_date_for_wp_query( $query_vars[ $query_var_key ], $db_key, $wp_query_args );
			}
		}

		// Handle paginate.
		if ( ! isset( $query_vars['paginate'] ) || ! $query_vars['paginate'] ) {
			$wp_query_args['no_found_rows'] = true;
		}

		// Handle orderby.
		if ( isset( $query_vars['orderby'] ) && 'include' === $query_vars['orderby'] ) {
			$wp_query_args['orderby'] = 'post__in';
		}

		/**
		 * Filters WP Query args for coupon post type query.
		 *
		 * @since 2.5.12
		 *
		 * @param array $wp_query_args WP Query args.
		 * @param array $query_vars Query vars.
		 * @param \Masteriyo\Addons\Coupons\Repository\CouponRepository $repository Coupon repository object.
		 */
		return apply_filters( 'masteriyo_coupon_wp_query_args', $wp_query_args, $query_vars, $this );
	}

	/**
	 * Get the number of uses for a coupon by user ID.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @param integer $user_id User ID.
	 *
	 * @return integer
	 */
	public function get_usage_count_by_user( $coupon, $user_id ) {
		global $wpdb;

		$usage_count = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT( meta_id ) FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_coupon_used_by' AND meta_value = %d;",
				$coupon->get_id(),
				$user_id
			)
		);
		$usage_count = absint( $usage_count );

		/**
		 * Filters coupon usage count by a user.
		 *
		 * @since 2.5.12
		 *
		 * @param integer $usage_count
		 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon
		 * @param integer $usage_count
		 */
		return apply_filters( 'masteriyo_coupon_usage_count_by_user', $usage_count, $coupon, $user_id );
	}

	/**
	 * Increase usage count for current coupon.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @param string $used_by Either user ID or billing email.
	 *
	 * @return integer New usage count.
	 */
	public function increase_usage_count( &$coupon, $used_by ) {
		$new_count = $this->update_usage_count_meta( $coupon, 'increase' );

		if ( $used_by ) {
			$this->add_coupon_used_by( $coupon, $used_by );
		}

		/**
		 * Fires after increasing coupon usage count.
		 *
		 * @since 2.5.12
		 *
		 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
		 * @param integer $new_count New coupon usage count.
		 * @param string $used_by Either user ID or billing email.
		 */
		do_action( 'masteriyo_increase_coupon_usage_count', $coupon, $new_count, $used_by );

		return $new_count;
	}

	/**
	 * Helper function to add a `_coupon_used_by` record to track coupons used by the user.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @param string $used_by Either user ID or billing email.
	 */
	protected function add_coupon_used_by( $coupon, $used_by ) {
		add_post_meta( $coupon->get_id(), '_coupon_used_by', strtolower( $used_by ) );
	}

	/**
	 * Decrease usage count for current coupon.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @param string $used_by Either user ID or billing email.
	 *
	 * @return integer New usage count.
	 */
	public function decrease_usage_count( &$coupon, $used_by ) {
		global $wpdb;

		$new_count = $this->update_usage_count_meta( $coupon, 'decrease' );

		if ( $used_by ) {
			/**
			 * We're doing this the long way because `delete_post_meta( $id, $key, $value )` deletes
			 * all instances where the key and value match, and we only want to delete one.
			 */
			$meta_id = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_coupon_used_by' AND meta_value = %s AND post_id = %d LIMIT 1;",
					$used_by,
					$coupon->get_id()
				)
			);

			if ( $meta_id ) {
				delete_metadata_by_mid( 'post', $meta_id );
			}
		}

		/**
		 * Fires after decreasing coupon usage count.
		 *
		 * @since 2.5.12
		 *
		 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
		 * @param integer $new_count New coupon usage count.
		 * @param string $used_by Either user ID or billing email.
		 */
		do_action( 'masteriyo_decrease_coupon_usage_count', $coupon, $new_count, $used_by );

		return $new_count;
	}

	/**
	 * Increase or decrease the usage count for a coupon by 1.
	 *
	 * @since 2.5.12
	 *
	 * @param \Masteriyo\Addons\Coupons\Models\Coupon $coupon Coupon object.
	 * @param string $operation 'increase' or 'decrease'.
	 *
	 * @return integer New usage count
	 */
	protected function update_usage_count_meta( &$coupon, $operation = 'increase' ) {
		global $wpdb;

		$coupon_id = $coupon->get_id();
		$operator  = 'increase' === $operation ? '+' : '-';
		$sql       = "UPDATE $wpdb->postmeta SET meta_value = meta_value {$operator} 1 WHERE meta_key = '_usage_count' AND post_id = %d;";

		add_post_meta( $coupon_id, '_usage_count', $coupon->get_usage_count( 'edit' ), true );
		$wpdb->query( $wpdb->prepare( $sql, $coupon_id ) );// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

		// Get the latest value direct from the DB, instead of possibly the WP meta cache.
		$new_count = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = '_usage_count' AND post_id = %d;", $coupon_id ) );

		return absint( $new_count );
	}
}
