<?php
/**
 * Preview Filters Model
 *
 * @category   WordPress_Plugin
 * @package    Common
 * @subpackage Models
 * @author     miniOrange <info@miniorange.com>
 * @license    MIT/Expat
 * @link       https://plugins.miniorange.com/woocommerce-api-product-sync-with-woocommerce-rest-apis
 */

namespace MOWCPS\Common\Models;

use MOWCPS\Common\Interfaces\Model_Interface;
use MOWCPS\Common\Constants\Constants;
use WP_Error;
use MOWCPS\Common\Utils\Model_Utils;
use MOWCPS\Common\Services\Preview\Preview_Filter_Service;
if ( ! defined( 'ABSPATH' ) ) {
	die;
}

/**
 * Class Preview_Filters_Model
 *
 * Handles preview filter data operations for product preview functionality
 * Uses file-based storage for product IDs to avoid database size limits
 */
class Preview_Filters_Model implements Model_Interface {
	/**
	 * Preview filters table name
	 *
	 * @var string
	 */
	private static $preview_filters_table = Model_Utils::TABLE_PREVIEW_FILTERS;

	/**
	 * Get preview filter by supplier ID
	 *
	 * @param int $supplier_id The supplier ID.
	 * @return array|null Filter data or null if not found
	 */
	public static function get_by_supplier_id( $supplier_id ) {
		global $wpdb;

		$preview_filters_table = Model_Utils::get_table_name( self::$preview_filters_table );

		$result = $wpdb->get_row( //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom query.
			$wpdb->prepare(
				sprintf( 'SELECT * FROM `%s` WHERE supplier_id = %%d', esc_sql( $preview_filters_table ) ),
				$supplier_id
			),
			ARRAY_A
		);

		if ( ! $result ) {
			return null;
		}

		$result['filter_skus']    = Preview_Filter_Service::load_filter_from_file( $supplier_id );
		$result['is_revert_mode'] = (bool) $result['is_revert_mode'];
		$result['is_active']      = (bool) $result['is_active'];

		return $result;
	}

	/**
	 * Create new preview filter for supplier
	 *
	 * @param array $data The preview filter data.
	 * @return array|WP_Error Created filter data or error
	 */
	public static function create( $data ) {
		return self::upsert( $data );
	}

	/**
	 * Update preview filter for supplier
	 *
	 * @param string $supplier_uuid The supplier UUID (not used, uses supplier_id from data).
	 * @param array  $data The preview filter data.
	 * @return array|WP_Error Updated filter data or error
	 */
	public static function update( $supplier_uuid, $data ) {
		return self::upsert( $data );
	}

	/**
	 * Create or update preview filter for supplier
	 *
	 * @param array $data The preview filter data.
	 * @return array|WP_Error Created/updated filter data or error
	 */
	public static function upsert( $data ) {
		global $wpdb;

		if ( empty( $data['supplier_id'] ) ) {
			return new WP_Error(
				Constants::ERROR_MISSING_REQUIRED_FIELD,
				sprintf( Constants::MSG_MISSING_REQUIRED_FIELD, 'supplier_id' ),
				array( 'status' => Constants::HTTP_BAD_REQUEST )
			);
		}

		$supplier_id = intval( $data['supplier_id'] );

		if ( isset( $data['filter_skus'] ) && is_array( $data['filter_skus'] ) ) {
			if ( empty( $data['filter_skus'] ) ) {
				Preview_Filter_Service::delete_filter_file( $supplier_id );
			} else {
				$file_result = Preview_Filter_Service::save_filter_to_file( $supplier_id, $data['filter_skus'] );
				if ( is_wp_error( $file_result ) ) {
					return $file_result;
				}
			}
		}

		$existing = self::get_by_supplier_id( $supplier_id );

		$filter_data = array(
			'supplier_id'    => $supplier_id,
			'is_revert_mode' => isset( $data['is_revert_mode'] ) ? (bool) $data['is_revert_mode'] : false,
			'is_active'      => isset( $data['is_active'] ) ? (bool) $data['is_active'] : false,
		);

		$formats = array( '%d', '%d', '%d' );

		$preview_filters_table = Model_Utils::get_table_name( self::$preview_filters_table );

		if ( $existing ) {
			$result = $wpdb->update( //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom query.
				$preview_filters_table,
				$filter_data,
				array( 'supplier_id' => $supplier_id ),
				$formats,
				array( '%d' )
			);

			if ( false === $result ) {
				return new WP_Error(
					Constants::ERROR_DB_ERROR,
					sprintf( Constants::MSG_DB_ERROR, 'Failed to update preview filter.' ),
					array( 'status' => Constants::HTTP_INTERNAL_SERVER_ERROR )
				);
			}
		} else {
			$result = $wpdb->insert( //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom query.
				$preview_filters_table,
				$filter_data,
				$formats
			);

			if ( false === $result ) {
				return new WP_Error(
					Constants::ERROR_DB_ERROR,
					sprintf( Constants::MSG_DB_ERROR, 'Failed to create preview filter.' ),
					array( 'status' => Constants::HTTP_INTERNAL_SERVER_ERROR )
				);
			}
		}

		return self::get_by_supplier_id( $supplier_id );
	}

