<?php
/**
 * Product Lists class file.
 *
 * @package WholesaleNode_For_WooCommerce
 */

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

/**
 * Product Lists data access.
 */
class WOOWSNFree_Product_Lists {

	private static $_instance = null;

	/**
	 * @return self
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	private function __construct() {
	}

	/**
	 * Get all active product lists.
	 *
	 * @return array
	 */
	public static function get_all() {
		global $wpdb;
		$table = $wpdb->prefix . 'woowsn_product_lists';

		$cache_key = 'woowsn_free_active_product_lists';
		$cached    = wp_cache_get( $cache_key, 'woowsn_free' );
		if ( false !== $cached ) {
			return $cached;
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		$results = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE status = %s ORDER BY title ASC', $table, 'active' ) );

		wp_cache_set( $cache_key, $results, 'woowsn_free', 5 * MINUTE_IN_SECONDS );

		return $results;
	}

	/**
	 * Get product IDs for a specific list.
	 *
	 * @param int $list_id List ID.
	 * @return int[]
	 */
	public static function get_product_ids( $list_id ) {
		global $wpdb;
		$list_id = absint( $list_id );
		if ( ! $list_id ) {
			return array();
		}

		$cache_key = 'woowsn_free_product_list_ids_' . $list_id;
		$cached    = wp_cache_get( $cache_key, 'woowsn_free' );
		if ( false !== $cached ) {
			return (array) $cached;
		}

		$table = $wpdb->prefix . 'woowsn_product_lists';
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
		$row = $wpdb->get_row(
			$wpdb->prepare( 'SELECT product_ids FROM %i WHERE id = %d AND status = %s', $table, $list_id, 'active' ),
			ARRAY_A
		);

		if ( ! $row ) {
			wp_cache_set( $cache_key, array(), 'woowsn_free', 5 * MINUTE_IN_SECONDS );
			return array();
		}

		$ids = json_decode( $row['product_ids'], true );
		$ids = is_array( $ids ) ? array_map( 'intval', $ids ) : array();

		wp_cache_set( $cache_key, $ids, 'woowsn_free', 5 * MINUTE_IN_SECONDS );

		return $ids;
	}
}
