<?php

namespace Fab\Controller;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Fab\Interfaces\JIT_Interface;
use Fab\Metabox\FABMetaboxSetting;

/**
 * Featured Product Template.
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class WC_Featured_Product_Template extends WC_Featured_Product_Type implements JIT_Interface {

    /**
     * Filter the FAB template to postmeta.
     *
     * @param array  $postmeta The postmeta.
     * @param string $type The type of FAB.
     * @param object $data The data.
     */
    public function filter_template_postmeta( $postmeta, $type, $data ) {
        // Check if woocommerce is active and type is featured product.
        if ( ! class_exists( 'WooCommerce' ) || 'featured_product' !== $type ) {
            return $postmeta;
        }

        // Check if product id is set.
        if ( isset( $data->product_id ) ) {
            $postmeta['fab_setting_woocommerce_featured_product'] = $data->product_id;
        } else {
            // Get product with most sales.
            $args     = array(
                'post_type'      => 'product',
                'meta_key'       => 'total_sales',
                'orderby'        => 'meta_value_num',
                'order'          => 'DESC',
                'posts_per_page' => 1,
            );
            $products = get_posts( $args );

            // If there no sales, get recent product.
            if ( ! $products ) {
                $args     = array(
                    'post_type'      => 'product',
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                    'posts_per_page' => 1,
                );
                $products = get_posts( $args );
            }

            // Get product ID.
            if ( ! empty( $products ) ) {
                $postmeta['fab_setting_woocommerce_featured_product'] = $products[0]->ID;
            }
        }

        return $postmeta;
    }

    /*
    |--------------------------------------------------------------------------
    | Fulfill implemented interface contracts
    |--------------------------------------------------------------------------
     */

    /**
     * JIT Method.
     *
     * @return void
     */
    public static function jit() {

        /**
         * |--------------------------------------------------------------------------
         * | WOOCOMMERCE HOOKS
         * | - Prevent error if woocommerce plugin is not active.
         * |--------------------------------------------------------------------------
         */
        if ( ! FAB_WOOCOMMERCE_PLUGIN_ACTIVE ) {
            return;
        }

        // @backend - Filter template postmeta.
        add_filter( 'fab_template_postmeta', array( __CLASS__, 'jit_filter_template_postmeta' ), 10, 3 );
    }
}
