<table class="form-table" role="presentation">
  <tbody>
  <?php 
  $isLocationsGroup = get_option('wcmlim_enable_location_group');	
  if( $isLocationsGroup == "on"){
  ?>
  <tr class="form-field term-locator-wrap">
      <th scope="row" valign="top">
        <label class="" for="locator"><?php esc_html_e('Location Group', 'wcmlim'); ?></label>
      </th>
      <td>
         <?php 
          //wp_dropdown_categories( 'show_count=1&hierarchical=1' ); 

          $tax_args = array(
            'taxonomy'     => 'location_group',
            'show_option_none'  => 'Select Group',
            'hide_empty'        => 0,
            'value_field'       => 'term_id',
            'name'              => 'wcmlim_locator',
            'id'                => 'locator',
            'class'             => 'form-control',
            'orderby'           => 'id',
            'selected'          => false,
          );
          wp_dropdown_categories($tax_args);  
          $term_locator = get_term_meta( $term->term_id , 'wcmlim_locator', true);
          ?>
      </td>
    </tr>
    <script type="text/javascript"> 
    jQuery(document).ready(function(){
        var gLocation = <?php echo $term_locator;?>;  
        jQuery( "#locator" ).find( 'option[value="'+gLocation+'"]' ).attr('selected', 'selected');
        jQuery( "#select_location" ).on( "change", function (  )
          {  
          jQuery( "#locator" ).find( ":selected" ).removeAttr( "selected" );
          jQuery( "#locator" ).find( 'option[value="'+gLocation+'"]' ).attr('selected', 'selected');
          } 
        );
    });
    </script>
    <?php 
    }
    ?>
    <tr class="form-field term-address-wrap">
      <th scope="row" valign="top">
        <label for="wcmlim_autocomplete_address"><?php esc_html_e('Search Address', 'wcmlim'); ?></label>
      </th>
      <td>
        <input id="wcmlim_autocomplete_address" placeholder="Enter your address" type="text" class="form-control">
        <div class="wclimtip">?<span class="wclimtiptext">
        <pre>Google API must be valid.
        Field help to fetch register address details from google map.</pre>
        </span></div>
      </td>
    </tr>
    <tr class="form-field  term-streetNumber-wrap">
      <th scope="row" valign="top">
        <label class="" for="street_number"><?php esc_html_e('Street address', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="street_number" name="wcmlim_street_number" type="text" value="<?php esc_attr_e($streetNumber); ?>">
      </td>
    </tr>
    <tr class="form-field term-route-wrap">
      <th scope="row" valign="top">
        <label class="" for="route"><?php esc_html_e('Route', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="route" name="wcmlim_route" type="text" value="<?php esc_attr_e($route); ?>">
      </td>
    </tr>
    <tr class="form-field term-city-wrap">
      <th scope="row" valign="top">
        <label class="" for="locality"><?php esc_html_e('City', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="locality" name="wcmlim_locality" type="text" value="<?php esc_attr_e($locality); ?>">
      </td>
    </tr>
    <tr class="form-field form-required term-country-wrap">
      <th scope="row" valign="top">
        <label class="" for="country"><?php esc_html_e('Country', 'wcmlim'); ?></label>
      </th>
      <td>
        <?php
        // Get WooCommerce countries
        $countries_obj = WC()->countries;
        $countries = $countries_obj->get_countries();
        ?>
        <select class="form-control" id="country" name="wcmlim_country">
          <option value=""><?php esc_html_e('Select Country', 'wcmlim'); ?></option>
          <?php foreach ($countries as $code => $name) : ?>
            <option value="<?php echo esc_attr($code); ?>" <?php selected($country, $code); ?>><?php echo esc_html($name); ?></option>
          <?php endforeach; ?>
        </select>
      </td>
    </tr>
        <tr class="form-field term-state-wrap">
      <th scope="row" valign="top">
        <label class="" for="administrative_area_level_1"><?php esc_html_e('State', 'wcmlim'); ?></label>
      </th>
      <td>
        <select class="form-control" id="administrative_area_level_1" name="wcmlim_administrative_area_level_1" required data-current-state="<?php echo esc_attr($state); ?>">
          <option value=""><?php esc_html_e('Select State', 'wcmlim'); ?></option>
          <?php
          if (!empty($country)) {
            $states = $countries_obj->get_states($country);
            if (is_array($states)) {
              foreach ($states as $state_code => $state_name) : ?>
                <option value="<?php echo esc_attr($state_code); ?>" <?php selected($state, $state_code); ?>><?php echo esc_html($state_name); ?></option>
              <?php endforeach;
            }
          }
          ?>
        </select>
        <div id="no-states-notice" style="color: #e32; margin-top: 5px; display: none;">
          <?php esc_html_e('This country does not have any states', 'wcmlim'); ?>
        </div>
      </td>
    </tr>
    <tr class="form-field form-required term-postcode-wrap">
      <th scope="row" valign="top">
        <label class="" for="postal_code"><?php esc_html_e('Zip code', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="postal_code" name="wcmlim_postal_code" type="text" value="<?php esc_attr_e($postal_code); ?>">
      </td>
    </tr>
    <?php
    $isShipping = get_option('wcmlim_enable_shipping_zones');
    if ($isShipping == "on") {
    ?>
      <tr class="form-field term-shippingZone-wrap">
        <th scope="row" valign="top"><label for="wcmlim_shipping_zone"><?php esc_html_e('Select Shipping Zones', 'wcmlim'); ?></label></th>
        <td>
          <select multiple="multiple" class="multiselect" name="wcmlim_shipping_zone[]" id="wcmlim_shipping_zone">
            <?php $shipping_zones = WC_Shipping_Zones::get_zones();

            foreach ((array) $shipping_zones as $key => $value) {
            ?>
              <option value="<?php echo $key; ?>" <?php if (!empty($wcmlim_shipping_zone)) {
                                                    if (in_array($key, $wcmlim_shipping_zone)) {
                                                      echo "selected='selected'";
                                                    }
                                                  }
                                                  ?>><?php echo $value['zone_name']; ?></option>
            <?php }

            ?>

          </select>
        </td>
      </tr>
    <?php } 
    $isTaxLocation       = get_option('wcmlim_allow_tax_to_locations');
    if ($isTaxLocation == "on") {
      $tax_name = get_term_meta($term->term_id, 'wcmlim_taxLocations_name', true);
      $tax_rate = get_term_meta($term->term_id, 'wcmlim_taxLocations_rate', true);
      ?>
        <tr class="form-field term-taxLocations-wrap">
          <th scope="row" valign="top"><label for="wcmlim_taxLocations"><?php esc_html_e('Add Tax to Location', 'wcmlim'); ?></label></th>
            <td class="wcmlim_tax_td">
              <input type="text" id="wcmlim_taxLocations_name" name="wcmlim_taxLocations_name" class="form-control" value="<?php echo esc_attr($tax_name); ?>" placeholder="Enter Tax Name">
              <input type="number" id="wcmlim_taxLocations_rate" name="wcmlim_taxLocations_rate" class="form-control" value="<?php echo esc_attr($tax_rate); ?>" placeholder="Tax Rate &#x25;" step="0.1">
            </td>
        </tr>
      <?php } ?>
    <tr class="form-field term-email-wrap">
      <th scope="row" valign="top">
        <label class="" for="email"><?php esc_html_e('Email', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="email" name="wcmlim_email" type="text" value="<?php esc_attr_e($email); ?>">
      </td>
    </tr>
    <tr class="form-field term-phone-wrap">
      <th scope="row" valign="top">
        <label class="" for="wcmlim_phone_validation"><?php esc_html_e('Phone', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="wcmlim_phone_validation" name="wcmlim_phone" type="number" pattern="[0-9]{10}" value="<?php esc_attr_e($phone); ?>">
        <div class="phonevalmsg" id="phonevalmsg"></div>
      </td>
    </tr>
    <?php

    $wcmlim_order_fulfil_edit = get_option('wcmlim_order_fulfil_edit');
    $wcmlim_allow_only_backend   = get_option('wcmlim_allow_only_backend');
    //checking backorder  is on or not
    if($wcmlim_allow_only_backend == 'on' ){
    $fulfilment_rule = get_option("wcmlim_order_fulfilment_rules");

    if($fulfilment_rule == "nearby_instock")
      {
        $fulfilment_rule = "clcsadd";
      }
    
    if (($fulfilment_rule == "locappriority") || ($fulfilment_rule == "clcsadd")) {

    ?>
      <tr class="form-field term-location-priority-wrap">
        <th scope="row" valign="top">
          <label class="" for="lcpriority"><?php esc_html_e('Location Priority', 'wcmlim'); ?></label>
        </th>
        <td>
          <input class="form-control noscroll" id="lcpriority" name="wcmlim_location_priority" type="number" min="1" pattern="[0-9]{10}" value="<?php esc_attr_e($locPriority); ?>">
        </td>
      </tr>
    <?php } }?>

    <?php $espe = get_option("wcmlim_assign_location_shop_manager");
    if ($espe == "on") { ?>
      <tr class="form-field term-shopManager-wrap">
        <th>
          <label class="" for="wcmlim_shop_manager"><?php esc_html_e('Location Shop Manager', 'wcmlim'); ?></label>
        </th>
        <td>
          <select multiple="multiple" class="multiselect" name="wcmlim_shop_manager[]" id="wcmlim_shop_manager">
            <?php
            $args = ['role' => 'location_shop_manager'];
            $all_users = get_users($args);
            foreach ((array) $all_users as $key => $user) {
            ?>
              <option value="<?php esc_html_e($user->ID); ?>" <?php if (!empty($lshopManager)) {
                                                                if (in_array($user->ID, $lshopManager)) {
                                                                  echo "selected='selected'";
                                                                }
                                                              }
                                                              ?>><?php esc_html_e($user->display_name); ?></option>
            <?php }
            
          ?>
          </select>
                   

        </td>
      </tr>

      
    <?php } ?>

    <?php
    $isPaymentMethods = get_option('wcmlim_assign_payment_methods_to_locations');
    if ($isPaymentMethods == "on") { ?>
      <tr class="form-field term-paymentMethods-wrap">
        <th>
          <label class="" for="wcmlim_payment_methods"><?php esc_html_e('Select Payment Methods', 'wcmlim'); ?></label>
        </th>
        <td>
          <select multiple="multiple" class="multiselect" name="wcmlim_payment_methods[]" id="wcmlim_payment_methods">
            <?php
            global $woocommerce;
            $gateways = $woocommerce->payment_gateways();
            foreach ($gateways as $gateway_single) {
              foreach ($gateway_single as $gateway) {
                if ($gateway->enabled == 'yes') {
                  $wcmlim_payment_methods = get_term_meta($term->term_id, 'wcmlim_payment_methods', true);
            ?>
                  <option value="<?php esc_html_e($gateway->id); ?>" <?php if (!empty($wcmlim_payment_methods)) {
                                                                        if (in_array($gateway->id, $wcmlim_payment_methods)) {
                                                                          echo "selected='selected'";
                                                                        }
                                                                      }
                                                                    }

                                                                      ?>><?php esc_html_e($gateway->title); ?></option>
              <?php }
            } ?>
          </select>
        </td>
      </tr>
    <?php } ?>

    <?php
    $wcmlim_pos_compatiblity1 = get_option('wcmlim_pos_compatiblity');
    if ($wcmlim_pos_compatiblity1 == "on" && in_array('woocommerce-openpos/woocommerce-openpos.php', apply_filters('active_plugins', get_option('active_plugins')))) { ?>
      <tr class="form-field term-pos-wrap">
        <th>
          <label class="" for="wcmlim_pos_compatiblity"><?php esc_html_e('Select OpenPOS Outlets', 'wcmlim'); ?></label>
        </th>
        <td>
          <select name="wcmlim_pos_compatiblity" id="wcmlim_pos_compatiblity">
             <option value="default"><?php esc_html_e('Select Outlet'); ?></option>
            <?php
            $wcmlim_locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false));
      
            $posts = get_posts([
              'post_type' => '_op_warehouse',
              'post_status' => array('publish'),
              'numberposts' => -1
            ]);

            foreach ((array) $posts as $p) 
            {
              $post = get_post($p->ID);
              $name = $post->post_title;
              $openposOutletMap = array();
                foreach ($wcmlim_locations as $key => $value) {
                  $term_id = $value->term_id;
                  $loc_outlet_id = get_term_meta($term_id, 'wcmlim_pos_compatiblity', true);
                  $openposOutletMap[] = $loc_outlet_id;
                }
                if($wcmlim_pos_compatiblity == $p->ID)
                {
                  ?>
                  <option value="<?php esc_html_e($p->ID); ?>" <?php
                                                        if ($p->ID == $wcmlim_pos_compatiblity) {
                                                          echo "selected='selected'";
                                                        }
                                                        ?>><?php esc_html_e($name); ?></option>
                <?php
                }
                if(!in_array($p->ID,$openposOutletMap))
                {
                  ?>
                  <option value="<?php esc_html_e($p->ID); ?>" <?php
                                                        if ($p->ID == $wcmlim_pos_compatiblity) {
                                                          echo "selected='selected'";
                                                        }
                                                        ?>><?php esc_html_e($name); ?></option>
                <?php
                }
            } ?>
          </select>
        </td>
      </tr>
    <?php }
    $wc_pos_compatiblity1 = get_option('wcmlim_wc_pos_compatiblity');
    if ($wc_pos_compatiblity1 == "on" && in_array('woocommerce-point-of-sale/woocommerce-point-of-sale.php', apply_filters('active_plugins', get_option('active_plugins')))) { 
      $locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false));
      
    ?>
    <tr class="form-field term-wcpos-wrap">
      <th>
        <label class="" for="wcmlim_wcpos_compatiblity"><?php esc_html_e('Select WC point of sale Outlets', 'wcmlim'); ?></label>
      </th>
      <td>
        <select name="wcmlim_wcpos_compatiblity" id="wcmlim_wcpos_compatiblity">
        <option value="default"><?php esc_html_e('Select Outlet'); ?></option>

          <?php
          $args = array('numberposts' => -1,'post_type'   => 'pos_outlet','post_status' => 'publish');
          $all_outlets = get_posts( $args );
          

          foreach ((array) $all_outlets as $key => $outlet) {
          
            $outlet_id = $outlet->ID;
            $outlet_name = $outlet->post_title;
            $tmpOutletMap = array();
            foreach ($locations as $key => $value) {
              $term_id = $value->term_id;
              $loc_outlet_id = get_term_meta($term_id, 'wcmlim_wcpos_compatiblity', true);
              $tmpOutletMap[] = $loc_outlet_id;
            }
            if($wcpos_selected_outlet == $outlet_id)
            {
              ?>
          <option value="<?php esc_html_e($outlet_id); ?>" <?php
                                                        if ($outlet_id == $wcpos_selected_outlet) {
                                                          echo "selected='selected'";
                                                        }
                                                        ?>><?php esc_html_e($outlet_name); ?></option>
        <?php
            }
            if(!in_array($outlet_id,$tmpOutletMap))
            {
              ?>
          <option value="<?php esc_html_e($outlet_id); ?>" <?php
                                                        if ($outlet_id == $wcpos_selected_outlet) {
                                                          echo "selected='selected'";
                                                        }
                                                        ?>><?php esc_html_e($outlet_name); ?></option>
        <?php

             
            }

            }
          
          ?>
        </select>
      </td>
    </tr>
  <?php 
  }

  $wcmlim_enable_split_packages = get_option("wcmlim_enable_split_packages");
  if ($wcmlim_enable_split_packages == 'on') {
    $wcmlim_dimension_unit = get_term_meta($term->term_id, 'wcmlim_dimension_unit', true);
?>
      <tr class="form-field term-measurement-unit-wrap">
        <th scope="row" valign="top"><label for="wcmlim_dimension_unit"><?php esc_html_e('Select Measurement Unit', 'wcmlim'); ?></label></th>
        <td>
          <select name="wcmlim_dimension_unit" id="wcmlim_dimension_unit">
            <option <?php echo ($wcmlim_dimension_unit == 'LBS_IN') ? 'selected': '';?>value="LBS_IN">LBS_IN</option>
            <option value="KG_CM" <?php echo ($wcmlim_dimension_unit == 'KG_CM') ? 'selected': '';?>>KG_CM</option>
        </select>
        </td>
      </tr>
<?php  
}
    $isShippingMethods = get_option('wcmlim_enable_shipping_methods');
    if ($isShippingMethods == "on") {
    ?>
      <tr class="form-field term-shippingMethod-wrap">
        <th scope="row" valign="top"><label for="wcmlim_shipping_method"><?php esc_html_e('Select Shipping Methods', 'wcmlim'); ?></label></th>
        <td>
          <select multiple="multiple" class="multiselect" name="wcmlim_shipping_method[]" id="wcmlim_shipping_method">
            <?php
            $wcmlim_payment_methods = get_term_meta($term->term_id, 'wcmlim_payment_methods', true);

            // Get all your existing shipping zones IDS
            $zone_ids = array_keys(array($wcmlim_payment_methods) + WC_Shipping_Zones::get_zones());

            // Loop through shipping Zones IDs
            foreach ($zone_ids as $zone_id) {
              // Get the shipping Zone object
              $shipping_zone = new WC_Shipping_Zone($zone_id);

              // Get all shipping method values for the shipping zone
              $shipping_methods = $shipping_zone->get_shipping_methods(true, 'values');

              // Loop through each shipping methods set for the current shipping zone
              foreach ($shipping_methods as $instance_id => $shipping_method) {
                // The dump of protected data from the current shipping method
            ?>
                <option value="<?php echo $instance_id; ?>" <?php if (!empty($wcmlim_shipping_method)) {
                                                              if (in_array($instance_id, $wcmlim_shipping_method)) {
                                                                echo "selected='selected'";
                                                              }
                                                            }
                                                            ?>><?php echo $shipping_method->title; ?></option>
            <?php }
            }

            ?>

          </select>
        </td>
      </tr>
    <?php }

    ?>
    <tr class="form-field term-time-wrap">
      <th scope="row" valign="top">
        <label class="" for="Time"><?php esc_html_e('Set your location time', 'wcmlim'); ?></label>
      </th>
      <td>
        Opens at - <input class="form-control w-15" id="start_time" name="wcmlim_start_time" type="time" value="<?php esc_attr_e($start_time); ?>">
        Close at - <input class="form-control w-15" id="end_time" name="wcmlim_end_time" type="time" value="<?php esc_attr_e($end_time); ?>">
      </td>
    </tr>

    <tr class="form-field term-latlng-wrap">
      <th scope="row" valign="top">
        <label class="" for="Latlng"><?php esc_html_e('Location Lat/Lng', 'wcmlim'); ?></label>
      </th>
      <td>
        Lat - <input class="form-control w-15" id="wcmlim_lat" name="wcmlim_lat" type="text" value="<?php esc_attr_e($wcmlim_lat); ?>">
        Lng - <input class="form-control w-15" id="wcmlim_lng" name="wcmlim_lng" type="text" value="<?php esc_attr_e($wcmlim_lng); ?>">
      </td>
      
    </tr>

    <tr class="form-field term-location-image-wrap">
      <th scope="row" valign="top">
        <label for="location_image"><?php esc_html_e('Location Image', 'wcmlim'); ?></label>
      </th>
      <td>
        <?php
        $location_image = get_term_meta($term->term_id, 'location_image', true);
        ?>
        <input type="text" id="location_image" name="location_image" class="form-control" value="<?php echo esc_attr($location_image); ?>" placeholder="Image URL">
        <button type="button" class="button wcmlim-upload-image-button" data-target="location_image" style="margin-top: 5px;">
          <?php esc_html_e('Upload Image', 'wcmlim'); ?>
        </button>
        <?php if ($location_image) : ?>
          <div class="wcmlim-image-preview" style="margin-top: 10px;">
            <img src="<?php echo esc_url($location_image); ?>" style="max-width: 200px; height: auto; display: block;">
          </div>
        <?php endif; ?>
        <p class="description"><?php esc_html_e('Upload an image of your store location for enhanced SEO (recommended size: 1200x675px)', 'wcmlim'); ?></p>
      </td>
    </tr>
    <?php
   $wcmlim_linked_users = get_term_meta($term->term_id, 'wcmlim_linked_users', true);

   if (is_string($wcmlim_linked_users)) {
       $wcmlim_linked_users = unserialize($wcmlim_linked_users);
   }
   
   $wcmlim_linked_users = is_array($wcmlim_linked_users) ? $wcmlim_linked_users : [];
   

  ?>
 <?php
  $add_multiple_users = get_option('wcmlim_enable_userspecific_location');
?>
<?php if ($add_multiple_users == 'on') { ?>
  <tr class="form-field term-wcmlim-linked-users-wrap">
      <th>
          <label for="wcmlim_linked_users"><?php esc_html_e('Add User', 'wcmlim'); ?></label>
      </th>
      <td>
          <select multiple="multiple" class="multiselect" id="wcmlim_linked_users" name="wcmlim_linked_users[]">
              <?php
              $users = get_users();
              
              foreach ($users as $user) {
                  echo '<option value="' . esc_attr($user->ID) . '"';
                  
                  if (in_array($user->ID, $wcmlim_linked_users)) {
                      echo " selected='selected'";
                  }
                  
                  echo '>' . esc_html($user->display_name) . '</option>';
              }
              ?>
          </select>
      </td>
</tr>
<?php } ?>


    <?php
        if (in_array('pos-ninja/pos-ninja.php', apply_filters('active_plugins', get_option('active_plugins'))))
       {
         ?>
           <tr class="form-field term-outlet-mapping-wrap">
            <th scope="row" valign="top">
                <label class="" for="stockuppposoutlets"><?php esc_html_e('StockUpp POS Outlet', 'wcmlim'); ?></label>
              </th>
              <td>
              <select name="wcmlim_stockupp_pos" id="wcmlim_stockupp_pos">
              <option value="">Select StockUpp POS Outlet</option>
            <?php
            $wcmlim_stockupp_pos = get_term_meta($term->term_id, 'wcmlim_stockupp_pos', true);
            $stockupp_outlets = get_terms(array('taxonomy' => 'pos_outlets', 'hide_empty' => false, 'parent' => 0));
            foreach ($stockupp_outlets as $k => $stockupp_pos_outlets) {
              $stockupp_pos_id = $stockupp_pos_outlets->term_id;
              $all_terms_locations = get_terms(array('taxonomy' => 'locations', 'hide_empty' => false, 'parent' => 0));
            $stockupp_pos_outlet_mapped = 0;
              foreach($all_terms_locations as $loc_edit_screen_key=>$loc_edit_screen_term){
              $location_terms_id = $loc_edit_screen_term->term_id;
            $row_wcmlim_stockupp_pos = get_term_meta($location_terms_id, 'wcmlim_stockupp_pos', true);

              if(($row_wcmlim_stockupp_pos == $stockupp_pos_id)){
                $stockupp_pos_outlet_mapped = 1;
              }
              if(!empty($wcmlim_stockupp_pos))
              {
                $stockupp_pos_outlet_mapped = 0;
              }
            }
if($stockupp_pos_outlet_mapped != 1)
{
  ?>
  <option value="<?php echo $stockupp_pos_outlets->term_id; ?>" <?php if (!empty($wcmlim_stockupp_pos)) {
                                                if ($stockupp_pos_outlets->term_id==$wcmlim_stockupp_pos) {
                                                  echo "selected='selected'";
                                                }
                                              }
                                              ?>><?php echo $stockupp_pos_outlets->name; ?></option>
<?php
}
            
            }

            ?>

          </select>
              </td>
            </tr>
         <?php
         }
         ?>

    <?php
    
     if (in_array('local-pickup-for-woocommerce/local-pickup.php', apply_filters('active_plugins', get_option('active_plugins'))) ||  is_array(get_site_option('active_sitewide_plugins')) && !array_key_exists('local-pickup-for-woocommerce/local-pickup.php', get_site_option('active_sitewide_plugins'))) 
    {
      update_option('wcmlim_allow_local_pickup','');
    }
    $allow_local_pickup = get_option('wcmlim_allow_local_pickup');
    // if ($allow_local_pickup == "on") { below code removed/deactivated for local pickup setting
      if (false) {
    ?>
      <tr class="form-field term-pickup">
        <th scope="row" valign="top">
          <label class="" for="allow_pickup"><?php esc_html_e('Enable Pickup For Location', 'wcmlim'); ?></label>
        </th>
        <td>
          <label class="switch">
            <input type="checkbox" id="allow_pickup" name="wcmlim_allow_pickup" <?php echo ($allow_pickup == 'on') ? 'checked="checked"' : ''; ?>>
            <span class="slider round"></span>
          </label>
        </td>
      </tr>
    <?php }

    $locationRadius = get_option( 'wcmlim_service_radius_for_location' );
    if($locationRadius == "on"){
    ?>
    <tr class="form-field term-service-radius-wrap">
      <th scope="row" valign="top">
        <label class="" for="wcmlim_service_radius"><?php esc_html_e('Service Radius', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="wcmlim_service_radius" name="wcmlim_service_radius" type="number" value="<?php echo $location_radius;?>" pattern="[0-9]{10}">
      </td>
    </tr>
    <?php } 
    $locationFee = get_option( 'wcmlim_location_fee' );
    if($locationFee == "on"){
    ?>
    
    <tr class="form-field term-location-fee-wrap">
      <th scope="row" valign="top">
        <label class="" for="wcmlim_location_fee"><?php esc_html_e('Location Fee', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="wcmlim_location_fee" name="wcmlim_location_fee" type="number" value="<?php echo $location_fee;?>" min="0" step="any">
      </td>
    </tr>
    <?php } ?>
    <tr class="form-field term-radius-wrap">
      <th scope="row" valign="top">
        <label class="" for="wcmlim_radius"><?php esc_html_e('Radius', 'wcmlim'); ?></label>
      </th>
      <td>
        <input class="form-control" id="wcmlim_radius" name="wcmlim_radius" type="number" min="0" step="any" value="<?php echo get_term_meta($term->term_id, 'wcmlim_radius', true); ?>">
      </td> 
    </tr>
    <tr class="form-field term-location-note-wrap">
      <th scope="row" valign="top">
        <label class="" for="wcmlim_location_note"><?php esc_html_e('Location Note', 'wcmlim'); ?></label>
      </th> 
      <td>
        <input class="form-control" id="wcmlim_location_note" name="wcmlim_location_note" type="text" value="<?php echo get_term_meta($term->term_id, 'wcmlim_location_note', true); ?>">
      </td>
    </tr>

    <?php
     if( in_array( 'Multiloca Premium Addon/multiloca-premium-addon.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    ?>
        <tr class="form-field term-location-note-wrap">
      <th scope="row" valign="top">
        <label class="" for="wcmlim_location_hide"><?php esc_html_e('Location Hide', 'wcmlim'); ?></label>
      </th> 
      <td>
        <input class="form-control" id="wcmlim_location_hide" name="wcmlim_location_hide" type="checkbox" value="yes" <?php echo 'yes' == get_term_meta($term->term_id, 'wcmlim_location_hide', true) ? 'checked' : '' ?>>
      </td>
    </tr>
          <style>
            .wcmlim-rulefilter_container,
            .wcmlim-rules_container {
                background-color: white;
                padding: 20px;
                border-radius: 8px;
                border: 1px solid #ddd;
                margin-top: 15px;
            }

            .wcmlim-filter_row {
                display: flex;
                align-items: center;
                margin-bottom: 10px;
                gap: 10px;
            }

            .wcmlim-add_btn {
                display: block;
                margin-top: 20px;
                padding: 10px 20px;
                background-color: #3498db;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 16px;
            }
            .wcmlim-rule_fields {
                width: 100%;
                max-width: 20rem !important
            }
            .wcmlim-initial .dashicons-trash {
                display: none;
            }
            .wcmlim-rulerowdelete {
                float: right;
            }
            .wcmlim-saverules {
                float: right;         
            }
            .wcmlim-rules_rows .select2-container {
                width: 300px !important;
            }
            .dashicons-trash {
              cursor: pointer;
            }

        </style>
        <script>
          jQuery(document).ready(function($) {

              function serializeRules() {
                  const rules = [];

                  $('.wcmlim-rulefilter_container').each(function () {
                      const andGroup = {
                          relation: 'AND',
                          conditions: []
                      };

                      $(this).find('.wcmlim-filter_row').each(function () {
                          const type = $(this).find('select[name="wcmlim_select_rule_type"]').val();
                          const operator = $(this).find('select[name="wcmlim_select_rule_cond"]').val();
                          const valueField = $(this).find('select[name="wcmlim_select_rule_value"]');

                          let values = valueField.val();

                          // Make sure values is an array
                          if (!Array.isArray(values)) {
                              values = values ? [values] : [];
                          }

                          andGroup.conditions.push({
                              type,
                              operator,
                              value: values
                          });
                      });

                      rules.push(andGroup);
                  });  

                  return rules;
              }


              jQuery('.wcmlim-saverules').click(function() {
                  const rulesData = serializeRules();
                  const rulesJson = JSON.stringify(rulesData);

                  $('#wcmlim-ruleshidden').val(rulesJson);

              });

              function initSelect2($select, type) {
                  let placeholderText = 'Select Value';
                  if (type === 'product') placeholderText = 'Select Products';
                  else if (type === 'category') placeholderText = 'Select Categories';
                  else if (type === 'tag') placeholderText = 'Select Tags';
                  else if (type === 'attribute') placeholderText = 'Select Attributes';
                  else if (type === 'brand') placeholderText = 'Select Brands';

                  $select.select2({
                      width: 'resolve',
                      placeholder: 'Select '+type,
                      multiple: true,
                      ajax: {
                          url: wcmlim_ajax.ajax_url,
                          dataType: 'json',
                          delay: 250,
                          method: 'POST',
                          data: function (params) {
                              return {
                                  action: type === 'product' ? 'wcmlim_rulesget_products'
                                  : type === 'category' ? 'wcmlim_rulesget_categories'
                                  : type === 'tag' ? 'wcmlim_rulesget_tags'
                                  : type === 'attribute' ? 'wcmlim_rulesget_attributes'
                                  : 'wcmlim_rulesget_brands',
                                  q: params.term,
                                  security: '<?php echo wp_create_nonce('wcmlim_settings_nonce'); ?>'
                              };
                          },
                          processResults: function (data) {
                              return {
                                  results: data
                              };
                          },
                          cache: true
                      }
                  });
              }

              // On rule type change
              $(document).on('change', 'select[name="wcmlim_select_rule_type"]', function () {
                  const $row = $(this).closest('.wcmlim-filter_row');
                  const $valueField = $row.find('select[name="wcmlim_select_rule_value"]');

                  const selectedType = $(this).val();

                  // Remove old Select2 instance if present
                  if ($valueField.hasClass('select2-hidden-accessible')) {
                      $valueField.select2('destroy');
                  }

                  if (selectedType === 'Product') {
                      // Replace with multi-select + Select2
                      $valueField.replaceWith('<select class="wcmlim-rule_fields wcmlim-product-select" name="wcmlim_select_rule_value" multiple="multiple"></select>');
                      initSelect2($row.find('.wcmlim-product-select'), 'product');
                  } else if (selectedType === 'Product Category') {
                      $valueField.replaceWith('<select class="wcmlim-rule_fields wcmlim-category-select" name="wcmlim_select_rule_value" multiple="multiple"></select>');
                      initSelect2($row.find('.wcmlim-category-select'), 'category');
                  } else if (selectedType === 'Product Tag') {
                      $valueField.replaceWith('<select class="wcmlim-rule_fields wcmlim-tag-select" name="wcmlim_select_rule_value" multiple="multiple"></select>');
                      initSelect2($row.find('.wcmlim-tag-select'), 'tag');
                  } else if (selectedType === 'Product Attribute') {
                      $valueField.replaceWith('<select class="wcmlim-rule_fields wcmlim-attribute-select" name="wcmlim_select_rule_value" multiple="multiple"></select>');
                      initSelect2($row.find('.wcmlim-attribute-select'), 'attribute');
                  } else if (selectedType === 'Product Brand') {
                      $valueField.replaceWith('<select class="wcmlim-rule_fields wcmlim-brand-select" name="wcmlim_select_rule_value" multiple="multiple"></select>');
                      initSelect2($row.find('.wcmlim-brand-select'), 'brand');
                  } else {
                      // Replace with normal dropdown
                      $valueField.replaceWith(`
                          <select class="wcmlim-rule_fields" name="wcmlim_select_rule_value">
                              <option>Select Value</option>
                          </select>`);
                  }
              });


              jQuery(document).on('click', '.wcmlim-ruledelete', function() {
                  jQuery(this).closest('.wcmlim-filter_row').remove();
              });

              jQuery(document).on('click', '.wcmlim-rulerowdelete', function() {
                  jQuery(this).closest('.wcmlim-add_and_rule_container').remove();
              });

              jQuery(document).on('click', '.wcmlim-add_or_rule', function() {
                  jQuery(this).closest('.wcmlim-rulefilter_container').find('.wcmlim-rules_rows').append(`
                      <div class="wcmlim-filter_row">
                          <select class="wcmlim-rule_fields" name="wcmlim_select_rule_type">
                              <option>Select Type</option>
                              <option>Product</option>
                              <option>Product Category</option>
                              <option>Product Tag</option>
                              <option>Product Attribute</option>
                              <option>Product Brand</option>
                          </select>
                          <select class="wcmlim-rule_fields" name="wcmlim_select_rule_cond">
                              <option>Includes</option>
                              <option>Excludes</option>
                          </select>
                          <select class="wcmlim-rule_fields" name="wcmlim_select_rule_value">
                              <option>Select Value</option>
                          </select>
                          <div><span class="dashicons dashicons-trash wcmlim-ruledelete"></span></div>
                      </div>`);
              });

              jQuery(document).on('click', '.wcmlim-add_and_rule', function() {
                  jQuery(this).closest('.wcmlim-rules_container').find('.wcmlim-rule_container').append(`
                      <div class="wcmlim-rulefilter_container wcmlim-add_and_rule_container">
                      <div class="wcmlim-rulerowdelete"><span class="dashicons dashicons-trash wcmlim-rulerowdelete"></span></div>
                          <div class="wcmlim-rules_rows">
                              <div class="wcmlim-filter_row wcmlim-initial">
                                  <select class="wcmlim-rule_fields" name="wcmlim_select_rule_type">
                                      <option>Select Type</option>
                                      <option>Product</option>
                                      <option>Product Category</option>
                                      <option>Product Tag</option>
                                      <option>Product Attribute</option>
                                      <option>Product Brand</option>
                                  </select>
                                  <select class="wcmlim-rule_fields" name="wcmlim_select_rule_cond">
                                      <option>Includes</option>
                                      <option>Excludes</option>
                                  </select>
                                  <select class="wcmlim-rule_fields" name="wcmlim_select_rule_value">
                                      <option>Select Value</option>
                                  </select>
                              </div>
                          </div>
                          <button class="wcmlim-add_or_rule wcmlim-add_btn" type="button">+ OR </button>
                      </div>`);
              });



              jQuery('.wcmlim-admin-menu-tab-li').on('click', function() {
                  jQuery('.wcmlim-admin-menu-tab-li').removeClass('active');
                  jQuery(this).addClass('active');
                  var tabId = jQuery(this).find('a').attr('href');
                  jQuery('.tab-pane').removeClass('active');
                  jQuery(tabId).addClass('active');
              });

             // Hide delete icon for first AND group and first rule in each group
        function adjustDeleteIcons() {
            // Hide .wcmlim-rulerowdelete for first .wcmlim-add_and_rule_container
            var $andGroups = jQuery('.wcmlim-add_and_rule_container');
            $andGroups.each(function(i, group) {
                var $group = jQuery(group);
                if (i === 0) {
                    $group.find('.wcmlim-rulerowdelete').hide();
                } else {
                    $group.find('.wcmlim-rulerowdelete').show();
                }
                // Hide .wcmlim-ruledelete for first .wcmlim-filter_row in each group
                $group.find('.wcmlim-filter_row').each(function(j, row) {
                    var $row = jQuery(row);
                    if (j === 0) {
                        $row.find('.wcmlim-ruledelete').hide();
                    } else {
                        $row.find('.wcmlim-ruledelete').show();
                    }
                });
            });
        }

        // Initial adjustment on page load
        adjustDeleteIcons();
        // Adjust after adding/removing rules/groups
        jQuery(document).on('click', '.wcmlim-add_and_rule, .wcmlim-add_or_rule, .wcmlim-ruledelete, .wcmlim-rulerowdelete', function() {
            setTimeout(adjustDeleteIcons, 50);
        });

        // Initialize select2 for rule selects with preselected values
        var typeMap = {
            'Product': 'product',
            'Product Category': 'category',
            'Product Tag': 'tag',
            'Product Attribute': 'attribute',
            'Product Brand': 'brand'
        };
        Object.keys(typeMap).forEach(function(label) {
            var type = typeMap[label];
            $('.wcmlim-' + type + '-select').each(function() {
                var $select = $(this);
                if (!$select.hasClass('select2-hidden-accessible')) {
                    initSelect2($select, type);
                }
            });
        });
              
          });  
        </script>
        <?php
            // Fetch saved rules
            $rules = get_term_meta($term->term_id, 'wcmlim_saved_rules', true);
            $rules = json_decode($rules, true);
            // Helper for rule types
            $rule_types = [
                'Product' => 'product',
                'Product Category' => 'category',
                'Product Tag' => 'tag',
                'Product Attribute' => 'attribute',
                'Product Brand' => 'brand'
            ];
        ?>
    <tr>
       <th scope="row" valign="top">
        <label class="" for="wcmlim_location_rules"><?php esc_html_e('Enable Rules Filtering', 'wcmlim'); ?></label>
      </th>          
      <td>                     
        <div>
            <div class="grid_box" style="margin-bottom: 30px;">
                <div class="wcmlim-setting-option-des">
                <label class="switch">
                    <input class="wcmlim-setting-option-des" type="checkbox" name="wcmlim_enable_rules" <?php checked(get_term_meta($term->term_id, 'wcmlim_enable_rules', true), 'on'); ?>>
                    <span class="slider round"></span>
                </label>
                </div>
            </div>          
            <div class="wcmlim-rules_container">
                <div class="wcmlim-rule_container">
                    <?php if (!empty($rules) && is_array($rules)) : ?>
                        <?php foreach ($rules as $groupIndex => $group) : ?>
                            <div class="wcmlim-rulefilter_container wcmlim-add_and_rule_container">
                                <div class="wcmlim-rulerowdelete">
                                    <?php if ($groupIndex !== 0) : ?>
                                        <span class="dashicons dashicons-trash wcmlim-rulerowdelete"></span>
                                    <?php endif; ?>
                                </div>
                                <div class="wcmlim-rules_rows">
                                    <?php foreach ($group['conditions'] as $index => $cond) :
                                        $type = $cond['type'];
                                        $operator = $cond['operator'];
                                        $values = $cond['value'];

                                        $slug = strtolower(str_replace(' ', '-', $type));
                                        $selectClass = "wcmlim-rule_fields wcmlim-{$slug}-select";
                                        $initialClass = $index === 0 ? 'wcmlim-filter_row wcmlim-initial' : 'wcmlim-filter_row';
                                        ?>
                                        <div class="<?php echo $initialClass; ?>">
                                            <select class="wcmlim-rule_fields" name="wcmlim_select_rule_type">
                                                <option>Select Type</option>
                                                <?php foreach ($rule_types as $label => $val) : ?>
                                                    <option value="<?php echo $label; ?>" <?php selected($type, $label); ?>><?php echo $label; ?></option>
                                                <?php endforeach; ?>
                                            </select>

                                            <select class="wcmlim-rule_fields" name="wcmlim_select_rule_cond">
                                                <option>Includes</option>
                                                <option <?php selected($operator, 'Excludes'); ?>>Excludes</option>
                                            </select>

                                            <?php
                                            // Map rule type to select2 class and type
                                            $type_map = [
                                                'Product' => ['class' => 'wcmlim-product-select', 'type' => 'product'],
                                                'Product Category' => ['class' => 'wcmlim-category-select', 'type' => 'category'],
                                                'Product Tag' => ['class' => 'wcmlim-tag-select', 'type' => 'tag'],
                                                'Product Attribute' => ['class' => 'wcmlim-attribute-select', 'type' => 'attribute'],
                                                'Product Brand' => ['class' => 'wcmlim-brand-select', 'type' => 'brand'],
                                            ];
                                            if (isset($type_map[$type])) {
                                                $select2class = $type_map[$type]['class'];
                                                $select2type = $type_map[$type]['type'];
                                                ?>
                                                <select class="wcmlim-rule_fields <?php echo $select2class; ?>" name="wcmlim_select_rule_value" multiple>
                                                    <?php if (!empty($values)) : ?>
                                                        <?php foreach ($values as $val) : ?>
                                                            <?php
                                                            $label = $val;
                                                            if ($select2type === 'product') {
                                                                $product = wc_get_product($val);
                                                                if ($product) {
                                                                    $label = $product->get_name();
                                                                }
                                                            } elseif ($select2type === 'category') {
                                                                $term = get_term($val, 'product_cat');
                                                                if ($term && !is_wp_error($term)) {
                                                                    $label = $term->name;
                                                                }
                                                            } elseif ($select2type === 'tag') {
                                                                $term = get_term($val, 'product_tag');
                                                                if ($term && !is_wp_error($term)) {
                                                                    $label = $term->name;
                                                                }
                                                            } elseif ($select2type === 'brand') {
                                                                $term = get_term($val, 'product_brand');
                                                                if ($term && !is_wp_error($term)) {
                                                                    $label = $term->name;
                                                                }
                                                            } elseif ($select2type === 'attribute') {
                                                                // Try to get attribute label
                                                                $attribute_taxonomies = wc_get_attribute_taxonomies();
                                                                $found = false;
                                                                foreach ($attribute_taxonomies as $tax) {
                                                                    $taxonomy = wc_attribute_taxonomy_name($tax->attribute_name);
                                                                    $term = get_term($val, $taxonomy);
                                                                    if ($term && !is_wp_error($term)) {
                                                                        $label = $term->name;
                                                                        $found = true;
                                                                        break;
                                                                    }
                                                                }
                                                                if (!$found) {
                                                                    $label = $val;
                                                                }
                                                            }
                                                            ?>
                                                            <option value="<?php echo esc_attr($val); ?>" selected><?php echo esc_html($label); ?></option>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </select>
                                            <?php } else { ?>
                                                <select class="wcmlim-rule_fields" name="wcmlim_select_rule_value">
                                                    <option>Select Value</option>
                                                </select>
                                            <?php } ?>

                                            <?php if ($index !== 0) : ?>
                                                <div><span class="dashicons dashicons-trash wcmlim-ruledelete"></span></div>
                                            <?php else : ?>
                                                <div></div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                                <button class="wcmlim-add_or_rule wcmlim-add_btn" type="button">+ OR </button>
                            </div>
                        <?php endforeach; ?>
                    <?php else : ?>
                        <div class="wcmlim-rulefilter_container wcmlim-add_and_rule_container">
                            <div></div>
                            <div class="wcmlim-rules_rows">  
                                <div class="wcmlim-filter_row wcmlim-initial">
                                    <select class="wcmlim-rule_fields" name="wcmlim_select_rule_type">
                                        <option>Select Type</option>
                                        <?php foreach ($rule_types as $label => $val) : ?>
                                            <option value="<?php echo $label; ?>"><?php echo $label; ?></option>
                                        <?php endforeach; ?>
                                    </select>

                                    <select class="wcmlim-rule_fields" name="wcmlim_select_rule_cond">
                                        <option>Includes</option>
                                        <option>Excludes</option>
                                    </select>

                                    <select class="wcmlim-rule_fields" name="wcmlim_select_rule_value">
                                        <option>Select Value</option>
                                    </select>
                                </div>
                            </div>
                            <button class="wcmlim-add_or_rule wcmlim-add_btn" type="button">+ OR </button>
                        </div>
                    <?php endif; ?>
                </div>
                <button class="wcmlim-add_and_rule wcmlim-add_btn" type="button">+ AND </button>
                <input type="hidden" id="wcmlim-ruleshidden" name="wcmlim_ruleshidden" value="">
            </div>
            <button class="wcmlim-saverules wcmlim-add_btn" type="button">Save Rules</button>   
        </div>
      </td>
    </tr>
    <?php } ?>
    
    <!-- SEO Settings Section -->
    <tr class="form-field">
      <th colspan="2" style="padding-left:0;">
        <h2 style="margin-top:20px;margin-bottom:10px;padding:10px;background:#f0f0f0;border-left:4px solid #0073aa;">
          🔍 SEO Optimization
        </h2>
      </th>
    </tr>
    
    <tr class="form-field term-meta-title-wrap">
      <th scope="row" valign="top">
        <label for="wcmlim_meta_title"><?php esc_html_e('Meta Title', 'wcmlim'); ?></label>
        <p class="description"><?php esc_html_e('Custom title for search engines (leave empty to use template)', 'wcmlim'); ?></p>
      </th>
      <td>
        <?php $meta_title = get_term_meta($term->term_id, 'wcmlim_meta_title', true); ?>
        <input type="text" class="form-control" id="wcmlim_meta_title" name="wcmlim_meta_title" 
               value="<?php echo esc_attr($meta_title); ?>" 
               placeholder="<?php echo esc_attr($term->name); ?> - <?php echo esc_attr(get_bloginfo('name')); ?>" 
               style="width:100%;max-width:600px;">
        <p class="description">
          💡 Variables: %location_name%, %site_name%, %location_city%, %location_state%
        </p>
      </td>
    </tr>
    
    <tr class="form-field term-meta-description-wrap">
      <th scope="row" valign="top">
        <label for="wcmlim_meta_description"><?php esc_html_e('Meta Description', 'wcmlim'); ?></label>
        <p class="description"><?php esc_html_e('SEO description (150-160 characters)', 'wcmlim'); ?></p>
      </th>
      <td>
        <?php $meta_description = get_term_meta($term->term_id, 'wcmlim_meta_description', true); ?>
        <textarea class="form-control" id="wcmlim_meta_description" name="wcmlim_meta_description" 
                  rows="3" style="width:100%;max-width:600px;" 
                  placeholder="Visit our <?php echo esc_attr($term->name); ?> store. Find products near you with local inventory and pickup options."><?php echo esc_textarea($meta_description); ?></textarea>
        <p class="description">
          <span id="meta-desc-count">0</span> characters (recommended: 150-160)
        </p>
      </td>
    </tr>
    
    <tr class="form-field term-schema-type-wrap">
      <th scope="row" valign="top">
        <label for="wcmlim_schema_type"><?php esc_html_e('Schema Type', 'wcmlim'); ?></label>
        <p class="description"><?php esc_html_e('Business type for structured data', 'wcmlim'); ?></p>
      </th>
      <td>
        <?php $schema_type = get_term_meta($term->term_id, 'wcmlim_schema_type', true); ?>
        <select class="form-control" id="wcmlim_schema_type" name="wcmlim_schema_type">
          <option value="LocalBusiness" <?php selected($schema_type, 'LocalBusiness'); ?>>Local Business</option>
          <option value="Store" <?php selected($schema_type, 'Store'); ?>>Store</option>
          <option value="RetailStore" <?php selected($schema_type, 'RetailStore'); ?>>Retail Store</option>
          <option value="DepartmentStore" <?php selected($schema_type, 'DepartmentStore'); ?>>Department Store</option>
          <option value="ClothingStore" <?php selected($schema_type, 'ClothingStore'); ?>>Clothing Store</option>
          <option value="ElectronicsStore" <?php selected($schema_type, 'ElectronicsStore'); ?>>Electronics Store</option>
          <option value="FurnitureStore" <?php selected($schema_type, 'FurnitureStore'); ?>>Furniture Store</option>
          <option value="Restaurant" <?php selected($schema_type, 'Restaurant'); ?>>Restaurant</option>
          <option value="Pharmacy" <?php selected($schema_type, 'Pharmacy'); ?>>Pharmacy</option>
        </select>
      </td>
    </tr>
    
    <tr class="form-field term-price-range-wrap">
      <th scope="row" valign="top">
        <label for="wcmlim_schema_price_range"><?php esc_html_e('Price Range', 'wcmlim'); ?></label>
        <p class="description"><?php esc_html_e('Price level indicator', 'wcmlim'); ?></p>
      </th>
      <td>
        <?php $price_range = get_term_meta($term->term_id, 'wcmlim_schema_price_range', true); ?>
        <select class="form-control" id="wcmlim_schema_price_range" name="wcmlim_schema_price_range">
          <option value="">Not specified</option>
          <option value="$" <?php selected($price_range, '$'); ?>>$ (Inexpensive)</option>
          <option value="$$" <?php selected($price_range, '$$'); ?>>$$ (Moderate)</option>
          <option value="$$$" <?php selected($price_range, '$$$'); ?>>$$$ (Expensive)</option>
          <option value="$$$$" <?php selected($price_range, '$$$$'); ?>>$$$$ (Very Expensive)</option>
        </select>
      </td>
    </tr>
    
    <tr class="form-field term-openstreetmap-id-wrap">
      <th scope="row" valign="top">
        <label for="wcmlim_openstreetmap_id"><?php esc_html_e('OpenStreetMap ID', 'wcmlim'); ?></label>
        <p class="description"><?php esc_html_e('OSM ID for alternative mapping', 'wcmlim'); ?></p>
      </th>
      <td>
        <?php $osm_id = get_term_meta($term->term_id, 'wcmlim_openstreetmap_id', true); ?>
        <input type="text" class="form-control" id="wcmlim_openstreetmap_id" name="wcmlim_openstreetmap_id" 
               value="<?php echo esc_attr($osm_id); ?>" 
               placeholder="e.g., way/123456789">
        <p class="description">
          Find on <a href="https://www.openstreetmap.org/" target="_blank">OpenStreetMap.org</a>
        </p>
      </td>
    </tr>
    
    <tr class="form-field term-canonical-url-wrap">
      <th scope="row" valign="top">
        <label for="wcmlim_canonical_url"><?php esc_html_e('Canonical URL', 'wcmlim'); ?></label>
        <p class="description"><?php esc_html_e('Custom canonical URL (optional)', 'wcmlim'); ?></p>
      </th>
      <td>
        <?php $canonical_url = get_term_meta($term->term_id, 'wcmlim_canonical_url', true); ?>
        <input type="url" class="form-control" id="wcmlim_canonical_url" name="wcmlim_canonical_url" 
               value="<?php echo esc_attr($canonical_url); ?>" 
               placeholder="https://example.com/location/<?php echo esc_attr($term->slug); ?>"
               style="width:100%;max-width:600px;">
      </td>
    </tr>
    
  </tbody>
</table>

<p class="alert-text" style="color: #e32!important;">Please fill all mandatory fields.</p>

<script type="text/javascript">
// Meta description character counter
jQuery(document).ready(function($) {
    function updateCharCount() {
        var count = $('#wcmlim_meta_description').val().length;
        $('#meta-desc-count').text(count);
        
        if (count < 150) {
            $('#meta-desc-count').css('color', '#d54e21');
        } else if (count > 160) {
            $('#meta-desc-count').css('color', '#d54e21');
        } else {
            $('#meta-desc-count').css('color', '#46b450');
        }
    }
    
    $('#wcmlim_meta_description').on('input', updateCharCount);
    updateCharCount();
});
</script>

<script type="text/javascript">
  
  // Add validation for mandatory fields in location edit 

jQuery(document).ready(function($) {

  var stateInitialized = false;
  var eventListenersSetup = false;
  window.wcmlimStateInitialized = false; // Global flag for external scripts
  
  // Function to setup event listeners after state initialization
  function setupEventListeners() {
    if (!eventListenersSetup) {
      jQuery("#postal_code, #name, #country, #locality, #administrative_area_level_1").on('input', function (e) {        
            validation_add_location();
        });
      eventListenersSetup = true;
    }
  }

    function validation_add_location() {
        // Don't run validation until state dropdown is properly initialized
        if (!stateInitialized) {
            console.log('WCMLIM: Validation skipped - state not initialized');
            return;
        }
        
        console.log('WCMLIM: Running validation');
        
        if ($(".taxonomy-locations").length > 0) {            

            var tag_name = $('#name').val();
            var postal_code = $('#postal_code').val();
            var country = $('#country').val();
            var locality = $('#locality').val();
            var administrative_area_level_1 = $('#administrative_area_level_1').val();
            var stateDropdownDisabled = $('#administrative_area_level_1').prop('disabled');

            console.log('WCMLIM: State dropdown disabled:', stateDropdownDisabled);
            console.log('WCMLIM: State value:', administrative_area_level_1);

            // Check for #submit button first
            var submitButton = $(".edit-tag-actions input[type='submit']");

            // If state dropdown is disabled (country has no states), don't require state value
            var stateValid = stateDropdownDisabled || administrative_area_level_1.trim() !== '';

            if ((postal_code.trim() !== '' && country.trim() !== '' && tag_name.trim() !== '' && locality.trim() !== '' && stateValid)) {              
              submitButton.removeAttr('disabled');
                $('.alert-text').hide();
                console.log('WCMLIM: Validation passed');
            } else {
                // if ($('.alert-text').length === 0) {
                //   $('<p class="alert-text" style="color: #e32!important;">Please fill all mandatory fields.</p>').insertBefore(submitButton);
                // }
                submitButton.attr("disabled", true);
                $('.alert-text').text('Please fill all mandatory fields.').show();
                console.log('WCMLIM: Validation failed');
            }
        }
    }

    // Initialize state dropdown based on current country selection
    var initial_country = $('#country').val();
    var state_dropdown = $('#administrative_area_level_1');
    
    // Store current state value for restoration
    state_dropdown.data('current-state', '<?php echo esc_js($state); ?>');
    
    if (initial_country) {
        // Check if state dropdown already has options (populated by PHP)
        var existingOptions = state_dropdown.find('option').length;
        
        if (existingOptions > 1) {
            // States already loaded from PHP, just mark as initialized
            console.log('WCMLIM: State dropdown already populated from PHP');
            state_dropdown.prop('disabled', false);
            state_dropdown.prop('required', true);
            stateInitialized = true;
            window.wcmlimStateInitialized = true;
            setupEventListeners();
            validation_add_location();
        } else {
            // No states loaded, trigger AJAX to check if country has states
            console.log('WCMLIM: Triggering AJAX to load states');
            $('#country').trigger('change');
        }
    } else {
        // If no country is selected, run initial validation
        stateInitialized = true;
        window.wcmlimStateInitialized = true;
        setupEventListeners();
        validation_add_location();
    }

    // Country State Dependent Dropdown functionality
    $('#country').on('change', function() {
        var country_code = $(this).val();
        var state_dropdown = $('#administrative_area_level_1');
        var no_states_notice = $('#no-states-notice');
        var current_state_value = state_dropdown.data('current-state') || '';
        
        // Clear existing options and hide notice
        state_dropdown.html('<option value=""><?php esc_html_e("Select State", "wcmlim"); ?></option>');
        no_states_notice.hide();
        
        if (country_code) {
            // Make AJAX call to get states
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'wcmlim_get_states',
                    country: country_code,
                    nonce: '<?php echo wp_create_nonce("wcmlim_get_states_nonce"); ?>'
                },
                success: function(response) {
                    if (response.success && response.data && Object.keys(response.data).length > 0) {
                        // Country has states, populate dropdown
                        $.each(response.data, function(code, name) {
                            var selected = (code == current_state_value) ? ' selected' : '';
                            state_dropdown.append('<option value="' + code + '"' + selected + '>' + name + '</option>');
                        });
                        state_dropdown.prop('disabled', false);
                        state_dropdown.prop('required', true);
                        no_states_notice.hide();
                    } else {
                        // Country has no states, disable dropdown and show notice
                        state_dropdown.prop('disabled', true);
                        state_dropdown.prop('required', false);
                        state_dropdown.val(''); // Clear any selected value
                        no_states_notice.show();
                    }
                    // Mark state as initialized and re-validate
                    stateInitialized = true;
                    window.wcmlimStateInitialized = true;
                    setupEventListeners();
                    validation_add_location();
                },
                error: function() {
                    console.log('Error loading states');
                    // On error, assume no states and disable dropdown
                    state_dropdown.prop('disabled', true);
                    state_dropdown.prop('required', false);
                    state_dropdown.val('');
                    no_states_notice.show();
                    // Mark state as initialized and re-validate
                    stateInitialized = true;
                    window.wcmlimStateInitialized = true;
                    setupEventListeners();
                    validation_add_location();
                }
            });
        } else {
            // No country selected, enable dropdown but don't show notice
            state_dropdown.prop('disabled', false);
            state_dropdown.prop('required', true);
            stateInitialized = true;
            window.wcmlimStateInitialized = true;
            setupEventListeners();
            validation_add_location();
        }
    });

    // WordPress Media Uploader for Location Image
    jQuery(document).ready(function($) {
        var mediaUploader;
        
        $('.wcmlim-upload-image-button').on('click', function(e) {
            e.preventDefault();
            
            var button = $(this);
            var targetInput = button.data('target');
            
            // If the uploader object has already been created, reopen the dialog
            if (mediaUploader) {
                mediaUploader.open();
                return;
            }
            
            // Extend the wp.media object
            mediaUploader = wp.media({
                title: 'Choose Location Image',
                button: {
                    text: 'Use this image'
                },
                multiple: false
            });
            
            // When a file is selected, run a callback
            mediaUploader.on('select', function() {
                var attachment = mediaUploader.state().get('selection').first().toJSON();
                $('#' + targetInput).val(attachment.url);
                
                // Update or add preview image
                var previewContainer = button.siblings('.wcmlim-image-preview');
                if (previewContainer.length) {
                    previewContainer.find('img').attr('src', attachment.url);
                } else {
                    button.after('<div class="wcmlim-image-preview" style="margin-top: 10px;"><img src="' + attachment.url + '" style="max-width: 200px; height: auto; display: block;"></div>');
                }
            });
            
            // Open the uploader dialog
            mediaUploader.open();
        });
    });
});
</script>