<?php

/**
 * WooCommerce Shipping Instance Setting Location Enable.
 *
 * @link       http://www.techspawn.com
 * @since      3.5.5
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/admin
 */

/**
 * WooCommerce Shipping Instance Setting Location Enable of the plugin.
 *
 * 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_Woocommerce_Shipping_Instance_Setting
{
  public function __construct()
  {
    add_action('woocommerce_init', array($this, 'wcmlim_shipping_settings_location_enabled'));
    add_action("wp_ajax_wcmlim_save_localpickup_instance_enabled", array($this, "wcmlim_save_localpickup_instance_enabled"));
    add_action("wp_ajax_wcmlim_fetch_localpickup_instance_enabled", array($this, "wcmlim_fetch_localpickup_instance_enabled")); 
  }

  public function wcmlim_shipping_settings_location_enabled() {
    $shipping_methods = WC()->shipping->get_shipping_methods();
    foreach ( $shipping_methods as $shipping_method ) {
      add_filter( 'woocommerce_shipping_instance_form_fields_' . $shipping_method->id, array( $this, 'wcmlim_shipping_settings_fields_location_enabled' ) );
    }
  }
  
  /**
   * Add value field for 'Locations' condition
   * 
   * @param array $settings List of value field arguments
   * @return array $settings List of modified value field arguments.
   */
  public function wcmlim_shipping_settings_fields_location_enabled($settings) {
    $zone_id = isset($_GET['zone_id']) ? $_GET['zone_id'] : '';
    
    $settings['wcmlim_localpickup_instance_enabled'] = array(
      'title' => "<h2>WooCommerce Multi Locations </h2><p> Assign this Shipping Method to specific Locations</p>",
      'type'  => 'title',
      'label' => __( 'Enable Location' )
    );
    
    $pickup_terms = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
    
    foreach ($pickup_terms as $pterm) {   
      $pterm_id = $pterm->term_id;
      $pterm_name = ucfirst($pterm->name);
      
      $settings['wcmlim_localpickup_instance_enabled_' . $pterm_id] = array(
        'title'   => '',
        'type'    => 'checkbox',
        'class'   => 'wcmlim_localpickup_instance_enabled',
        'label'   => __( 'Enable for <b>' . $pterm_name . '</b>' ),
        'default' => 'no',
      );
    }
      
    return $settings;
  }

  /**
   * Get zone key from zone id
   * 
   * @param int $zone_id The zone ID
   * @return int|null The zone key or null if not found
   */
  private function get_zone_key_from_id($zone_id) {
    $shipping_zones = WC_Shipping_Zones::get_zones();
    foreach ($shipping_zones as $key => $zone) {
      if ($zone_id == $zone['zone_id']) {
        return $key;
      }
    }
    return null;
  }

  /**
   * Save local pickup instance enabled status
   */
  public function wcmlim_save_localpickup_instance_enabled() {

    // Verify request parameters
    if (!isset($_POST['instance_id']) || !isset($_POST['zone_id']) || 
        !isset($_POST['this_value']) || !isset($_POST['this_id'])) {
      wp_send_json_error('Missing required parameters');
      return;
    }

    $instance_id = sanitize_text_field($_POST['instance_id']);
    $zone_id = sanitize_text_field($_POST['zone_id']);
    $this_value = (int) $_POST['this_value'];
    $this_id = sanitize_text_field($_POST['this_id']);

    // Get location ID from this_id
    preg_match('/\d+$/', $this_id, $matches);
    $location_id = isset($matches[0]) ? $matches[0] : 0;
    
    if (!$location_id) {
      wp_send_json_error('Invalid location ID');
      return;
    }

    // Get zone key from zone id
    $zone_key = $this->get_zone_key_from_id($zone_id);
    
    // Handle shipping zone association
    $wcmlim_shipping_zone = get_term_meta($location_id, 'wcmlim_shipping_zone', true);
    if (!is_array($wcmlim_shipping_zone)) {
      $wcmlim_shipping_zone = array();
    }

    // Handle shipping method association
    $wcmlim_shipping_method = get_term_meta($location_id, 'wcmlim_shipping_method', true);
    if (!is_array($wcmlim_shipping_method)) {
      $wcmlim_shipping_method = array();
    }
    
    // Update shipping method associations based on checkbox state
    if ($this_value == 1) {
      // Add zone if needed
      if ($zone_key && !in_array($zone_key, $wcmlim_shipping_zone)) {
        $wcmlim_shipping_zone[] = $zone_key;
        $wcmlim_shipping_zone = array_unique($wcmlim_shipping_zone);
        update_term_meta($location_id, 'wcmlim_shipping_zone', $wcmlim_shipping_zone);
      }

      // Add method if needed
      if (!in_array($instance_id, $wcmlim_shipping_method)) {
        $wcmlim_shipping_method[] = $instance_id;
        $wcmlim_shipping_method = array_unique($wcmlim_shipping_method);
        update_term_meta($location_id, 'wcmlim_shipping_method', $wcmlim_shipping_method);
      }
    } else {
      // Remove method if needed
      $key_index = array_search($instance_id, $wcmlim_shipping_method);
      if ($key_index !== false) {
        unset($wcmlim_shipping_method[$key_index]);
        update_term_meta($location_id, 'wcmlim_shipping_method', $wcmlim_shipping_method);
      }

      // Check if any shipping methods for this zone remain
      if ($zone_key) {
        $shipping_zone = new WC_Shipping_Zone($zone_key);
        $shipping_methods = $shipping_zone->get_shipping_methods();
        $shipping_methods_keys = array_keys($shipping_methods);
        $result = array_intersect($shipping_methods_keys, $wcmlim_shipping_method);
        
        // Remove zone association if no methods are associated with this zone
        if (empty($result)) {
          $zone_index = array_search($zone_key, $wcmlim_shipping_zone);
          if ($zone_index !== false) {
            unset($wcmlim_shipping_zone[$zone_index]);
            update_term_meta($location_id, 'wcmlim_shipping_zone', $wcmlim_shipping_zone);
          }
        }
      }
    }
    
    wp_send_json_success('Method updated');
  }

  /**
   * Fetch local pickup instance enabled status
   */
  public function wcmlim_fetch_localpickup_instance_enabled() {
    if (!isset($_POST['instance_id']) || !isset($_POST['this_id'])) {
      wp_send_json_error('Missing required parameters');
      return;
    }

    $instance_id = sanitize_text_field($_POST['instance_id']);
    $this_id = sanitize_text_field($_POST['this_id']);

    // Get location ID from this_id
    preg_match('/\d+$/', $this_id, $matches);
    $location_id = isset($matches[0]) ? $matches[0] : 0;
    
    if (!$location_id) {
      wp_send_json_error('Invalid location ID');
      return;
    }

    $wcmlim_shipping_method = get_term_meta($location_id, 'wcmlim_shipping_method', true);
    $checked = (is_array($wcmlim_shipping_method) && in_array($instance_id, $wcmlim_shipping_method)) ? 'checked' : 'uncheck';
    
    echo $checked;
    die();
  }
}

new Wcmlim_Woocommerce_Shipping_Instance_Setting();
