<?php
if (! defined('ABSPATH')) {
    exit;
} class PufferGo_Product_Settings
{
    public const PAGE_SLUG = 'puffergo-product-settings';

    public const OPTION_PRODUCT_ORDERBY = 'puffergo_product_default_orderby';

    public const OPTION_CATEGORY_ORDERBY = 'puffergo_product_cat_orderby';

    public const NONCE_ACTION = 'puffergo_save_product_settings';

    public function __construct()
    {
        add_action('admin_init', array($this, 'maybe_save_settings'));
        add_action('pre_get_posts', array($this, 'apply_default_orderby'));
        add_filter('posts_clauses', array($this, 'apply_featured_sort'), 10, 2);
    }

    private function is_target_query($query)
    {
        if (defined('REST_REQUEST') && REST_REQUEST) {
            return false;
        }

if (function_exists('wp_is_serving_rest_request') && wp_is_serving_rest_request()) {
            return false;
        }

if (is_admin()) {
            return false;
        }

if (! $query->is_main_query()) {
            return false;
        }

return $query->is_post_type_archive('puffergo_product') || $query->is_tax('puffergo_product_cat');
    }

    public function apply_default_orderby($query)
    {
        if (! $this->is_target_query($query)) {
            return;
        } $query->set('posts_per_page', 12);
        $orderby = get_option(self::OPTION_PRODUCT_ORDERBY, 'date');

        if ('title' === $orderby) {
            $query->set('orderby', 'title');
            $query->set('order', 'ASC');
        } elseif ('date_asc' === $orderby) {
            $query->set('orderby', 'date');
            $query->set('order', 'ASC');
        } else {
            $query->set('orderby', 'date');
            $query->set('order', 'DESC');
        }
    }

    public function apply_featured_sort($clauses, $query)
    {
        if (! $this->is_target_query($query)) {
            return $clauses;
        } global $wpdb;
        $clauses['join'] .= $wpdb->prepare(" LEFT JOIN {$wpdb->postmeta} AS puffergo_featured_meta ON ( puffergo_featured_meta.post_id = {$wpdb->posts}.ID AND puffergo_featured_meta.meta_key = %s )", '_puffergo_featured');
        $featured_order = "( CASE WHEN puffergo_featured_meta.meta_value = '1' THEN 0 ELSE 1 END )";
        $clauses['orderby'] = trim($featured_order . ' ASC' . ($clauses['orderby'] ? ', ' . $clauses['orderby'] : ''));

        return $clauses;
    }

    public function maybe_save_settings()
    {
        if (! isset($_POST['puffergo_product_settings_submit'])) {
            return;
        }

if (! current_user_can('manage_options')) {
            return;
        } check_admin_referer(self::NONCE_ACTION);
        $product_orderby = isset($_POST[ self::OPTION_PRODUCT_ORDERBY ]) ? sanitize_text_field(wp_unslash($_POST[ self::OPTION_PRODUCT_ORDERBY ])) : 'date';

        if (! in_array($product_orderby, array('date', 'date_asc', 'title'), true)) {
            $product_orderby = 'date';
        } $category_orderby = isset($_POST[ self::OPTION_CATEGORY_ORDERBY ]) ? sanitize_text_field(wp_unslash($_POST[ self::OPTION_CATEGORY_ORDERBY ])) : 'name';

        if (! in_array($category_orderby, array('manual', 'name', 'count'), true)) {
            $category_orderby = 'name';
        } update_option(self::OPTION_PRODUCT_ORDERBY, $product_orderby);
        update_option(self::OPTION_CATEGORY_ORDERBY, $category_orderby);
        add_action('admin_notices', array($this, 'render_saved_notice'));
    }

    public function render_saved_notice()
    { ?>
		<div class="notice notice-success is-dismissible">
			<p><?php esc_html_e('Product settings saved.', 'puffergo'); ?></p>
		</div>
		<?php
    }

    public static function render_page()
    {
        if (! current_user_can('manage_options')) {
            return;
        } $product_orderby = get_option(self::OPTION_PRODUCT_ORDERBY, 'date');
        $category_orderby = get_option(self::OPTION_CATEGORY_ORDERBY, 'name'); ?>
		<div class="wrap">
			<h1><?php esc_html_e('Product Settings', 'puffergo'); ?></h1>

			<form method="post" action="">
				<?php wp_nonce_field(self::NONCE_ACTION); ?>

				<table class="form-table" role="presentation">
					<tbody>
						<tr>
							<th scope="row">
								<label for="puffergo_product_cat_orderby"><?php esc_html_e('Default category order', 'puffergo'); ?></label>
							</th>
							<td>
								<select name="<?php echo esc_attr(self::OPTION_CATEGORY_ORDERBY); ?>" id="puffergo_product_cat_orderby">
									<option value="name" <?php selected($category_orderby, 'name'); ?>>
										<?php esc_html_e('Name (A–Z)', 'puffergo'); ?>
									</option>
									<option value="count" <?php selected($category_orderby, 'count'); ?>>
										<?php esc_html_e('Product count (most first)', 'puffergo'); ?>
									</option>
									<option value="manual" <?php selected($category_orderby, 'manual'); ?>>
										<?php esc_html_e('Manual (custom order value)', 'puffergo'); ?>
									</option>
								</select>
								<p class="description">
									<?php esc_html_e('Manual order is set per-category on the Product Categories edit screen.', 'puffergo'); ?>
								</p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="puffergo_product_default_orderby"><?php esc_html_e('Default product order', 'puffergo'); ?></label>
							</th>
							<td>
								<select name="<?php echo esc_attr(self::OPTION_PRODUCT_ORDERBY); ?>" id="puffergo_product_default_orderby">
									<option value="date" <?php selected($product_orderby, 'date'); ?>>
										<?php esc_html_e('Publish date (newest first)', 'puffergo'); ?>
									</option>
									<option value="date_asc" <?php selected($product_orderby, 'date_asc'); ?>>
										<?php esc_html_e('Publish date (oldest first)', 'puffergo'); ?>
									</option>
									<option value="title" <?php selected($product_orderby, 'title'); ?>>
										<?php esc_html_e('Title (A–Z)', 'puffergo'); ?>
									</option>
								</select>
								<p class="description">
									<?php esc_html_e('Featured products (starred in the product list) are always shown first, regardless of this setting.', 'puffergo'); ?>
								</p>
							</td>
						</tr>
					</tbody>
				</table>

				<?php submit_button(__('Save Settings', 'puffergo'), 'primary', 'puffergo_product_settings_submit'); ?>
			</form>
		</div>
		<?php
    }
}
