<?php

namespace Fab\Controller;

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

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

/**
 * Plugin hooks in a backend
 * setComponent
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class WC_Apply_Coupon_Template extends WC_Apply_Coupon_Type implements JIT_Interface {

    /**
     * Filter template title.
     *
     * @template
     *
     * @param string $title Title.
     * @param string $type Type.
     * @param object $data Data.
     * @return string
     */
    public function filter_template_title( $title, $type, $data ) {
        if ( $this->type !== $type || ! isset( $data->coupon_id ) ) {
            return $title;
        }

        // Get coupon title.
        $coupon = get_post( $data->coupon_id );
        if ( $coupon ) {
            // translators: %s will be replaced coupon title.
            $title = sprintf( __( 'Apply %s Coupon', 'floating-awesome-button' ), $coupon->post_title );
        }

        return $title;
    }

    /**
     * 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.
        if ( ! class_exists( 'WooCommerce' ) || $this->type !== $type ) {
            return $postmeta;
        }

        // Check if coupon id is set.
        if ( isset( $data->coupon_id ) ) {
            $postmeta['fab_setting_woocommerce_apply_coupon'] = $data->coupon_id;
        } else {
            // Get recent coupon.
            $coupons = get_posts(
                array(
                    'post_type'      => 'shop_coupon',
                    'posts_per_page' => 1,
                    'orderby'        => 'date',
                    'order'          => 'DESC',
                )
            );

            // If coupon exists, set the postmeta.
            if ( ! empty( $coupons ) ) {
                $postmeta['fab_setting_woocommerce_apply_coupon'] = $coupons[0]->ID;
            }
        }

        return $postmeta;
    }

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

    /**
     * JIT Method.
     *
     * @return void
     */
    public static function jit() {
        // Prevent error if plugin is not active.
        if ( ! FAB_WOOCOMMERCE_PLUGIN_ACTIVE ) {
            return;
        }

        // Filter template title.
        add_filter( 'fab_template_title', array( __CLASS__, 'jit_filter_template_title' ), 10, 3 );

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