<?php


namespace SMFWC\Shiperman\Orders_List_Table;

use SMFWC\Shiperman\API\SMFWC_Shiperman_API;

if (!defined('ABSPATH')) exit;

if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

class SMFWC_Shiperman_Orders_List_Table extends \WP_List_Table
{
    private $total_items;

    public function __construct()
    {
        parent::__construct([
            'singular' => __('Order', 'shiperman-for-woocommerce'),
            'plural'   => __('Orders', 'shiperman-for-woocommerce'),
            'ajax'     => false,
        ]);
    }

    /**
     * Define the columns for the table.
     */
    public function get_columns()
    {
        return [
            // 'cb'           => '<input type="checkbox" />', // Checkbox column for bulk actions
            'order_number' => __('Order Number', 'shiperman-for-woocommerce'),
            'internal_order_number' => __('Internal Number', 'shiperman-for-woocommerce'),
            'created'      => __('Created', 'shiperman-for-woocommerce'),
            'status'       => __('Status', 'shiperman-for-woocommerce'),
            'sender'       => __('Sender', 'shiperman-for-woocommerce'),
            'email'        => __('Email', 'shiperman-for-woocommerce'),
            'parcel_inside' => __('Parcel Inside', 'shiperman-for-woocommerce'),
            'price' => __('Price (EUR)', 'shiperman-for-woocommerce')
        ];
    }

    /**
     * Define sortable columns.
     */
    protected function get_sortable_columns()
    {
        return [
            'order_number' => ['order_number', true],
            'internal_order_number' => ['order_number', true],
            'created'      => ['created', false],
            'status'       => ['status', false],
        ];
    }

    /**
     * Prepare the items for display.
     */
    public function prepare_items()
    {
        $per_page     = 10;
        $current_page = $this->get_pagenum();

        $this->_column_headers = [
            $this->get_columns(),
            [], // hidden columns
            $this->get_sortable_columns(),
            $this->get_primary_column_name(),
        ];

        // Add search box functionality
        $search_term = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';

        // Display the search box (output will be captured when the page renders)
        if (!empty($search_term)) {
            echo '<p>Search results for: <strong>' . esc_html($search_term) . '</strong></p>';
        }

        $this->items = $this->fetch_orders_data($per_page, $current_page);
        $this->total_items  = $this->get_total_items_count();

        //var_dump($this->items);
        $this->set_pagination_args([
            'total_items' => $this->total_items,
            'per_page'    => $per_page,
        ]);
    }

    /**
     * Fetch orders data from Shipperman API.
     */
    private function fetch_orders_data($per_page = 10, $page_number = 1)
    {
        $current_user_id = get_current_user_id();
        $token = $_SESSION['shiperman_jwt_token'] ?? '';

        // Get search term if any
        $search_term = isset($_REQUEST['s']) ? sanitize_text_field(wp_unslash($_REQUEST['s'])) : '';

        // Create cache key (without search term for initial data fetch)
        $cache_key = "smfwc_shipperman_orders_data_{$current_user_id}_" . md5($token);
        $cache_expiration = 600; // 10 minutes

        // Get cached data (all items)
        $all_orders = get_transient($cache_key);

        // If no cached data, fetch from API
        if ($all_orders === false) {
            // Fetch all orders or a larger batch (adjust size parameter as needed)
            $endpoint = "plugin/orders?page=1&size=100"; // Larger batch size

            $shiperman_api = SMFWC_Shiperman_API::get_instance();
            $response = $shiperman_api->make_authenticated_request($endpoint, 'GET');

            if (!$response || $response['status'] !== 'success' || empty($response['data']['items'])) {
                return [];
            }

            // Format all data
            $all_orders = array_map(function ($item) {
                // Same formatting logic as your original method
                $order_status_code = $item['status'] ?? null;
                $status_map = [
                    0 => 'Created',
                    1 => 'Processing',
                    2 => 'Successful'
                ];

                $order_status_text = isset($status_map[$order_status_code]) ? $status_map[$order_status_code] : 'Unknown';
                $order_id = $item['internalId'] ?? '';
                $reference_id = $item['referenceId'] ?? 'N/A';
                $total_price = isset($item['items']) && is_array($item['items']) ? array_sum(array_column($item['items'], 'price')) : 0;

                return [
                    'order_number' => $reference_id,
                    'internal_order_number' => $order_id,
                    'created' => gmdate('Y-m-d H:i:s', $item['dateCreated'] ?? 0),
                    'status' => $order_status_text,
                    'sender' => $item['recipient']['name'] ?? '',
                    'email' => $item['recipient']['email'] ?? '',
                    'parcel_inside' => implode(', ', array_column($item['items'], 'id') ?? []),
                    'price' => $total_price,
                ];
            }, $response['data']['items']);

            // Cache all orders
            set_transient($cache_key, $all_orders, $cache_expiration);

            // Store total count
            $this->total_items = $response['data']['total'] ?? count($all_orders);
        } else {
            // If using cached data, set the total items
            $this->total_items = count($all_orders);
        }

        // Apply search filter if search term is provided
        $filtered_orders = $all_orders;
        if (!empty($search_term)) {
            $filtered_orders = array_filter($all_orders, function ($item) use ($search_term) {
                // Convert search term and item values to lowercase for case-insensitive search
                $search_term = strtolower($search_term);

                // Search in relevant fields - add more fields as needed
                return
                    strpos(strtolower($item['order_number']), $search_term) !== false ||
                    strpos(strtolower($item['internal_order_number']), $search_term) !== false ||
                    strpos(strtolower($item['sender']), $search_term) !== false ||
                    strpos(strtolower($item['email']), $search_term) !== false ||
                    strpos(strtolower($item['status']), $search_term) !== false ||
                    strpos(strtolower($item['parcel_inside']), $search_term) !== false;
            });

            // Update total items count for pagination
            $this->total_items = count($filtered_orders);
        }

        // Apply pagination manually
        $offset = ($page_number - 1) * $per_page;
        return array_slice($filtered_orders, $offset, $per_page);
    }


