<?php

/**
 * Provide a admin area view for the plugin
 *
 * This file is used to markup the admin-facing aspects of the plugin.
 *
 * @link       http://www.techspawn.com
 * @since      1.0.0
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/admin/partials
 */


    if (get_option('wcmlim_license') == '' || get_option('wcmlim_license') == 'invalid') {
    ?>
        <script>
            window.location.href = "?page=multi-location-inventory-management";
        </script>
    <?php
    }

$table = new Multiloc_Product_Central();
$search = (isset($_GET['search'])) ? $_GET['search'] : '';
$page_number = isset($_GET['c_paged']) ? absint($_GET['c_paged']) : 1;
$table->prepare_items($search,$page_number);
$message = '';
if ('delete' === $table->current_action()) {
  $message = '<div class="updated below-h2" id="message"><p>' . sprintf(esc_html__('Items deleted: %d', 'wcmlim'), count($_REQUEST['id'])) . '</p></div>';
}
?>
  <div class="loader"></div>
  <div class="loader-message"><?php esc_html_e('Your products are updating, please wait...', 'wcmlim'); ?></div>
  <div class="loader-overlay"></div>
<style>
  .pctabs.nav-tab-wrapper .nav-tab a {
    text-decoration: none;
    color: #000;
  }
  #tab-3 #DataTables_Table_0_length {
    margin-bottom: 20px;
  }
  #tab-3 #DataTables_Table_0 {
    width: 100% !important;
  }
  #tab-3 table.fixed {
    table-layout: unset;
  }
  #tab-3 #DataTables_Table_0 .column-id,
  #tab-3 #DataTables_Table_0 .column-image {
    width: 30px !important;
  }
  #tab-3 #DataTables_Table_0 .column-name {
    width: 60px !important;
  }
  #tab-3 #DataTables_Table_0 .column-stock_status,
  #tab-3 #DataTables_Table_0 .column-manage_stock {
    width: 30px !important;
  }
  </style>
