<?php
/**
 * Inventory Manager List Table Class
 *
 * This class handles the display of the inventory manager list table in the WordPress admin.
 *
 * @package Inventory_Manager
 */
if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

class Inventory_Manager_List_Table extends WP_List_Table {

    public function __construct() {
        parent::__construct([
            'singular' => __('Product', 'textdomain'),
            'plural'   => __('Products', 'textdomain'),
            'ajax'     => false
        ]);
    }

    /**
     * Override get_pagenum to use custom pagination parameter
     * 
     * @return int Current page number
     */
    public function get_pagenum() {
        $pagenum = isset($_REQUEST['inv_paged']) ? absint($_REQUEST['inv_paged']) : 0;
        if (isset($this->_pagination_args['total_pages']) && $pagenum > $this->_pagination_args['total_pages']) {
            $pagenum = $this->_pagination_args['total_pages'];
        }
        return max(1, $pagenum);
    }

    /**
     * Override pagination display to use custom parameter name
     * 
     * @param string $which Position of pagination (top or bottom)
     */
    protected function pagination($which) {
        if (empty($this->_pagination_args)) {
            return;
        }

        $total_items = $this->_pagination_args['total_items'];
        $total_pages = $this->_pagination_args['total_pages'];
        $infinite_scroll = false;

        if (isset($this->_pagination_args['infinite_scroll'])) {
            $infinite_scroll = $this->_pagination_args['infinite_scroll'];
        }

        if ('top' === $which && $total_pages > 1) {
            $this->screen->render_screen_reader_content('heading_pagination');
        }

        $output = '<span class="displaying-num">' . sprintf(
            _n('%s item', '%s items', $total_items),
            number_format_i18n($total_items)
        ) . '</span>';

        $current = $this->get_pagenum();
        $removable_query_args = wp_removable_query_args();

        $current_url = set_url_scheme('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        $current_url = remove_query_arg($removable_query_args, $current_url);
        
        // Ensure tab parameter is preserved
        if (!isset($_GET['tab'])) {
            $current_url = add_query_arg('tab', 'tab-3', $current_url);
        }

        $page_links = array();

        $total_pages_before = '<span class="paging-input">';
        $total_pages_after  = '</span></span>';

        $disable_first = $disable_last = $disable_prev = $disable_next = false;

        if ($current == 1) {
            $disable_first = true;
            $disable_prev  = true;
        }
        if ($current == 2) {
            $disable_first = true;
        }
        if ($current == $total_pages) {
            $disable_last = true;
            $disable_next = true;
        }
        if ($current == $total_pages - 1) {
            $disable_last = true;
        }

        if ($disable_first) {
            $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&laquo;</span>';
        } else {
            $page_links[] = sprintf(
                "<a class='first-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
                esc_url(remove_query_arg('inv_paged', $current_url)),
                __('First page'),
                '&laquo;'
            );
        }

        if ($disable_prev) {
            $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&lsaquo;</span>';
        } else {
            $page_links[] = sprintf(
                "<a class='prev-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
                esc_url(add_query_arg('inv_paged', max(1, $current - 1), $current_url)),
                __('Previous page'),
                '&lsaquo;'
            );
        }

        if ('bottom' === $which) {
            $html_current_page  = $current;
            $total_pages_before = '<span class="screen-reader-text">' . __('Current Page') . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
        } else {
            $html_current_page = sprintf(
                "%s<input class='current-page' id='current-page-selector' type='text' name='inv_paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
                '<label for="current-page-selector" class="screen-reader-text">' . __('Current Page') . '</label>',
                $current,
                strlen($total_pages)
            );
        }
        $html_total_pages = sprintf("<span class='total-pages'>%s</span>", number_format_i18n($total_pages));
        $page_links[]     = $total_pages_before . sprintf(_x('%1$s of %2$s', 'paging'), $html_current_page, $html_total_pages) . $total_pages_after;

        if ($disable_next) {
            $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&rsaquo;</span>';
        } else {
            $page_links[] = sprintf(
                "<a class='next-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
                esc_url(add_query_arg('inv_paged', min($total_pages, $current + 1), $current_url)),
                __('Next page'),
                '&rsaquo;'
            );
        }

        if ($disable_last) {
            $page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">&raquo;</span>';
        } else {
            $page_links[] = sprintf(
                "<a class='last-page button' href='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></a>",
                esc_url(add_query_arg('inv_paged', $total_pages, $current_url)),
                __('Last page'),
                '&raquo;'
            );
        }

        $pagination_links_class = 'pagination-links';
        if (!empty($infinite_scroll)) {
            $pagination_links_class .= ' hide-if-js';
        }
        $output .= "\n<span class='$pagination_links_class'>" . join("\n", $page_links) . '</span>';

        if ($total_pages) {
            $page_class = $total_pages < 2 ? ' one-page' : '';
        } else {
            $page_class = ' no-pages';
        }
        $this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";

        echo $this->_pagination;
    }

public function get_columns() {
    $columns = array(
        'cb'             => '<input type="checkbox" />',
        'id'             => __('ID'),
        'image'          => __('Image'),
        'name'           => __('Name'),
        'stock_status'   => __('Stock Status'),
        'manage_stock'   => __('Manage Stock'),
    );

    // Get selected location IDs from the options table
    $selected_location_ids = get_option('wcmlim_inventory_selected_locations', []);
    error_log('Inventory get_columns - Selected location IDs: ' . print_r($selected_location_ids, true));

    if (!empty($selected_location_ids) && is_array($selected_location_ids)) {
        $locations = get_terms(array(
            'taxonomy'   => 'locations',
            'hide_empty' => false,
            'include'    => $selected_location_ids,
            'parent'     => 0
        ));

        error_log('Inventory get_columns - Found locations: ' . print_r($locations, true));

        foreach ($locations as $location) {
            $columns['location_' . $location->term_id] = esc_html($location->name);
            error_log('Added column: location_' . $location->term_id . ' = ' . $location->name);
        }
    }

    $columns['total_stock'] = __('Total Stock');
    
    error_log('Inventory get_columns - Final columns: ' . print_r(array_keys($columns), true));
    return $columns;
}


    public function get_sortable_columns() {
        return [
            'id'          => ['id', false],
            'name'        => ['name', false],
            'total_stock' => ['total_stock', false],
        ];
    }

    public function get_hidden_columns() {
        // Since we're controlling location visibility through wcmlim_inventory_selected_locations
        // and the get_columns() method already filters based on selected locations,
        // we don't need to hide any columns here
        return array();
    }

    public function prepare_items($search = '', $paged = 1) {
        // Get per page value from screen options
        $user_id = get_current_user_id();
        $per_page = get_user_meta($user_id, 'product_central_pagination', true);
        if (empty($per_page) || $per_page < 1) {
            $per_page = 20; // Default value
        }
        
        // Use parameters if provided, otherwise read from GET
        if (empty($search)) {
            $search = isset($_GET['inv_search']) ? sanitize_text_field($_GET['inv_search']) : '';
        }
        // Use the passed paged parameter, but fallback to GET parameter if not provided properly
        if ($paged <= 0) {
            $paged = isset($_GET['inv_paged']) ? absint($_GET['inv_paged']) : 1;
        }
        // Get total count for pagination
        $total_items = $this->get_total_products_count($search);

        // Get products for current page
        $data = $this->get_sample_data($search, $per_page, $paged);
        $this->items = $data;
        
        // Set up column headers
        $columns = $this->get_columns();
        $hidden = $this->get_hidden_columns();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = [$columns, $hidden, $sortable];
        
        // Set up pagination
        $this->set_pagination_args([
            'total_items' => $total_items,
            'per_page'    => $per_page,
            'total_pages' => ceil($total_items / $per_page)
        ]);
    }

    /**
     * Get total count of products for pagination
     */
    private function get_total_products_count($search = '') {
        global $wpdb;
        
        // First, get all regular products (simple, grouped, external)
        $args = [
            'limit' => -1,
            'status' => 'publish',
            'type' => ['simple', 'grouped', 'external'],
            'return' => 'ids'
        ];
        
        if (!empty($search)) {
            $args['s'] = $search;
        }
        
        $product_ids = wc_get_products($args);
        
        // Now get all variable products to extract their variations
        $variable_args = [
            'limit' => -1,
            'status' => 'publish',
            'type' => 'variable',
            'return' => 'ids'
        ];
        
        $variable_ids = wc_get_products($variable_args);
        
        // Get count of variations for all variable products
        $variation_count = 0;
        if (!empty($variable_ids)) {
            $variation_query = "
                SELECT COUNT(ID)
                FROM {$wpdb->posts}
                WHERE post_type = 'product_variation'
                AND post_status = 'publish'
                AND post_parent IN (" . implode(',', $variable_ids) . ")";
                
            if (!empty($search)) {
                $like_search = '%' . $wpdb->esc_like($search) . '%';
                $variation_query .= $wpdb->prepare(
                    " AND (post_title LIKE %s OR ID IN (
                        SELECT post_id FROM {$wpdb->postmeta} 
                        WHERE meta_key = '%s' AND meta_value LIKE %s
                    ))",
                    $like_search,
                    '_sku',
                    $like_search
                );
            }
            
            $variation_count = (int) $wpdb->get_var($variation_query);
        }
        