	/**
	 * Delete preview filter by supplier ID
	 *
	 * @param int $supplier_id The supplier ID.
	 * @return bool|WP_Error True on success, WP_Error on failure
	 */
	public static function delete_by_supplier_id( $supplier_id ) {
		global $wpdb;

		Preview_Filter_Service::delete_filter_file( $supplier_id );

		$preview_filters_table = Model_Utils::get_table_name( self::$preview_filters_table );

		$result = $wpdb->delete( //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom query.
			$preview_filters_table,
			array( 'supplier_id' => $supplier_id ),
			array( '%d' )
		);

		if ( false === $result ) {
			return new WP_Error(
				Constants::ERROR_DB_ERROR,
				sprintf( Constants::MSG_DB_ERROR, 'Failed to delete preview filter.' ),
				array( 'status' => Constants::HTTP_INTERNAL_SERVER_ERROR )
			);
		}

		return true;
	}

	/**
	 * Update preview filter status
	 *
	 * @param int  $supplier_id The supplier ID.
	 * @param bool $is_active The active status.
	 * @return bool|WP_Error True on success, WP_Error on failure
	 */
	public static function update_status( $supplier_id, $is_active ) {
		global $wpdb;

		$preview_filters_table = Model_Utils::get_table_name( self::$preview_filters_table );

		$result = $wpdb->update( //phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom query.
			$preview_filters_table,
			array( 'is_active' => (bool) $is_active ),
			array( 'supplier_id' => $supplier_id ),
			array( '%d' ),
			array( '%d' )
		);

		if ( false === $result ) {
			return new WP_Error(
				Constants::ERROR_DB_ERROR,
				sprintf( Constants::MSG_DB_ERROR, 'Failed to update preview filter status.' ),
				array( 'status' => Constants::HTTP_INTERNAL_SERVER_ERROR )
			);
		}

		return true;
	}

	/**
	 * Get all preview filters (not implemented for this model)
	 *
	 * @param array $args Query parameters.
	 * @return array Empty array as this method is not applicable.
	 */
	public static function get_all( $args = array() ) {
		// This method is not applicable for preview filters.
		return array();
	}

	/**
	 * Get filter by UUID (not implemented for this model)
	 *
	 * @param string $uuid The filter UUID.
	 * @return null Always returns null as preview filters don't have UUIDs.
	 */
	public static function get_by_uuid( $uuid ) {
		// This method is not applicable for preview filters as they don't have UUIDs.
		return null;
	}

	/**
	 * Delete filter by UUID (not implemented for this model)
	 *
	 * @param string $uuid The filter UUID.
	 * @return bool|WP_Error Always returns error as preview filters don't have UUIDs.
	 */
	public static function delete( $uuid ) {
		return new WP_Error(
			Constants::ERROR_INVALID_OPERATION,
			'Delete by UUID is not supported for preview filters. Use delete_by_supplier_id instead.',
			array( 'status' => Constants::HTTP_BAD_REQUEST )
		);
	}
}
