<?php
/**
 * This class manage the data store of exclusion list
 *
 * @package YITH\DynamicPricingAndDiscounts\Classes
 */

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

/**
 * Class that manage the query for the exclusion table
 */
class YWDPD_Exclusion_List_Data_Store {
	/**
	 * The table name
	 *
	 * @var string
	 */
	protected static $table_name = 'ywdpd_exclusion_list_table';

	/**
	 * Add new row in the table
	 *
	 * @param int    $term_id the term id.
	 * @param string $term_type the term type.
	 *
	 * @since 3.0.0
	 */
	public static function insert( $term_id, $term_type ) {
		global $wpdb;

		$args = array(
			'term_id'   => $term_id,
			'term_type' => $term_type,
		);
		if ( ! self::is_exist( $term_id, $term_type ) ) {
			$wpdb->insert( $wpdb->prefix . self::$table_name, $args, array( '%d', '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB,DirectDatabaseQuerySniff.NoCaching
			do_action( 'ywdpd_after_insert_in_exclusion', $term_id, $term_type );
		}
	}

	/**
	 * Check if a term exist in the table
	 *
	 * @param int    $term_id The term id.
	 * @param string $term_type The term type.
	 *
	 * @return bool
	 * @since 3.0.0
	 */
	public static function is_exist( $term_id, $term_type ) {

		global $wpdb;
		$tabla_name = $wpdb->prefix . self::$table_name;
		$query      = "SELECT COUNT(ID) FROM {$tabla_name} WHERE term_id = %d AND term_type = %s;";

		$query = $wpdb->prepare( $query, $term_id, $term_type ); // phpcs:ignore  WordPress.DB.PreparedSQL.NotPrepared

		return $wpdb->get_var( $query ) > 0; // phpcs:ignore WordPress.DB,DirectDatabaseQuerySniff.NoCaching
	}

	/**
	 * Check if the table is empty
	 *
	 * @return bool
	 * @since 3.0.0
	 */
	public static function has_items() {

		global $wpdb;
		$tabla_name = $wpdb->prefix . self::$table_name;
		$query      = "SELECT COUNT(ID) FROM {$tabla_name}";

		return $wpdb->get_var( $query ) > 0; // phpcs:ignore WordPress.DB,DirectDatabaseQuerySniff.NoCaching
	}

	/**
	 * Get all terms by type
	 *
	 * @param string $term_type The term type.
	 *
	 * @return array|null
	 * @since 3.0.0
	 */
	public static function get_terms_by_type( $term_type ) {
		global $wpdb;
		$tabla_name = $wpdb->prefix . self::$table_name;
		$query      = "SELECT term_id FROM {$tabla_name} WHERE term_type = %s;";
		$query      = $wpdb->prepare( $query, $term_type ); // phpcs:ignore  WordPress.DB.PreparedSQL.NotPrepared

		return $wpdb->get_col( $query ); // phpcs:ignore WordPress.DB,DirectDatabaseQuerySniff.NoCaching
	}

	/**
	 * Delete an item in the table
	 *
	 * @param int $term_id The item to delete.
	 *
	 * @since 3.0.0
	 */
	public static function delete( $term_id ) {

		global $wpdb;

		$wpdb->delete( $wpdb->prefix . self::$table_name, array( 'term_id' => $term_id ) );// phpcs:ignore WordPress.DB,DirectDatabaseQuerySniff.NoCaching
		do_action( 'ywdpd_after_delete_in_exclusion', $term_id );
	}
}
