<?php

/**
 * WooCommerce Payment Method locationwise.
 *
 * @link       http://www.techspawn.com
 * @since      1.2.2
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/admin
 */

/**
 * WooCommerce Payment Method locationwise.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/admin
 * @author     techspawn1 <contact@techspawn.com>
 */
class Wcmlim_Checkout_Payment_Method_Locationwise
{
    public function __construct()
    {
        add_filter('woocommerce_available_payment_gateways', array($this, 'filter_available_payment_gateways_per_category'), 10, 2);
    }

    public function filter_available_payment_gateways_per_category($available_gateways)
    {
        if (is_admin()) {
            return $available_gateways;
        }

        global $woocommerce;
        $tmp_term_meta = array();

        if (!empty($woocommerce->cart->cart_contents)) {
            $cart = $woocommerce->cart->cart_contents;

            $isExcLoc = get_option("wcmlim_exclude_locations_from_frontend");
            $term_args = array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0);
            if (!empty($isExcLoc)) {
                $term_args['exclude'] = $isExcLoc;
            }
            $terms = get_terms($term_args);

            foreach ($cart as $array_item) {
                if (!isset($array_item['select_location']['location_name'])) {
                    continue; // Skip items without a location.
                }
                $cart_location = $array_item['select_location']['location_name'];

                foreach ($terms as $term) {
                    if ($term->name === $cart_location) {
                        $wcmlim_payment_methods = get_term_meta($term->term_id, 'wcmlim_payment_methods');
                        if (!empty($wcmlim_payment_methods[0])) {
                            $tmp_term_meta = array_merge($tmp_term_meta, $wcmlim_payment_methods[0]);
                        }
                    }
                }
            }

            $common_payment_methods = array_unique($tmp_term_meta);
            if (empty($common_payment_methods)) {
                return $available_gateways; // No filtering if no methods are found.
            }

            foreach ($available_gateways as $gateway_id => $gateway) {
                if (!in_array($gateway_id, $common_payment_methods)) {
                    unset($available_gateways[$gateway_id]);
                }
            }
        }

        if (empty($available_gateways)) {
            add_filter('woocommerce_no_available_payment_methods_message', function () {
                return __('No common payment methods are available for the selected items. Please check your cart and try again.', 'wcmlim');
            });
        }

        return $available_gateways;
    }
}

new Wcmlim_Checkout_Payment_Method_Locationwise();