        // Return total count of regular products + variations
        return count($product_ids) + $variation_count;
    }

    public function column_cb($item) {
        return sprintf('<input type="checkbox" name="product[]" value="%s" />', $item['id']);
    }

    public function column_image($item) {
        return sprintf('<img src="%s" width="40" height="40" />', esc_url($item['image']));
    }

    public function column_name($item) {
        $edit_link = get_edit_post_link($item['id']);
        return sprintf(
            '<a href="%s" target="_blank">%s</a>',
            esc_url($edit_link),
            esc_html($item['name'])
        );
    }

    public function column_default($item, $column_name) {
        if (strpos($column_name, 'location_') === 0) {
            $term_id = (int) str_replace('location_', '', $column_name);
            $product_id = $item['id'];

            // Get all linked locations (IDs)
            $linked_loc = wp_get_object_terms($product_id, 'locations', array('fields' => 'ids'));

            if (in_array($term_id, $linked_loc)) {
                // If linked, show input field
                $stock = get_post_meta($product_id, "wcmlim_stock_at_{$term_id}", true);
                $stock_value = $stock !== '' ? esc_attr($stock) : 0;

                return sprintf(
                    '<input type="number" name="stock" class="wcmlim-stock_manage" value="%d" min="0" style="width: 60px;" data-termid="%d" data-productid="%d"/>',
                    $stock_value,
                    $term_id,
                    $product_id
                );
            } else {
                // If not linked, show text
                return '<span style="color:#999;">Not linked</span>';
            }
        }

        // Other columns
        if ($column_name === 'stock_status') {
            $total_stock = get_post_meta($item['id'], "_stock", true);
            return $total_stock . ' ' . get_post_meta($item['id'], "_stock_status", true);
        } elseif ($column_name === 'manage_stock') {
            return get_post_meta($item['id'], "_manage_stock", true) ? 'Yes' : 'No';
        }

        return $item[$column_name] ?? '';
    }

    /**
     * Count total regular products (not variations) with current filters
     * This is needed for proper variation offset calculation
     */
    private function count_regular_products_total($search = '') {
        // Get count of regular products (not variations) with current filters
        $args = [
            'limit' => -1,
            'status' => 'publish',
            'type' => ['simple', 'grouped', 'external'],
            'return' => 'ids',
        ];
        
        // Apply same filters as main query
        if (!empty($search)) {
            $args['s'] = $search;
        }
        
        $product_ids = wc_get_products($args);
        return count($product_ids);
    }

    private function get_sample_data($search = '', $per_page = 20, $paged = 1) {
        global $wpdb;
        $data = [];
        $offset = ($paged - 1) * $per_page;
        $count = 0;
        
        // Get sorting parameters
        $orderby = isset($_REQUEST['orderby']) ? sanitize_sql_orderby($_REQUEST['orderby']) : 'ID';
        $order = isset($_REQUEST['order']) && in_array($_REQUEST['order'], array('asc', 'desc')) ? $_REQUEST['order'] : 'asc';
        
        // Step 1: First get regular products (simple, grouped, external)
        $regular_args = [
            'limit' => $per_page,
            'offset' => $offset,
            'status' => 'publish',
            'type' => ['simple', 'grouped', 'external'],
            'orderby' => $orderby,
            'order' => $order,
            'return' => 'objects'
        ];

        if (!empty($search)) {
            $regular_args['s'] = $search;
        }
        
        $regular_products = wc_get_products($regular_args);
        
        // Add regular products to data
        foreach ($regular_products as $product) {
            if ($count >= $per_page) break;
            
            // Get image URL with fallback to placeholder
            $image_url = wp_get_attachment_url($product->get_image_id());
            if (!$image_url) {
                $image_url = wc_placeholder_img_src();
            }
            
            // Get stock information
            $stock_quantity = $product->get_stock_quantity();
            $stock_status = $product->get_stock_status();
            
            $data[] = [
                'id' => $product->get_id(),
                'image' => $image_url,
                'name' => $product->get_name(),
                'manage_stock' => $product->get_manage_stock() ? '1' : '0',
                'stock_status' => $stock_quantity !== null ? $stock_quantity . ' (' . $stock_status . ')' : $stock_status,
                'total_stock' => $stock_quantity ?? '—',
            ];
            
            $count++;
        }
        
        // If we haven't filled the page yet, get variations
        if ($count < $per_page) {
            // Step 2: Get variable products
            $variable_args = [
                'limit' => -1, // We'll manually handle pagination for variations
                'status' => 'publish',
                'type' => 'variable',
                'return' => 'ids'
            ];
            
            $variable_ids = wc_get_products($variable_args);
            
            if (!empty($variable_ids)) {
                // Calculate how many more items we need
                $remaining = $per_page - $count;
                
                // Query variations directly with pagination
                $variations_query = "
                    SELECT ID, post_title, post_parent
                    FROM {$wpdb->posts} 
                    WHERE post_type = 'product_variation'
                    AND post_status = 'publish'
                    AND post_parent IN (" . implode(',', $variable_ids) . ")";
                
                // Add search condition if needed
                if (!empty($search)) {
                    $like_search = '%' . $wpdb->esc_like($search) . '%';
                    $variations_query .= $wpdb->prepare(
                        " AND (post_title LIKE %s OR ID IN (
                            SELECT post_id FROM {$wpdb->postmeta} 
                            WHERE meta_key = '%s' AND meta_value LIKE %s
                        ))",
                        $like_search,
                        '_sku',
                        $like_search
                    );
                }
                
                // Calculate proper variation offset
                $total_regular_count = $this->count_regular_products_total($search);
                $variation_offset = max(0, $offset - $total_regular_count);
                
                // Add sorting and pagination
                $variations_query .= " ORDER BY ID {$order} LIMIT {$remaining} OFFSET {$variation_offset}";
                
                $variations = $wpdb->get_results($variations_query);
                
                // Add variations to data
                foreach ($variations as $variation) {
                    $variation_product = wc_get_product($variation->ID);
                    if (!$variation_product) continue;
                    
                    // Get image URL with fallback to placeholder
                    $image_url = wp_get_attachment_url($variation_product->get_image_id());
                    if (!$image_url) {
                        $image_url = wc_placeholder_img_src();
                    }
                    
                    // Get stock information
                    $stock_quantity = $variation_product->get_stock_quantity();
                    $stock_status = $variation_product->get_stock_status();
                    
                    $data[] = [
                        'id' => $variation_product->get_id(),
                        'image' => $image_url,
                        'name' => $variation_product->get_name(),
                        'manage_stock' => $variation_product->get_manage_stock() ? '1' : '0',
                        'stock_status' => $stock_quantity !== null ? $stock_quantity . ' (' . $stock_status . ')' : $stock_status,
                        'total_stock' => $stock_quantity ?? '—',
                    ];
                    
                    $count++;
                    if ($count >= $per_page) break;
                }
            }
        }

        return $data;
    }

    function extra_tablenav($which) {
        global $wpdb;
        ?>
        <div class="alignleft actions">
            <input type="text" class="inventory_search_search_input" name="inv_search" placeholder="<?php esc_attr_e('Search products...', 'textdomain'); ?>" value="<?php echo isset($_GET['inv_search']) ? esc_attr($_GET['inv_search']) : ''; ?>" />
        </div>
        <div class="alignleft actions bulkactions">
            <a href="?page=wcmlim-product-central&tab=tab-3"><input type="button" class="button" id="wcmlim-rest" value="Reset"></a>
        </div>
        <?php
    }
}
