<?php

/**
 * The frontend-specific functionality of the plugin.
 *
 * @since      1.0.0
 * @package    DevNajmusOneClickOrderPopup
 * @subpackage  DevNajmusOneClickOrderPopup/includes
 */

if (!defined('WPINC')) {
    die;
}

/**
 * The frontend-specific functionality of the plugin.
 */
class DOPW_Frontend
{

    /**
     * Initialize the class.
     *
     * @return void
     */
    public function init()
    {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_footer', array($this, 'render_popup_template'));

        // Add Quick Order buttons
        add_action('woocommerce_after_shop_loop_item', array($this, 'add_shop_quick_order_button'), 15);
        add_action('woocommerce_after_add_to_cart_button', array($this, 'add_single_quick_order_button'), 15);
    }

    /**
     * Return an array of available gateways for JS consumption.
     *
     * @return array
     */
    private function get_gateways_for_js()
    {
        $out = array();
        if (!function_exists('WC') || !class_exists('WC_Payment_Gateways')) {
            return $out;
        }

        $all = WC()->payment_gateways()->get_available_payment_gateways();
        if (empty($all)) {
            $all = WC()->payment_gateways()->payment_gateways();
        }

        foreach ($all as $id => $gateway) {
            $g = array();
            $g['id'] = isset($gateway->id) ? $gateway->id : $id;
            $g['title'] = method_exists($gateway, 'get_title') ? $gateway->get_title() : (!empty($gateway->title) ? $gateway->title : $g['id']);
            // Detect if gateway outputs custom fields on checkout
            $has_fields = false;
            if (isset($gateway->has_fields) && $gateway->has_fields) {
                $has_fields = true;
            } elseif (method_exists($gateway, 'payment_fields')) {
                $has_fields = true;
            }
            $g['has_fields'] = (bool)$has_fields;

            // Determine if gateway is card-based (Stripe-like)
            $lower_id = strtolower($g['id']);
            $needs_card = false;
            if (strpos($lower_id, 'stripe') !== false || $lower_id === 'woocommerce_payments' || is_a($gateway, 'WC_Payment_Gateway_CC')) {
                $needs_card = true;
            }
            $g['needs_card'] = (bool)$needs_card;

            // Support flags if provided
            $g['supports'] = is_array($gateway->supports) ? $gateway->supports : (method_exists($gateway, 'supports') ? (array)$gateway->supports : array());

            // Attempt to surface any public keys/client ids the gateway may expose (for client-side SDKs)
            $public_keys = array();
            $try_keys = array('client_id', 'client_id_sandbox', 'paypal_client_id', 'paypal_client_id_sandbox', 'publishable_key', 'test_publishable_key', 'stripe_publishable_key', 'stripe_test_publishable_key');
            foreach ($try_keys as $kopt) {
                if (method_exists($gateway, 'get_option')) {
                    $val = $gateway->get_option($kopt, '');
                    if (!empty($val)) $public_keys[$kopt] = $val;
                }
                if (empty($public_keys[$kopt]) && isset($gateway->{$kopt}) && $gateway->{$kopt}) {
                    $public_keys[$kopt] = $gateway->{$kopt};
                }
            }
            $g['public_keys'] = $public_keys;

            $out[] = $g;
        }

        return $out;
    }

    /**
     * Register the stylesheets for the frontend.
     *
     * @return void
     */
    public function enqueue_styles()
    {
        // Only enqueue on WooCommerce pages
        if (!is_woocommerce() && !is_cart() && !is_checkout() && !is_product()) {
            return;
        }

        wp_enqueue_style(
            'devnajmus-oneclick-order-popup',
            DOPW_PLUGIN_URL . 'assets/css/quickorder.css',
            array(),
            DOPW_VERSION,
            'all'
        );
    }

