<?php
?>
<?php
?>
<style>
  /* ——— Card + Layout ——— */
  .wcmlim-rules_container {
    padding: 0;
    margin: 0;
    border: none;
    box-shadow: none;
  }
  .wcmlim-settings-card {
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 12px;
    padding: 18px 20px;
    box-shadow: 0 2px 10px rgba(16,24,40,.04);
  }
  .wcmlim-card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 6px 2px 12px 2px;
  }
  .wcmlim-card-title {
    font-weight: 700;
    font-size: 18px;
    margin: 0;
  }
  .wcmlim-divider {
    height: 1px;
    background: #f0f0f0;
    margin: 10px 0 16px 0;
    border: 0;
  }

  /* ——— Section headings ——— */
  .wcmlim-section-title {
    font-weight: 800;
    letter-spacing: .02em;
    font-size: 14px;
    color: #111827;
    margin: 6px 0 10px 0;
    text-transform: uppercase;
  }

  /* ——— AND group container (each “box”) ——— */
  .wcmlim-rulefilter_container {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    padding: 14px 14px 10px 14px;
    margin: 10px 0 14px 0;
  }
  .wcmlim-rulerowdelete {
    float: right;
    margin: -4px -4px 6px 6px;
    padding: 2px;
    color: #6b7280;
  }
  .wcmlim-rulerowdelete .dashicons-trash {
    cursor: pointer;
  }

  /* ——— Rows inside a group (OR rows) ——— */
  .wcmlim-rules_rows {
    display: grid;
    gap: 10px;
  }
  .wcmlim-filter_row {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    gap: 10px;
    align-items: center;
  }
  .wcmlim-initial .dashicons-trash { display: none; }

  /* ——— Inputs ——— */
  .wcmlim-rule_fields {
    width: 100%;
    max-width: none !important;
    min-height: 36px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    padding: 6px 10px;
    font-size: 14px;
    background: #fff;
  }
  .wcmlim-rules_rows .select2-container {
    width: 100% !important;
  }

  /* ——— Link-style adders (“Add condition”, “Add ‘and’ group”) ——— */
  .wcmlim-addlink {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: transparent;
    border: 0;
    color: #2563eb;
    font-size: 14px;
    padding: 6px 0;
    cursor: pointer;
  }
  .wcmlim-addlink:hover { text-decoration: underline; }

  /* Keep original classes on buttons so JS keeps working */
  .wcmlim-add_or_rule,
  .wcmlim-add_and_rule {
    all: unset;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: #2563eb;
    font-size: 14px;
    cursor: pointer;
    padding: 6px 0;
  }
  .wcmlim-add_btn { /* preserve class for JS; restyled to link look */
    background: transparent;
    color: #2563eb;
    padding: 0;
    margin: 0;
    border: 0;
    border-radius: 0;
    font-size: 14px;
    font-weight: 500;
  }

  /* ——— Save button ——— */
  .wcmlim-saverules {
    float: none;
    display: block;
    width: 100%;
    margin-top: 18px;
    padding: 14px 18px;
    border-radius: 12px;
    background: #2563eb;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    border: 0;
    cursor: pointer;
    box-shadow: 0 1px 3px rgba(37, 99, 235, .25);
  }
  .wcmlim-saverules:hover { filter: brightness(1.04); }

  /* ——— Trash icon on each OR row ——— */
  .wcmlim-ruledelete .dashicons-trash,
  .dashicons-trash { cursor: pointer; color: #6b7280; }

  /* Responsive tweaks */
  @media (max-width: 840px) {
    .wcmlim-filter_row {
      grid-template-columns: 1fr;
    }
  }
</style>

<?php
  // Fetch saved rules
  $rules = get_option('wcmlim_saved_rules');
  $rules = maybe_unserialize($rules);

  // Helper for rule types
  $rule_types = [
    'Product' => 'product',
    'Product Category' => 'category',
    'Product Tag' => 'tag',
    'Product Attribute' => 'attribute',
    'Product Brand' => 'brand'
  ];
?>

<div id="tab-2" class="tab-pane" style="padding: 24px 40px; width: 90%;">
  <div class="wcmlim-settings-card">
    <!-- Header: title + toggle (right) -->
    <div class="wcmlim-card-header">
      <p class="wcmlim-card-title"><?php echo __('Enable Rules Filtering', 'wcmlim'); ?></p>
      <label class="switch">
        <input class="wcmlim-setting-option-des" type="checkbox" name="wcmlim_enable_rules" <?php checked(get_option('wcmlim_enable_rules', 'no'), 'yes'); ?>>
        <span class="slider round"></span>
      </label>
    </div>

    <hr class="wcmlim-divider" />

    <!-- CONDITIONS -->
    <div class="wcmlim-section">
      <div class="wcmlim-section-title"><?php echo __('Conditions', 'wcmlim'); ?></div>

      <div class="wcmlim-rules_container"><!-- keep class for JS -->
        <div class="wcmlim-rule_container"><!-- JS depends on this wrapper -->
          <?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'];

                    $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'],
                    ];
                    $initialClass = $index === 0 ? 'wcmlim-filter_row wcmlim-initial' : 'wcmlim-filter_row';
                  ?>
                  <div class="<?php echo $initialClass; ?>">
                    <!-- Type -->
                    <select class="wcmlim-rule_fields" name="wcmlim_select_rule_type">
                      <option><?php echo __('Select Type','wcmlim'); ?></option>
                      <?php foreach ($rule_types as $label => $val) : ?>
                        <option value="<?php echo $label; ?>" <?php selected($type, $label); ?>><?php echo $label; ?></option>
                      <?php endforeach; ?>
                    </select>

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

                    <!-- Value (Select2 when applicable) -->
                    <?php 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)) :
                          foreach ($values as $val) :
                            $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') {
                              $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; endif; ?>
                      </select>
                    <?php else : ?>
                      <select class="wcmlim-rule_fields" name="wcmlim_select_rule_value">
                        <option><?php echo __('Select Value','wcmlim'); ?></option>
                      </select>
                    <?php endif; ?>

                    <!-- Row delete (hidden for first) -->
                    <?php if ($index !== 0) : ?>
                      <div class="wcmlim-ruledelete"><span class="dashicons dashicons-trash wcmlim-ruledelete"></span></div>
                    <?php else : ?>
                      <div></div>
                    <?php endif; ?>
                  </div>
                  <?php endforeach; ?>
                </div>

                <!-- Add condition link -->
                <button class="wcmlim-add_or_rule wcmlim-add_btn" type="button">+ OR</button>
              </div>
            <?php endforeach; ?>
          <?php else : ?>
            <!-- Empty state = one empty AND group -->
            <div class="wcmlim-rulefilter_container wcmlim-add_and_rule_container">
              <div class="wcmlim-rules_rows">
                <div class="wcmlim-filter_row wcmlim-initial">
                  <select class="wcmlim-rule_fields" name="wcmlim_select_rule_type">
                    <option><?php echo __('Select Type','wcmlim'); ?></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><?php echo __('Includes','wcmlim'); ?></option>
                    <option><?php echo __('Excludes','wcmlim'); ?></option>
                  </select>

                  <select class="wcmlim-rule_fields" name="wcmlim_select_rule_value">
                    <option><?php echo __('Select Value','wcmlim'); ?></option>
                  </select>

                  <div></div>
                </div>
              </div>

              <button class="wcmlim-add_or_rule wcmlim-add_btn" type="button">Add condition</button>
            </div>
          <?php endif; ?>
        </div>

        <!-- Add AND group link -->
        <button class="wcmlim-add_and_rule wcmlim-add_btn" type="button">Add ‘and’ group</button>

        <!-- (Hidden) JSON + Save CTA -->
        <input type="hidden" id="wcmlim-ruleshidden" name="wcmlim_ruleshidden" value="">
        
        <button class="wcmlim-saverules wcmlim-add_btn" type="button">Save Changes</button>
      </div>
    </div>
  </div>
</div>

    <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);

            // Get the enable_rules checkbox value
            const enableRules = $('input[name="wcmlim_enable_rules"]').is(':checked') ? 'yes' : 'no';

            $.post(ajaxurl, {
                action: 'save_wcmlim_rules',
                rules: rulesJson,
                enable_rules: enableRules,
                security: '<?php echo wp_create_nonce('wcmlim_settings_nonce'); ?>'
            }, function(response) {
                alert('Saved Successfully !!!');
            });

        });

        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">+ OR </button>
                </div>`);
        });
                // 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>