<?php

namespace Fab\Controller;

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

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

/**
 * Frontend controller for WooCommerce Apply Coupon
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class WC_Apply_Coupon_Frontend extends WC_Apply_Coupon_Type implements JIT_Interface {

    /**
     * Adds WooCommerce Features data to the FAB item instance.
     *
     * @param object $instance The FAB item instance.
     */
    public function add_fab_item_data( $instance ) {
        // Check if the FAB type is the same as the current type.
        if ( $this->type !== $instance->getType() ) {
            return;
        }

        // Make sure WC is fully loaded.
        if ( ! class_exists( 'WooCommerce' ) || ! did_action( 'wp_loaded' ) || ! function_exists( 'WC' ) || WC()->cart === null ) {
            return;
        }

        // Check if cart is empty.
        if ( WC()->cart->get_cart_contents_count() === 0 ) {
            $instance->setToBeDisplayed( false );
            return;
        }

        // Check if coupon exists.
        $coupon_id = get_post_meta( $instance->getID(), $this->post_metas['woocommerce_apply_coupon']['meta_key'], true );
        $coupon    = new \WC_Coupon( $coupon_id );
        if ( ! $coupon_id || ! $coupon || ! $coupon->is_valid() ) {
            $instance->setToBeDisplayed( false );
            return;
        }

        // Set link.
        $link = add_query_arg( 'fab_coupon_code', $coupon->get_code(), home_url( add_query_arg( null, null ) ) );
        $instance->setLink( $link );
        $instance->setLinkHref( true );

        // Set third party data.
        $instance->setThirdPartyData(
            array(
                'coupon_id'   => $coupon_id,
                'coupon_code' => $coupon->get_code(),
            )
        );
    }

    /*
    |--------------------------------------------------------------------------
    | 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;
        }

        // Add fab item data.
        add_action( 'fab_item_data', array( __CLASS__, 'jit_add_fab_item_data' ), 10, 1 );
    }
}
