<?php

/**
 * Product Validation Service
 *
 * @package ArraySubs\Features\SubscriptionProducts\Services
 */

namespace ArraySubs\Features\SubscriptionProducts\Services;

defined('ABSPATH') || exit;

/**
 * Validate subscription product settings
 */
class Validation
{
    /**
     * Enable auto-loading
     *
     * @var bool
     */
    public static $loadable = true;

    /**
     * Constructor
     */
    public function __construct()
    {
        add_filter('woocommerce_product_data_store_cpt_get_products_query', [$this, 'handleCustomQuery'], 10, 2);
    }

    /**
     * Validate product before saving
     *
     * @param \WC_Product       $product  Product object
     * @param \WC_Data_Store_WP $data_store Data store object
     */
    public function validateBeforeSave($product, $data_store): void
    {
        $product_id = $product->get_id();

        if (!$product_id) {
            return;
        }

        $is_subscription = get_post_meta($product_id, '_is_subscription', true);

        if ($is_subscription !== 'yes') {
            return;
        }

        // Validate product has a regular price (used as subscription price)
        $regular_price = $product->get_regular_price();
        if (empty($regular_price) || $regular_price <= 0) {
            $this->addValidationError(__('Subscription products must have a valid regular price greater than zero.', 'arraysubs'));
        }

        // Validate billing interval (skip for lifetime period)
        $subscription_period = get_post_meta($product_id, '_subscription_period', true);
        if ($subscription_period !== 'lifetime') {
            $billing_interval = get_post_meta($product_id, '_subscription_interval', true);
            if (empty($billing_interval) || $billing_interval < 1 || $billing_interval > 12) {
                $this->addValidationError(__('Billing interval must be between 1 and 12.', 'arraysubs'));
            }
        }

        // Validate renewal price if enabled
        $enable_renewal_price = get_post_meta($product_id, '_enable_renewal_price', true);
        if ($enable_renewal_price === 'yes') {
            $renewal_price = get_post_meta($product_id, '_renewal_price', true);
            if (empty($renewal_price) || $renewal_price <= 0) {
                $this->addValidationError(__('If different renewal price is enabled, you must set a valid renewal price.', 'arraysubs'));
            }

            $renewal_price_after = get_post_meta($product_id, '_renewal_price_after', true);
            if (empty($renewal_price_after) || $renewal_price_after < 1) {
                $this->addValidationError(__('Renewal price after period must be at least 1.', 'arraysubs'));
            }
        }
    }

    /**
     * Add validation error notice
     *
     * @param string $message Error message
     */
    private function addValidationError(string $message): void
    {
        add_action('admin_notices', function () use ($message) {
?>
            <div class="notice notice-error is-dismissible">
                <p><strong><?php esc_html_e('Subscription Product Error:', 'arraysubs'); ?></strong> <?php echo esc_html($message); ?></p>
            </div>
<?php
        });
    }

    /**
     * Handle custom product queries
     *
     * @param array $query      Query arguments
     * @param array $query_vars Query variables
     * @return array Modified query
     */
    public function handleCustomQuery(array $query, array $query_vars): array
    {
        // Add support for querying subscription products
        if (!empty($query_vars['is_subscription'])) {
            $query['meta_query'][] = [
                'key'     => '_is_subscription',
                'value'   => 'yes',
                'compare' => '=',
            ];
        }

        return $query;
    }
}