<div class="wrap">  
  <div class="pc-woocommerce-layout__header">
    <div class="pc-woocommerce-layout__header-wrapper">
      <h2 ><?php esc_html_e('Product Central', 'wcmlim') ?></h2>
    </div>
  </div>
  <?php esc_attr_e($message, 'wcmlim'); ?>

  <div class="PCtab">
    <div class="pctabs nav-tab-wrapper woo-nav-tab-wrapper">
      <a class="nav-tab tab-link <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-1' ? 'nav-tab-active' : ''; ?>" data-tabid="tab-1" href="<?php echo esc_url( add_query_arg('tab', 'tab-1') ); ?>">
        <div>
          <?php esc_html_e('Products Editor', 'wcmlim'); ?>
        </div>
       </a>

      <a class="nav-tab tab-link <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-2' ? 'nav-tab-active' : ''; ?>" data-tabid="tab-2" href="<?php echo esc_url( add_query_arg('tab', 'tab-2') ); ?>">
        <div>
          <?php esc_html_e('Settings', 'wcmlim'); ?>
        </div>
      </a>
     
      <a class="nav-tab tab-link <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-3' ? 'nav-tab-active' : ''; ?>" data-tabid="tab-3" href="<?php echo esc_url( add_query_arg('tab', 'tab-3') ); ?>">
        <div>
          <?php esc_html_e('Inventory Management', 'wcmlim'); ?>
        </div>
      </a>

      <a class="nav-tab tab-link <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-4' ? 'nav-tab-active' : ''; ?>" data-tabid="tab-4" href="<?php echo esc_url( add_query_arg('tab', 'tab-4') ); ?>">
        <div>
          <?php esc_html_e('Inventory Settings', 'wcmlim'); ?>
        </div>
      </a>
    </div>

    <div id="tab-1" class="tab-content <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-1' ? 'current' : ''; ?>">
      <form id="product-edit-table" method="GET">
        <input type="hidden" name="page" value="<?php echo esc_attr($_REQUEST['page']); ?>" />
        <input type="hidden" name="tab" value="tab-1" />
        <?php        
        $table->display();       
        ?>
      </form>
    </div>

    <div id="tab-2" class="tab-content <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-2' ? 'current' : ''; ?>">
      <form id="Product_Central_Setting" method="post" action="">
      <table style="width: 100%;">
          <tbody>
            <tr>
              <td style="width: 65%; vertical-align: top;">
              <div class="enable_all">
                <span class=""><?php esc_html_e('Enable All', 'wcmlim'); ?></span>&nbsp;
                <label class="switch"><input type="checkbox" id="Enable_ProdCentral_Control" ><span class="slider round"></span></label>
              </div>
              <div class="disable_all">
                <span class=""><?php esc_html_e('Disable All', 'wcmlim'); ?></span>&nbsp;
                <label class="switch"><input type="checkbox" id="Disable_ProdCentral_Control" ><span class="slider round"></span></label>
              </div>
                <h3><?php esc_html_e('Columns Settings', 'wcmlim'); ?></h3>
                <?php $get_col = $table->get_columns();
                $get_col_slug = $table->get_sortable_columns(); ?>
                <ul class="SIMS_fields ui-sortable">
                  <?php
                  global $wpdb;
                  $options_table = $wpdb->prefix . 'options';                 
                  $ProductCentralControlOptions = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . $options_table . "` WHERE `option_name`= '%s'", 'ProductCentralControlOptions'));
                  $PCFO = maybe_unserialize($ProductCentralControlOptions[0]->option_value);
                  foreach ($get_col as $index => $code) {
                    
                    if (isset($get_col_slug[$index])) {
                      if (is_array($get_col_slug[$index])) {
                        $col_slug = $get_col_slug[$index][0];
                      } else {
                        $col_slug = $get_col_slug[$index];
                      }
                    } else {
                      $col_slug = $index; // Use the index itself as the column slug if not defined in sortable columns
                    }
                    
                    if (isset($PCFO)) {
                      if (isset($PCFO[0]) && isset($PCFO[0][$col_slug])) {
                          $checkbox_val = $PCFO[0][$col_slug];
                      } elseif (isset($PCFO[$col_slug])) {
                          $checkbox_val = $PCFO[$col_slug];
                      } else {
                          $checkbox_val = ''; 
                      }
                  } else {
                      $checkbox_val = '';
                  }
                  
                    
                    if ($checkbox_val == 'Show') {
                      $checked_val = 'checked';
                    } else {
                      $checked_val = '';
                    }
                    echo '<li class="SIMS_options_li " id="' . $col_slug . '"><span class="Head_nm">' . $code . '</span><label class="switch"><input type="checkbox" id="' . $col_slug . '" ' . $checked_val . ' chech_status="' . $checkbox_val . '"><span class="slider round"></span></label></li>';
                  }
                  ?>

                </ul>
                <br>
                <input type="button" class="button button-primary button-primary" id="Submit_ProdCentral_Control" value="<?php esc_attr_e('Save all settings', 'wcmlim'); ?>">
              </td>
              <td style="width: 35%; vertical-align: top; padding-left: 7px;">                
              </td>
            </tr>
          </tbody>
        </table>
       
      </form>
    </div>

    <div id="tab-3" class="tab-content <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-3' ? 'current' : ''; ?>">
      <?php
        $table_2 = new Inventory_Manager_List_Table();
        $search = (isset($_GET['inv_search'])) ? $_GET['inv_search'] : '';
        $page_number = isset($_GET['inv_paged']) ? absint($_GET['inv_paged']) : 1;
        $table_2->prepare_items($search, $page_number);
      ?>
      <form method="get">
        <input type="hidden" name="page" value="<?php echo esc_attr($_REQUEST['page']); ?>" />
        <input type="hidden" name="tab" value="tab-3" />
        <?php $table_2->display(); ?>
      </form>
      <script>
          jQuery(document).ready(function ($) {
                      
        	// Triggering the script for inventory management where the stock management is changed
          jQuery(document).on('change', '.wcmlim-stock_manage', function () {
                var input = jQuery(this);
                var product_id = input.data('productid');
                var term_id = input.data('termid');
                var value = input.val();

                jQuery.ajax({
                    type: "POST",
                    url: multi_inventory.ajaxurl,
                    data: {
                        action: 'update_wcmlim_inventory_management',
                        product_id: product_id,
                        term_id: term_id,
                        stock: value,
                        security: multi_inventory.check_nonce
                    },
                    success: function (response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            console.warn('Update failed:', response.data);
                        }
                    }
                });
            });
            });
          document.addEventListener('DOMContentLoaded', function () {
            const toggles = document.querySelectorAll('.toggle-location-column');

            toggles.forEach(toggle => {
                toggle.addEventListener('click', function (e) {
                    e.stopPropagation(); // Prevent DataTable header click
                    const col = this.dataset.column;
                    const selector = 'tbody .column-' + col;

                    document.querySelectorAll(selector).forEach(cell => {
                        cell.style.visibility = (cell.style.visibility === 'hidden') ? 'visible' : 'hidden';
                    });

                    // Optional: toggle icon class
                    this.classList.toggle('dashicons-visibility');
                    this.classList.toggle('dashicons-hidden');
                });
            });
        });
        </script>
    </div>

    <div id="tab-4" class="tab-content <?php echo ( $_GET['tab'] ?? 'tab-1' ) === 'tab-4' ? 'current' : ''; ?>">
      <?php 
      $selected_locations = get_option('wcmlim_inventory_selected_locations', []);

      $locations = get_terms(array(
          'taxonomy'   => 'locations',
          'hide_empty' => false,
          'parent'     => 0
      ));

      if (!empty($locations)) {
          echo '<ul style="list-style: none; padding: 0;">';
          foreach ($locations as $location) {
              $checked = in_array($location->term_id, (array) $selected_locations) ? 'checked' : '';
              $id = 'location_' . esc_attr($location->term_id);
              echo '<li style="margin-bottom: 6px;">';
              echo '<label>';
              echo '<input type="checkbox" class="location-checkbox" id="' . $id . '" value="' . esc_attr($location->term_id) . '" ' . $checked . ' />';
              echo ' ' . esc_html($location->name);
              echo '</label>';
              echo '</li>';
          }
          echo '</ul>';
      } else {
          echo '<p>' . esc_html__('No locations found.', 'wcmlim') . '</p>';
      }
      ?>
      <button type="button" class="button button-primary" id="wcmlim-inv_locations"><?php esc_html_e('Save Locations', 'wcmlim'); ?></button>
  </div>

  </div>
</div>
<script>
  jQuery(document).ready(function ($) {
    jQuery('#wcmlim-inv_locations').click(function() {

      var selected = [];
      $('.location-checkbox:checked').each(function () {
        selected.push($(this).val());
      });

      jQuery.ajax({
                    type: "POST",
                    url: multi_inventory.ajaxurl,
                    data: {
                        action: 'save_inventory_selected_locations',
                        selected_locations: selected,
                        security: multi_inventory.check_nonce
                    },
                    success: function (response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            console.warn('Update failed:', response.data);
                        }
                    }
      });

    });
  });
</script>