<?php

namespace Fab\Helper\WooCommerce;

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

/**
 * WooCommerce Coupon Helper
 *
 * @package    Fab
 * @subpackage Fab/Helper/WooCommerce
 */
class Coupon {

    // Load traits.
    use \Fab\Plugin\Helper\Singleton;

    /**
     * Search FAB item by coupon ID.
     *
     * @param int $coupon_id The coupon ID.
     * @return \Fab\Helper\FABItem|null The FAB item.
     */
    public function search_fab_by_coupon_id( $coupon_id ) {
        $apply_coupon_type = \Fab\Controller\WC_Apply_Coupon_Type::get_instance();
        $fab_posts         = get_posts(
            array(
                'post_type'      => 'fab',
                'posts_per_page' => 1,
                'meta_query'     => array(
                    array(
                        'key'   => $apply_coupon_type->post_metas['woocommerce_apply_coupon']['meta_key'],
                        'value' => $coupon_id,
                    ),
                ),
            )
        );
        if ( empty( $fab_posts ) ) {
            return null;
        }
        return new \Fab\Helper\FABItem( $fab_posts[0]->ID );
    }
}
