<?php

namespace Fab\Controller;

use Fab\Interfaces\JIT_Interface;

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

/**
 * WC Quick Purchase Editor
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class WC_Quick_Purchase_Editor extends WC_Quick_Purchase_Type implements JIT_Interface {

    /**
     * Save Metabox Data.
     *
     * @param int    $post_id Post ID.
     * @param object $post Post object.
     * @param bool   $update Whether the post is being updated.
     * @return void
     */
    public function save_metabox_data( $post_id, $post, $update ) {
        $params = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing
        $type   = isset( $params['fab_setting_type'] ) ? sanitize_text_field( wp_unslash( $params['fab_setting_type'] ) ) : '';

        // If type is not post recommendation, return.
        if ( $this->type !== $type ) {
            return;
        }

        // Save post quick purchase action.
        $post_meta = $this->post_meta['action'];
        $action    = isset( $params['fab_setting_woocommerce_quick_purchase'] ) ? sanitize_text_field( wp_unslash( $params['fab_setting_woocommerce_quick_purchase'] ) ) : $post_meta['default'];
        update_post_meta( $post_id, $post_meta['meta_key'], $action );

        // Save post quick purchase product.
        $post_meta = $this->post_meta['product'];
        $product   = isset( $params['fab_setting_woocommerce_quick_purchase_product'] ) ? intval( $params['fab_setting_woocommerce_quick_purchase_product'] ) : $post_meta['default'];
        update_post_meta( $post_id, $post_meta['meta_key'], $product );
    }

    /**
     * Add fab metabox setting tabs fields.
     *
     * @param array $tabs The tabs.
     * @param array $fab The fab.
     * @return array
     */
    public function add_fab_metabox_setting_tabs_fields( $tabs, $fab ) {
        // Set quick purchase field.
        $tabs['setting']['fields']['quick_purchase'] = array(
            'type'       => 'select',
            'name'       => 'fab_setting_woocommerce_quick_purchase',
            'label'      => __( 'Action', 'floating-awesome-button' ),
            'tooltip'    => __( 'Action for quick purchase', 'floating-awesome-button' ),
            'value'      => get_post_meta( $fab['ID'], $this->post_meta['action']['meta_key'], true ),
            'options'    => array(
                array(
                    'id'   => 'fab_add_to_cart',
                    'text' => __( 'Add to Cart', 'floating-awesome-button' ),
                ),
                array(
                    'id'   => 'fab_buy_now',
                    'text' => __( 'Buy Now', 'floating-awesome-button' ),
                ),
            ),
            'visible_if' => array(
                array(
                    'tab'      => 'setting',
                    'field'    => 'type',
                    'operator' => '==',
                    'value'    => $this->type,
                ),
            ),
        );

        // Set product field.
        $product_id = get_post_meta( $fab['ID'], $this->post_meta['product']['meta_key'], true );
        $product    = wc_get_product( $product_id );
        $tabs['setting']['fields']['quick_purchase_product'] = array(
            'type'        => 'select',
            'name'        => 'fab_setting_woocommerce_quick_purchase_product',
            'label'       => __( 'Default Product', 'floating-awesome-button' ),
            'info'        => __( 'Choose a product that will be used when the quick purchase button appears outside of product pages. If left empty, the button will only be shown on product pages.', 'floating-awesome-button' ),
            'placeholder' => __( 'Search for a product...', 'floating-awesome-button' ),
            'value'       => $product ? $product->get_id() : '',
            'options'     => $product ? array(
                array(
                    'id'   => $product->get_id(),
                    'text' => sprintf( '%s #%s (%s)', $product->get_name(), $product->get_id(), 'product' ),
                ),
            ) : array(),
            'select2'     => array(
                'allowClear'         => true,
                'minimumInputLength' => 3,
                'ajax'               => array(
                    'url'            => admin_url( 'admin-ajax.php' ),
                    'action'         => 'fab_search_products',
                    'dataType'       => 'json',
                    'delay'          => 250,
                    'processResults' => true,
                    'cache'          => true,
                ),
            ),
            'visible_if'  => array(
                array(
                    'tab'      => 'setting',
                    'field'    => 'type',
                    'operator' => '==',
                    'value'    => $this->type,
                ),
            ),
        );

        return $tabs;
    }

    /**
     * Filter the FAB post row action url.
     *
     * @param string $url The url.
     * @param string $type The type of FAB.
     * @param object $post The post.
     */
    public function filter_fab_post_row_action_url( $url, $type, $post ) {
        if ( 'quick_purchase' === $type ) {
            // Get recent product.
            $args     = array(
                'post_type'      => 'product',
                'posts_per_page' => 1,
            );
            $products = get_posts( $args );

            // If no product, return.
            if ( empty( $products ) ) {
                return $url;
            }

            // Get product permalink.
            return get_permalink( $products[0]->ID );
        }

        return $url;
    }

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

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

        // Save Metabox Data.
        add_action( 'fab_save_post', array( __CLASS__, 'jit_save_metabox_data' ), 10, 3 );

        // Add fab metabox setting tabs fields.
        add_filter( 'fab_metabox_setting_tabs', array( __CLASS__, 'jit_add_fab_metabox_setting_tabs_fields' ), 10, 2 );

        // Filter FAB post row action url.
        add_filter( 'fab_post_row_action_preview_url', array( __CLASS__, 'jit_filter_fab_post_row_action_url' ), 10, 3 );
    }
}