    /**
     * Register the JavaScript for the frontend.
     *
     * @return void
     */
    public function enqueue_scripts()
    {
        global $post;

        // Load scripts on any page that might have products
        if (!is_woocommerce() && !is_shop() && !is_product() && !is_product_category() && !is_product_tag() && !has_shortcode($post->post_content, 'products')) {
            return;
        }

        // Core scripts
        wp_enqueue_script('jquery');
        wp_enqueue_script('woocommerce');
        wp_enqueue_script('accounting');

        // Plugin script
        wp_enqueue_script(
            'devnajmus-oneclick-order-popup-frontend',
            DOPW_PLUGIN_URL . 'assets/js/quickorder.js',
            array('jquery'),
            DOPW_VERSION . '.' . time(),
            true
        );

        // Pass data to JavaScript
        // Attempt to find a Stripe publishable key from registered gateways (if any)
        $stripe_publishable_key = '';
        if (function_exists('WC') && class_exists('WC_Payment_Gateways')) {
            $all_gateways = WC()->payment_gateways()->payment_gateways();
            foreach ($all_gateways as $gateway) {
                if (!empty($gateway->id) && (false !== stripos($gateway->id, 'stripe') || $gateway->id === 'woocommerce_payments')) {
                    // Try common option keys
                    $k = '';
                    if (method_exists($gateway, 'get_option')) {
                        $k = $gateway->get_option('publishable_key', '');
                        if (empty($k)) {
                            $k = $gateway->get_option('test_publishable_key', '');
                        }
                    }
                    // Additional attempts for WooCommerce Payments and other variants
                    if (empty($k) && method_exists($gateway, 'get_option')) {
                        $k = $gateway->get_option('stripe_publishable_key', '');
                    }
                    if (empty($k) && method_exists($gateway, 'get_option')) {
                        $k = $gateway->get_option('stripe_test_publishable_key', '');
                    }
                    if (empty($k) && isset($gateway->publishable_key)) {
                        $k = $gateway->publishable_key;
                    }
                    if (empty($k) && isset($gateway->test_publishable_key)) {
                        $k = $gateway->test_publishable_key;
                    }
                    if (!empty($k)) {
                        $stripe_publishable_key = $k;
                        break;
                    }
                }
            }
        }

        wp_localize_script(
            'devnajmus-oneclick-order-popup-frontend',
            'DOPWData',
            array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('DOPW_nonce'),
                'currency_symbol' => get_woocommerce_currency_symbol(),
                'currency_pos' => get_option('woocommerce_currency_pos'),
                'decimal_separator' => wc_get_price_decimal_separator(),
                'thousand_separator' => wc_get_price_thousand_separator(),
                'decimals' => wc_get_price_decimals(),
                'debug' => WP_DEBUG,
                'stripe_publishable_key' => $stripe_publishable_key,
                'gateways' => $this->get_gateways_for_js(),
            )
        );

        wp_localize_script(
            'devnajmus-oneclick-order-popup-frontend',
            'DOPWAjax',
            array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('DOPW_nonce'),
            )
        );
    }

    /**
     * Render the popup template.
     *
     * @return void
     */
    public function render_popup_template()
    {
        // Only render on pages where we might need it
        if (is_woocommerce() || is_product() || is_shop() || is_product_category() || is_product_tag()) {
            include DOPW_PLUGIN_DIR . 'templates/quickorder-popup.php';
        }
    }

    /**
     * Add Quick Order button to shop/archive pages.
     *
     * @return void
     */
    public function add_shop_quick_order_button()
    {
        global $product;
        if (!$product || !$product->is_purchasable()) {
            return;
        }
        $this->render_quick_order_button($product);
    }

    /**
     * Add Quick Order button to single product page.
     *
     * @return void
     */
    public function add_single_quick_order_button()
    {
        global $product;
        if (!$product || !$product->is_purchasable()) {
            return;
        }
        $this->render_quick_order_button($product);
    }

    /**
     * Render the Quick Order button.
     *
     * @param WC_Product $product The product object.
     * @return void
     */
    private function render_quick_order_button($product)
    {
        $button_text = get_option('DOPW_button_text', __('Order Now', 'devnajmus-oneclick-order-popup-for-woocommerce'));
        $image_url = wp_get_attachment_image_url($product->get_image_id(), 'woocommerce_thumbnail');
        if (!$image_url) {
            $image_url = wc_placeholder_img_src('woocommerce_thumbnail');
        }
?>
        <button type="button"
            class="button DOPW-quick-order-btn"
            data-product-id="<?php echo esc_attr($product->get_id()); ?>"
            data-product-type="<?php echo esc_attr($product->get_type()); ?>"
            data-product-title="<?php echo esc_attr($product->get_name()); ?>"
            data-product-price="<?php echo esc_attr($product->get_price()); ?>"
            data-product-price-formatted="<?php echo esc_attr(wp_strip_all_tags(wc_price($product->get_price()))); ?>"
            data-product-image-url="<?php echo esc_attr($image_url); ?>">
            <?php echo esc_html($button_text); ?>
        </button>
<?php
    }
}