    /**
     * Get total items count from the API.
     */
    private function get_total_items_count()
    {
        return $this->total_items;
    }

    /**
     * Render the checkbox column.
     */
    public function column_cb($item)
    {
        return sprintf('<input type="checkbox" name="order[]" value="%s" />', $item['order_number']);
    }

    /**
     * Render each column.
     */
    // protected function column_default($item, $column_name)
    // {

    //     switch ($column_name) {
    //         case 'order_number':
    //             return esc_html($item['order_number']);
    //         case 'internal_order_number':
    //             return esc_html($item['internal_order_number']);
    //         case 'created':
    //             return esc_html($item['created']);
    //         case 'status':
    //             return esc_html((string) $item['status']);  // Convert integer to string
    //         case 'sender':
    //             return esc_html($item['sender']);
    //         case 'email':
    //             return esc_html($item['email']);
    //         case 'parcel_inside':
    //             return esc_html($item['parcel_inside']);
    //         case 'price':
    //             return esc_html($item['price']);
    //         default:
    //             return print_r($item, true); // For any unexpected column
    //     }
    // }

    /**
     * Display additional filters
     */
    public function extra_tablenav($which)
    {
        if ($which !== 'top') {
            return;
        }

        // Get all statuses (unique values)
        $statuses = [];
        $cache_key = "smfwc_shipperman_orders_data_" . get_current_user_id() . "_" . md5($_SESSION['shiperman_jwt_token'] ?? '');
        $all_orders = get_transient($cache_key);

        if ($all_orders) {
            foreach ($all_orders as $order) {
                if (!in_array($order['status'], $statuses) && !empty($order['status'])) {
                    $statuses[] = $order['status'];
                }
            }
        }

        // Status filter dropdown
        $current_status = isset($_REQUEST['filter_status']) ? sanitize_text_field($_REQUEST['filter_status']) : '';
?>
        <div class="alignleft actions">
            <label for="filter-by-status" class="screen-reader-text"><?php esc_html_e('Filter by status', 'shiperman-for-woocommerce'); ?></label>
            <select name="filter_status" id="filter-by-status">
                <option value=""><?php esc_html_e('All Statuses', 'shiperman-for-woocommerce'); ?></option>
                <?php
                foreach ($statuses as $status) {
                    printf(
                        '<option value="%s" %s>%s</option>',
                        esc_attr($status),
                        selected($status, $current_status, false),
                        esc_html($status)
                    );
                }
                ?>
            </select>

            <?php
            // Date filter
            $from_date = isset($_REQUEST['filter_date_from']) ? sanitize_text_field($_REQUEST['filter_date_from']) : '';
            $to_date = isset($_REQUEST['filter_date_to']) ? sanitize_text_field($_REQUEST['filter_date_to']) : '';
            ?>

            <label for="filter-date-from" class="screen-reader-text"><?php esc_html_e('From date', 'shiperman-for-woocommerce'); ?></label>
            <input type="date" id="filter-date-from" name="filter_date_from" value="<?php echo esc_attr($from_date); ?>" placeholder="<?php esc_attr_e('From', 'shiperman-for-woocommerce'); ?>" />

            <label for="filter-date-to" class="screen-reader-text"><?php esc_html_e('To date', 'shiperman-for-woocommerce'); ?></label>
            <input type="date" id="filter-date-to" name="filter_date_to" value="<?php echo esc_attr($to_date); ?>" placeholder="<?php esc_attr_e('To', 'shiperman-for-woocommerce'); ?>" />

            <?php submit_button(__('Filter', 'shiperman-for-woocommerce'), '', 'filter_action', false); ?>

            <?php
            // Only show reset button if any filter is active
            if (!empty($_REQUEST['s']) || !empty($_REQUEST['filter_status']) || !empty($_REQUEST['filter_date_from']) || !empty($_REQUEST['filter_date_to'])) {
                $reset_url = remove_query_arg(['s', 'filter_status', 'filter_date_from', 'filter_date_to', 'filter_action']);
                echo '<a href="' . esc_url($reset_url) . '" class="button">' . esc_html__('Reset Filters', 'shiperman-for-woocommerce') . '</a>';
            }
            ?>
        </div>
<?php
    }

    /**
     * Add search functionality.
     */
    public function prepare_search_query($query)
    {
        if (isset($_REQUEST['s'])) {
            $search = sanitize_text_field(wp_unslash($_REQUEST['s']));
            $query['search'] = $search;
        }
        return $query;
    }

    protected function column_default($item, $column_name)
    {
        $value = $item[$column_name];

        // If search term exists, highlight it
        if (isset($_REQUEST['s']) && !empty($_REQUEST['s'])) {
            $search = sanitize_text_field(wp_unslash($_REQUEST['s']));
            $value = preg_replace(
                '/(' . preg_quote($search, '/') . ')/i',
                '<span class="search-highlight">$1</span>',
                $value
            );
        }

        return $value;
    }
}
