<?php

namespace orderflow\Admin\Incomplete;
class Incomplete
{
    public function __construct()
    {
        add_action('admin_init', array( $this,  'orderflow_handle_settings_form' ) );
        add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'));


        add_action('wp_ajax_update_incomplete_status', array($this, 'handle_update_incomplete_status'));
        add_action('wp_ajax_nopriv_update_incomplete_status', array($this, 'handle_update_incomplete_status'));


        add_action('wp_ajax_delete_incomplete_orders', array($this, 'handle_delete_incomplete_orders'));
        add_action('wp_ajax_nopriv_delete_incomplete_orders', array($this, 'handle_delete_incomplete_orders'));

        add_action('wp_ajax_bulk_mark_incomplete_orders', array($this, 'handle_bulk_mark_incomplete_orders'));
        add_action('wp_ajax_nopriv_bulk_mark_incomplete_orders', array($this, 'handle_bulk_mark_incomplete_orders'));

        add_action('wp_ajax_bulk_delete_incomplete_orders', array($this, 'handle_bulk_delete_incomplete_orders'));
        add_action('wp_ajax_nopriv_bulk_delete_incomplete_orders', array($this, 'handle_bulk_delete_incomplete_orders'));


        add_action('wp_ajax_update_abandoned_note', array($this, 'handle_update_abandoned_note'));
        add_action('wp_ajax_nopriv_update_abandoned_note', array($this, 'handle_update_abandoned_note'));


        add_action('admin_post_export_abandoned_checkouts', array($this, 'handle_export_incomplete_orders'));
    }

    function enqueue_scripts($hook) {
        // Get current admin page
        $current_screen = get_current_screen();

        // Check if we're on the specific plugin pages
        if (isset($_GET['page']) && in_array($_GET['page'], ['orderflow', 'orderflow-incomplete-orders'])) {

            // Tailwind CSS load
            wp_enqueue_style(
                'tailwindcss',
                ADS_PLUGIN_URL . 'assets/css/tailwind.min.css',
                array(),
                '2.2.19'
            );

            // Your custom CSS
            wp_enqueue_style(
                'ic-custom-css',
                ADS_PLUGIN_URL . 'assets/css/incomplete.css',
                array('tailwindcss'),
                time()
            );


            // Your custom JS
            wp_enqueue_script(
                'incomplete-function',
                ADS_PLUGIN_URL . 'assets/js/incomplete.js',
                array('jquery'),
                time(),
                true
            );

            // Localize script
            wp_localize_script('incomplete-function', 'ic_ajax_object', array(
                'ajax_url'               => admin_url('admin-ajax.php'),
                'delete_nonce'           => wp_create_nonce('ic_delete_nonce'),
                'status_nonce'           => wp_create_nonce('ic_status_nonce'),
                'note_nonce'             => wp_create_nonce('ic_note_nonce'),
                'bulk_action_nonce'      => wp_create_nonce('ic_bulk_action_nonce'),
                'settings_save_nonce'    => wp_create_nonce('ic_settings_save_nonce'),
                'schedule_cleanup_nonce' => wp_create_nonce('ic_schedule_cleanup_nonce'),
                'run_cleanup_nonce'      => wp_create_nonce('ic_run_cleanup_nonce'),
                'reset_analytics_nonce'  => wp_create_nonce('ic_reset_analytics_nonce'),
                'fetch_analytics_nonce'  => wp_create_nonce('ic_fetch_analytics_nonce'),
            ));
        }
    }


    function render_settings()
    {
        $current_search_term = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
        $current_paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $current_date_filter = isset($_GET['date_filter']) ? sanitize_text_field($_GET['date_filter']) : '';
        $current_items_per_page = isset($_GET['items_per_page']) ? intval($_GET['items_per_page']) : 10;
        // Get globalwpdb object
        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';
        // Build the base query
        $query = "SELECT * FROM $table_name WHERE status_to = 'ads-incomplete'";
        $count_query = "SELECT COUNT(*) FROM $table_name WHERE status_to = 'ads-incomplete'";
        // Add search conditions
        if (!empty($current_search_term)) {
            $search_term = '%' . $wpdb->esc_like($current_search_term) . '%';
            $query .= $wpdb->prepare(" AND (billing_first_name LIKE %s OR billing_last_name LIKE %s OR billing_phone LIKE %s OR email LIKE %s)",
                $search_term, $search_term, $search_term, $search_term);
            $count_query .= $wpdb->prepare(" AND (billing_first_name LIKE %s OR billing_last_name LIKE %s OR billing_phone LIKE %s OR email LIKE %s)",
                $search_term, $search_term, $search_term, $search_term);
        }
        // Add date filter
        if (!empty($current_date_filter)) {
            $query .= $wpdb->prepare(" AND DATE(created_at) = %s", $current_date_filter);
            $count_query .= $wpdb->prepare(" AND DATE(created_at) = %s", $current_date_filter);
        }
        // Add ordering and pagination
        $query .= " ORDER BY created_at DESC";
        $query .= $wpdb->prepare(" LIMIT %d OFFSET %d", $current_items_per_page, ($current_paged - 1) * $current_items_per_page);
        // Get total items for pagination
        $total_items = $wpdb->get_var($count_query);
        $total_pages = ceil($total_items / $current_items_per_page);
        // Execute the main query
        $results = $wpdb->get_results($query);
        // Get states for Bangladesh
        $country_code = 'BD';
        $states_arr = (function_exists('WC') && WC()->countries) ? WC()->countries->get_states($country_code) : [];
        ?>
        <div class="order-flow-main-box">

            <div class="wrap bg-gray-100 text-gray-800" id="ic-main-dashboard-wrapper">
                <?php // The default WordPress H1 page title has been removed. ?>
                <main class="md:p-2 lg:p-4">
                    <header class="mb-6 bg-white p-4 border-b border-gray-200 shadow-sm rounded-lg">
                        <div class="flex flex-wrap justify-between items-center gap-4">
                            <h2 class="text-xl sm:text-2xl font-bold text-slate-800 flex items-center">
                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                                     stroke="currentColor" class="w-6 h-6 sm:w-7 sm:h-7 mr-2 text-[#1a7278]">
                                    <path stroke-linecap="round" stroke-linejoin="round"
                                          d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 0 0-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 0 0-16.536-1.84M7.5 14.25 5.106 5.272M6 20.25a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Zm12.75 0a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z"/>
                                </svg>
                                <?php esc_html_e('Incomplete Order', 'incomplete-orders'); ?>
                            </h2>
                            <div class="text-sm text-slate-500">
                                <?php printf(
                                    esc_html__('Developed by %s', 'incomplete-orders'),
                                    '<a href="https://xionweb.com" target="_blank" rel="noopener noreferrer" class="text-[#1a7278] hover:underline font-semibold">Xionweb</a>'
                                ); ?>
                            </div>
                        </div>
                    </header>
                    <div class="mb-8">
                        <p class="text-slate-700 text-lg font-medium mb-4"
                           id="current-view-subtitle"><?php esc_html_e('Incomplete Orders List', 'incomplete-orders'); ?></p>
                        <div class="border-b border-gray-200">
                            <nav class="-mb-px flex space-x-4" aria-label="Tabs">
                                <a href="#incomplete-orders" id="tab-incomplete-orders" class="tab-button active"
                                   aria-current="page"
                                   onclick="showTabContent('incomplete-orders-content', this, '<?php echo esc_js(__('Incomplete Orders List', 'incomplete-orders')); ?>'); return false;">
                                    <?php esc_html_e('Incomplete Orders', 'incomplete-orders'); ?>
                                </a>
                                <a href="#analytics" id="tab-analytics" class="tab-button"
                                   onclick="showTabContent('analytics-content', this, '<?php echo esc_js(__('Analytics Overview', 'incomplete-orders')); ?>'); return false;">
                                    <?php esc_html_e('Analytics', 'incomplete-orders'); ?>
                                </a>
                                <a href="#settings" id="tab-settings" class="tab-button"
                                   onclick="showTabContent('settings-content', this, '<?php echo esc_js(__('Plugin Settings', 'incomplete-orders')); ?>'); return false;">
                                    <?php esc_html_e('Settings', 'incomplete-orders'); ?>
                                </a>
                            </nav>
                        </div>
                    </div>
                    <div id="tab-content-area">
                        <div id="incomplete-orders-content" class="tab-pane active-pane">
                            <form method="get" id="ic-filters-form" class="mb-6 p-4 bg-white rounded-lg shadow" action="">
                                <input type="hidden" name="page" value="orderflow-incomplete-orders">
                                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
                                    <div>
                                        <label for="search-checkout"
                                               class="block text-sm font-medium text-gray-700"><?php esc_html_e('Search:', 'incomplete-orders'); ?></label>
                                        <input type="text" id="search-checkout" name="s"
                                               placeholder="<?php esc_attr_e('Search by name, phone or email', 'incomplete-orders'); ?>"
                                               class="filter-input w-full text-sm"
                                               value="<?php echo esc_attr($current_search_term); ?>">
                                    </div>
                                    <div>
                                        <label for="filter-date"
                                               class="block text-sm font-medium text-gray-700"><?php esc_html_e('Filter by Date:', 'incomplete-orders'); ?></label>
                                        <input type="date" id="filter-date" name="date_filter"
                                               class="filter-input w-full text-sm"
                                               value="<?php echo esc_attr($current_date_filter); ?>">
                                    </div>
                                    <div>
                                        <label for="items-per-page"
                                               class="block text-sm font-medium text-gray-700"><?php esc_html_e('Items Per Page:', 'incomplete-orders'); ?></label>
                                        <select id="items-per-page" name="items_per_page"
                                                class="filter-input w-full text-sm">
                                            <?php
                                            $ipp_options = [10, 25, 50, 100];
                                            foreach ($ipp_options as $option) {
                                                echo '<option value="' . esc_attr($option) . '" ' . selected($current_items_per_page, $option, false) . '>' . esc_html($option) . '</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>
                                    <button type="submit"
                                            class="btn-primary py-2 text-sm w-full lg:w-auto"><?php esc_html_e('Filter', 'incomplete-orders'); ?></button>
                                </div>
                            </form>
                            <div class="mb-6 p-4 bg-white rounded-lg shadow">
                                <div class="flex flex-wrap justify-between items-center gap-4">
                                    <div class="flex items-center gap-2">
                                        <label for="bulk-actions-top"
                                               class="sr-only"><?php esc_html_e('Bulk Actions', 'incomplete-orders'); ?></label>
                                        <select id="bulk-actions-top" name="action_bulk_top"
                                                class="filter-input text-sm w-auto">
                                            <option value="-1"><?php esc_html_e('Bulk Actions', 'incomplete-orders'); ?></option>
                                            <option value="delete"><?php esc_html_e('Delete Selected', 'incomplete-orders'); ?></option>
                                            <option value="mark-recovered"><?php esc_html_e('Create Order', 'incomplete-orders'); ?></option>
                                        </select>
                                        <button type="button" id="doaction-top"
                                                class="btn-secondary py-2 text-sm"><?php esc_html_e('Apply', 'incomplete-orders'); ?></button>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <div class="relative">
                                            <button type="button" id="toggleColumnsBtn"
                                                    class="btn-secondary py-2 text-sm"><?php esc_html_e('Columns', 'incomplete-orders'); ?></button>
                                            <div id="columnsDropdown" class="column-toggle-dropdown hidden">
                                                <label><input type="checkbox" class="column-select-all"
                                                              checked> <?php esc_html_e('Select All', 'incomplete-orders'); ?>
                                                </label>
                                                <hr class="my-1 border-gray-200">
                                            </div>
                                        </div>
                                        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"
                                              style="display:inline;">
                                            <input type="hidden" name="action" value="export_abandoned_checkouts">
                                            <?php wp_nonce_field('export_abandoned_checkouts_action', 'export_abandoned_checkouts_nonce'); ?>
                                            <button type="submit"
                                                    class="btn-primary py-2 text-sm ml-2"><?php esc_html_e('Export All as CSV', 'incomplete-orders'); ?></button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <div class="table-card overflow-x-auto">
                                <table class="w-full checkout-table" id="incompleteOrdersTable">
                                    <thead>
                                    <tr>
                                        <th class="w-10" data-column-key="checkbox"><input type="checkbox"
                                                                                           class="rounded border-gray-300 text-[#1a7278] focus:ring-[#1a7278] table-select-all-rows">
                                        </th>
                                        <th data-column-key="date"><?php esc_html_e('Date', 'incomplete-orders'); ?></th>
                                        <th data-column-key="name"><?php esc_html_e('Name', 'incomplete-orders'); ?></th>
                                        <th data-column-key="phone"><?php esc_html_e('Phone', 'incomplete-orders'); ?></th>
                                        <th data-column-key="address"><?php esc_html_e('Address', 'incomplete-orders'); ?></th>
                                        <th data-column-key="state"><?php esc_html_e('State', 'incomplete-orders'); ?></th>
                                        <th class="text-right"
                                            data-column-key="subtotal"><?php esc_html_e('Subtotal', 'incomplete-orders'); ?></th>
                                        <th data-column-key="products"><?php esc_html_e('Products', 'incomplete-orders'); ?></th>
                                        <th data-column-key="status"><?php esc_html_e('Status', 'incomplete-orders'); ?></th>
                                        <th class="w-64" data-column-key="note"><?php esc_html_e('Note', 'incomplete-orders'); ?></th>
                                        <th class="w-32" data-column-key="actions"><?php esc_html_e('Actions', 'incomplete-orders'); ?></th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    if (empty($results)) {
                                        echo '<tr><td colspan="9" class="text-center py-4">' . esc_html__('No incomplete orders found matching your criteria.', 'incomplete-orders') . '</td></tr>';
                                    } else {
                                        foreach ($results as $row) {
                                            $id = $row->id;
                                            $first = $row->billing_first_name;
                                            $last = $row->billing_last_name;
                                            $name_str = trim("$first $last");
                                            $name_display = !empty($name_str) ? esc_html($name_str) : '<em>' . esc_html__('No Name Provided', 'incomplete-orders') . '</em>';
                                            $phone_val = $row->billing_phone;
                                            $addr_val = $row->billing_address_1;
                                            $state_code = $row->billing_state;
                                            $state_display = isset($states_arr[$state_code]) ? esc_html($states_arr[$state_code]) : esc_html($state_code ?: __('Unknown', 'incomplete-orders'));
                                            $subtotal_raw = floatval($row->order_total);
                                            $subtotal_display = function_exists('wc_price') ? wc_price($subtotal_raw) : esc_html(number_format($subtotal_raw, 2));
                                            // Format date - WordPress timezone অনুযায়ী
                                            $date_val_display = __('N/A', 'incomplete-orders');
                                            $time_val_display = '';
                                            if (!empty($row->created_at)) {
                                                // mysql2date() WordPress এর built-in function যা MySQL date string কে
                                                // site timezone অনুযায়ী format করে (WordPress General Settings → Timezone)
                                                // current_time('mysql') site timezone এ date return করে, তাই mysql2date() perfect fit
                                                $date_val_display = mysql2date(get_option('date_format', 'M j, Y'), $row->created_at);
                                                $time_val_display = mysql2date(get_option('time_format', 'H:i:s'), $row->created_at);
                                                
                                                // Fallback: যদি mysql2date() false return করে
                                                if ($date_val_display === false || $time_val_display === false) {
                                                    $date_val_display = __('N/A', 'incomplete-orders');
                                                    $time_val_display = '';
                                                }
                                            }
                                            $note_val = $row->note;
                                            $status_html_display = '<span class="status-badge status-pending">' . esc_html__('Pending', 'incomplete-orders') . '</span>';

                                            // প্রোডাক্ট তালিকা HTML তৈরি করা
                                            $products_list_html = "";
                                            $all_products_data = array(); // সব প্রোডাক্টের ডেটা JSON এর জন্য
                                            $order_id = absint($row->order_id ); // অর্ডার ID নিশ্চিত করুন

                                            // WooCommerce অর্ডার অবজেক্ট লোড করুন
                                            if (function_exists('wc_get_order')) {
                                                $order = wc_get_order($order_id);

                                                if ($order) {
                                                    $items = $order->get_items();
                                                    $product_count = 0;
                                                    $max_display = 2; // সর্বোচ্চ কতগুলো প্রোডাক্ট দেখাবেন

                                                    foreach ($items as $item_id => $item) {
                                                        $product = $item->get_product();

                                                        if (!$product) {
                                                            continue;
                                                        }

                                                        $product_name = $product->get_name();
                                                        $quantity = $item->get_quantity();
                                                        $total = $item->get_total();

                                                        // সব প্রোডাক্টের ডেটা সংরক্ষণ করুন
                                                        $all_products_data[] = array(
                                                            'name' => $product_name,
                                                            'quantity' => $quantity,
                                                            'total' => $total,
                                                            'formatted_total' => function_exists('wc_price') ? wc_price($total) : number_format($total, 2)
                                                        );

                                                        // প্রোডাক্টের নাম ছোট করে দেখানো (যদি খুব লম্বা হয়)
                                                        $display_name = $product_name;
                                                        if (strlen($display_name) > 20) {
                                                            $display_name = substr($display_name, 0, 20) . '...';
                                                        }

                                                        // প্রথম কয়েকটি প্রোডাক্ট দেখানো
                                                        if ($product_count < $max_display) {
                                                            $products_list_html .= sprintf(
                                                                '<div class="product-item">%s (Qty: %d) </div>',
                                                                esc_html($display_name),
                                                                $quantity
                                                            );
                                                        }

                                                        $product_count++;
                                                    }

                                                    // যদি আরও প্রোডাক্ট থাকে তাহলে "আরও X টি" দেখানো এবং "View All" বাটন যোগ করুন
                                                    if ($product_count > $max_display) {
                                                        $remaining = $product_count - $max_display;
                                                        $products_list_html .= sprintf(
                                                            '<div class="more-items">%s +%d %s</div>',
                                                            esc_html__('...', 'incomplete-orders'),
                                                            $remaining,
                                                            esc_html__('more', 'incomplete-orders')
                                                        );
                                                    }

                                                    // সব প্রোডাক্ট দেখানোর জন্য বাটন যোগ করুন
                                                    if ($product_count > 0) {
                                                        $products_list_html .= sprintf(
                                                            '<button type="button" class="view-all-products-btn text-xs text-[#1a7278] hover:text-[#13585c] underline mt-1 cursor-pointer" data-order-id="%d" data-products=\'%s\'>%s</button>',
                                                            $order_id,
                                                            esc_attr(wp_json_encode($all_products_data)),
                                                            esc_html__('View All Products', 'incomplete-orders')
                                                        );
                                                    }
                                                } else {
                                                    $products_list_html = esc_html__('No products found', 'incomplete-orders');
                                                }
                                            } else {
                                                $products_list_html = esc_html__('WooCommerce not available', 'incomplete-orders');
                                            }
                                            ?>
                                            <tr id="checkout-row-<?php echo esc_attr($id); ?>">
                                                <td data-column-key="checkbox"><input type="checkbox"
                                                                                      class="rounded border-gray-300 text-[#1a7278] focus:ring-[#1a7278] row-checkbox"
                                                                                      value="<?php echo esc_attr($id); ?>">
                                                </td>
                                                <td class="text-xs text-gray-500"
                                                    data-column-key="date"><?php echo esc_html($date_val_display); ?>
                                                    <br><?php echo esc_html($time_val_display); ?></td>
                                                <td class="relative-cell group" data-column-key="name">
                                                    <span class="data-text"><?php echo $name_display; ?></span>
                                                    <!--
                                                <button type="button" class="btn-action copy-button"
                                                        data-copytext="<?php echo esc_attr(strip_tags($name_str)); ?>">
                                                    Copy
                                                </button> -->
                                                </td>
                                                <td class="relative-cell group" data-column-key="phone">
                                                    <span class="data-text"><?php echo esc_html($phone_val); ?></span>
                                                    <div class="absolute bottom-[-22px] left-1/2 transform -translate-x-1/2 whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity duration-200 z-10">
                                                        <!--<button type="button"
                                                            class="btn-action !visible !opacity-100 !relative !bottom-auto !left-auto !transform-none copy-button mr-1"
                                                            data-copytext="<?php echo esc_attr($phone_val); ?>">Copy
                                                    </button> -->
                                                        <!--<a href="tel:<?php echo esc_attr($phone_val); ?>"
                                                       class="btn-action !visible !opacity-100 !relative !bottom-auto !left-auto !transform-none bg-green-500 hover:bg-green-600 text-white">Call</a>-->
                                                    </div>
                                                </td>
                                                <td class="relative-cell group" data-column-key="address">
                                                    <span class="data-text"><?php echo esc_html($addr_val); ?></span>
                                                    <!--
                                                <button type="button" class="btn-action copy-button"
                                                        data-copytext="<?php echo esc_attr($addr_val); ?>">Copy
                                                </button> -->
                                                </td>
                                                <td class="relative-cell group" data-column-key="state">
                                                    <span class="data-text"><?php echo $state_display; ?></span>
                                                    <!--
                                                <button type="button" class="btn-action copy-button"
                                                        data-copytext="<?php echo esc_attr($state_display); ?>">Copy
                                                </button> -->
                                                </td>
                                                <td class="text-right font-medium"
                                                    data-column-key="subtotal"><?php echo $subtotal_display; ?></td>
                                                <td class="text-right font-medium"
                                                    data-column-key="products"><?php echo $products_list_html; ?></td>
                                                <td data-column-key="status"
                                                    id="status-cell-<?php echo esc_attr($id); ?>"><?php echo $status_html_display; ?></td>
                                                <td class="w-64" data-column-key="note">
            <textarea rows="1" id="note-<?php echo esc_attr($id); ?>"
                      class="filter-input w-full text-xs p-1"
                      placeholder="<?php esc_attr_e('Add note...', 'incomplete-orders'); ?>"><?php echo esc_textarea($note_val); ?></textarea>
                                                </td>
                                                <td class="action-buttons-cell whitespace-nowrap" data-column-key="actions">
                                                    <button type="button"
                                                            class="btn-secondary btn-action !visible !opacity-100 !relative !bottom-auto !left-auto !transform-none py-1 px-2 text-xs ic-toggle-status"
                                                            data-id="<?php echo esc_attr($id); ?>"><?php esc_html_e('Create Order', 'incomplete-orders'); ?></button>
                                                    <button type="button"
                                                            class="btn-primary btn-action !visible !opacity-100 !relative !bottom-auto !left-auto !transform-none py-1 px-2 text-xs ic-save-note"
                                                            data-id="<?php echo esc_attr($id); ?>"><?php esc_html_e('Update', 'incomplete-orders'); ?></button>
                                                    <button type="button"
                                                            class="btn-danger btn-action !visible !opacity-100 !relative !bottom-auto !left-auto !transform-none py-1 px-2 text-xs ic-delete-lead"
                                                            data-id="<?php echo esc_attr($id); ?>"><?php esc_html_e('Delete', 'incomplete-orders'); ?></button>
                                                </td>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    ?>
                                    </tbody>
                                </table>
                            </div>
                            <div class="mt-4 text-sm text-gray-600" id="ic-pagination-summary">
                                <?php
                                if ($total_items > 0) {
                                    $start_item = ($current_paged - 1) * $current_items_per_page + 1;
                                    $end_item = min($current_paged * $current_items_per_page, $total_items);
                                    printf(
                                        wp_kses_post( /* translators: 1: Start item number, 2: End item number, 3: Total items. */ __('Showing %1$s to %2$s of %3$s incomplete orders', 'incomplete-orders')),
                                        '<strong>' . esc_html($start_item) . '</strong>',
                                        '<strong>' . esc_html($end_item) . '</strong>',
                                        '<strong>' . esc_html($total_items) . '</strong>'
                                    );
                                }
                                ?>
                            </div>
                            <div class="mt-4 flex items-center justify-center" id="ic-pagination-links">
                                <?php
                                if ($total_pages > 1) {
                                    $pagination_links = paginate_links([
                                        'base' => add_query_arg('paged', '%#%', ads_get_current_admin_url()),
                                        'format' => '',
                                        'current' => $current_paged,
                                        'total' => $total_pages,
                                        'prev_text' => __('&laquo; Previous', 'incomplete-orders'),
                                        'next_text' => __('Next &raquo;', 'incomplete-orders'),
                                        'type' => 'array',
                                        'add_args' => true,
                                        'show_all' => false,
                                        'mid_size' => 2,
                                        'end_size' => 1,
                                    ]);
                                    if ($pagination_links) {
                                        echo '<div class="flex items-center space-x-2">';
                                        foreach ($pagination_links as $link) {
                                            if (strpos($link, 'current') !== false) {
                                                // Current page number
                                                $clean_link = strip_tags($link);
                                                echo '<span class="px-3 py-2 text-sm font-medium text-white bg-[#1a7278] rounded-md">' . esc_html($clean_link) . '</span>';
                                            } elseif (strpos($link, 'prev') !== false || strpos($link, 'next') !== false) {
                                                // Previous/Next buttons
                                                $clean_link = preg_replace('/<a[^>]*>/', '<a class="px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 hover:text-gray-900 transition-colors duration-200">', $link);
                                                echo $clean_link;
                                            } elseif (strpos($link, 'dots') !== false) {
                                                // Ellipsis
                                                echo '<span class="px-3 py-2 text-sm font-medium text-gray-500">...</span>';
                                            } else {
                                                // Regular page numbers
                                                $clean_link = preg_replace('/<a[^>]*>/', '<a class="px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 hover:text-gray-900 transition-colors duration-200">', $link);
                                                echo $clean_link;
                                            }
                                        }
                                        echo '</div>';
                                    }
                                }
                                ?>
                            </div>
                        </div>
                        <!-- Analytics and Settings tabs remain unchanged -->
                        <div id="analytics-content" class="tab-pane" style="display: none;">
                            <?php
                            require_once __DIR__ . '/deshobard.php';
                            ?>
                        </div>
                        <div id="settings-content" class="tab-pane" style="display: none;">
                            <form id="ic-settings-form" method="POST" action="">
                                <input type="hidden" name="page" value="orderflow-incomplete-orders">

                                <div class="space-y-8">
                                    <div class="settings-card">
                                        <h3 class="text-lg font-semibold text-gray-900 mb-4">General Settings</h3>
                                        <div class="space-y-6">
                                            <div class="settings-field-group">
                                                <label class="settings-label">Enable Order Incomplete</label>
                                                <div class="flex-grow md:flex-grow-0 md:w-1/4">
                                                    <div class="orderflow-field-input">
                                                        <label class="orderflow-toggle-switch">
                                                            <input type="checkbox" name="ads_enable_order_autosave" value="1"  <?php checked( get_option('ads_enable_order_autosave'), 1 ); ?>>
                                                            <span class="orderflow-slider"></span>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="settings-field-group">
                                                <label class="settings-label">Incomplete Session Time Duration (minutes)
                                                    <p class="ads-settings-description">Default: 5 minutes. Min: 1, Max: 1440 (24 hours)</p>
                                                </label>
                                                <div class="flex-grow md:flex-grow-0 md:w-1/4">
                                                    <input type="number" name="ads_order_autosave_session_time" value="<?php echo esc_attr( get_option('ads_order_autosave_session_time', 5) ); ?>" min="1" max="1440">
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="pt-5">
                                        <div class="flex justify-end">
                                            <button type="button" class="btn-secondary mr-3" onclick="location.reload();">
                                                Cancel
                                            </button>
                                            <button type="submit" id="ic-save-settings-btn" name="save_ic_settings" class="btn-primary">
                                                Save Settings
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>

                        </div>
                    </div>
                    <footer class="mt-8 text-center text-sm text-gray-500">
                        <p>&copy; <span
                                    id="currentYear"></span> <?php esc_html_e('Xionweb Incomplete Order Plugin. All rights reserved.', 'incomplete-orders'); ?>
                        </p>
                    </footer>
                </main>
                <div id="copyMessage"><?php esc_html_e('Copied to clipboard!', 'incomplete-orders'); ?></div>
            </div>
        </div>

        <!-- Products Modal/Popup -->
        <div id="products-modal" class="products-modal-overlay" style="display: none;">
            <div class="products-modal-content">
                <div class="products-modal-header">
                    <h3 class="products-modal-title"><?php esc_html_e('All Products', 'incomplete-orders'); ?></h3>
                    <button type="button" class="products-modal-close" aria-label="<?php esc_attr_e('Close', 'incomplete-orders'); ?>">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
                <div class="products-modal-body">
                    <div id="products-modal-list"></div>
                </div>
            </div>
        </div>
        <style>
            .notice.notice-info {
                display: none;
            }
        </style>
        <?php
    }


    function handle_update_incomplete_status()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ic_status_nonce')) {
            wp_send_json_error(array('reason' => 'Security check failed'));
        }

        // Get and validate parameters
        $lead_id = isset($_POST['lead_id']) ? intval($_POST['lead_id']) : 0;

        if ($lead_id <= 0) {
            wp_send_json_error(array('reason' => 'Invalid lead ID'));
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';

        // Get the order_id from the custom table using lead_id
        $order_id = $wpdb->get_var($wpdb->prepare(
            "SELECT order_id FROM $table_name WHERE id = %d",
            $lead_id
        ));


        if (!$order_id) {
            wp_send_json_error(array('reason' => 'Order ID not found for this lead'));
        }

        $order = wc_get_order($order_id);
        if ($order) {
            $order->update_status('ads-recovered', 'Converted from incomplete order.');
        }


        $order = wc_get_order($order_id);
        if ($order) {
            $current_time = new \WC_DateTime('now', new \DateTimeZone(wp_timezone_string()));
            $order->set_date_created($current_time);

            // Save the order
            $order->save();

            wc_delete_shop_order_transients($order_id);
            clean_post_cache($order_id);

        }

        // Return success response
        wp_send_json_success(array(
            'message' => 'Status updated successfully',
            'new_status' => "Purchase"
        ));
    }

    function handle_delete_incomplete_orders()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ic_delete_nonce')) {
            wp_send_json_error(array('reason' => 'Security check failed'));
        }

        // Get and validate lead_id
        $lead_id = isset($_POST['lead_id']) ? intval($_POST['lead_id']) : 0;

        if ($lead_id <= 0) {
            wp_send_json_error(array('reason' => 'Invalid lead ID'));
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';

        // Get the order_id from the custom table
        $order_id = $wpdb->get_var($wpdb->prepare(
            "SELECT order_id FROM $table_name WHERE id = %d",
            $lead_id
        ));

        if (!$order_id) {
            wp_send_json_error(array('reason' => 'Order ID not found for this lead'));
        }

        // Create an instance of the Incomplete_Order class to use its methods
        $incomplete_order = new \orderflow\Incomplete_Order();

        // Use the existing delete_autosave_order_on_checkout method
        // This will handle all the cleanup including deleting from custom table and WooCommerce order
        $incomplete_order->delete_autosave_order_on_checkout($order_id, true );

        // Return success response
        wp_send_json_success(array(
            'message' => 'Record deleted successfully',
            'deleted_id' => $lead_id
        ));
    }

    function handle_bulk_mark_incomplete_orders()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ic_bulk_action_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }

        // Get and validate lead_ids
        $lead_ids = isset($_POST['lead_ids']) ? array_map('intval', $_POST['lead_ids']) : array();

        if (empty($lead_ids)) {
            wp_send_json_error(array('message' => 'No lead IDs provided'));
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';
        $updated_count = 0;
        $errors = array();

        foreach ($lead_ids as $lead_id) {
            // Get the order_id from the custom table
            $order_id = $wpdb->get_var($wpdb->prepare(
                "SELECT order_id FROM $table_name WHERE id = %d",
                $lead_id
            ));

            if (!$order_id) {
                $errors[] = "Order ID not found for lead ID: $lead_id";
                continue;
            }

            // Update WooCommerce order status + created time
            $order = wc_get_order($order_id);
            if ($order) {
                // Update status
                $order->update_status('ads-recovered', 'Converted from incomplete order.');

                // Update created time to now
                $current_time = new \WC_DateTime('now', new \DateTimeZone(wp_timezone_string()));
                $order->set_date_created($current_time);

                // Save the order
                $order->save();

                wc_delete_shop_order_transients($order_id);
                clean_post_cache($order_id);

                $updated_count++;
            } else {
                $errors[] = "WooCommerce order not found for ID: $order_id";
            }
        }

        // Return success response
        wp_send_json_success(array(
            'updated_count' => $updated_count,
            'errors'        => $errors
        ));
    }



    function handle_bulk_delete_incomplete_orders()
    {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ic_bulk_action_nonce')) {
            wp_send_json_error(array('reason' => 'Security check failed'));
        }

        // Get and validate lead_ids
        $lead_ids = isset($_POST['lead_ids']) ? array_map('intval', $_POST['lead_ids']) : array();

        if (empty($lead_ids)) {
            wp_send_json_error(array('reason' => 'No lead IDs provided'));
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';
        $deleted_count = 0;
        $errors = array();

        // Create an instance of the Incomplete_Order class to use its methods
        $incomplete_order = new \orderflow\Incomplete_Order();

        foreach ($lead_ids as $lead_id) {
            // Get the order_id from the custom table
            $order_id = $wpdb->get_var($wpdb->prepare(
                "SELECT order_id FROM $table_name WHERE id = %d",
                $lead_id
            ));

            if (!$order_id) {
                $errors[] = "Order ID not found for lead ID: $lead_id";
                continue;
            }

            // Use the existing delete_autosave_order_on_checkout method
            // This will handle all the cleanup including deleting from custom table and WooCommerce order
            $result = $incomplete_order->delete_autosave_order_on_checkout($order_id, true);

            if ($result) {
                $deleted_count++;
            } else {
                $errors[] = "Failed to delete lead ID: $lead_id";
            }
        }

        // Return success response
        wp_send_json_success(array(
            'message' => sprintf('%d record(s) deleted successfully', $deleted_count),
            'deleted' => $deleted_count,
            'deleted_ids' => $lead_ids,
            'errors' => $errors
        ));
    }

    public function orderflow_handle_settings_form() {
        if (isset($_POST['save_ic_settings'])) {
            // নিরাপত্তা চেক
            if (!current_user_can('manage_options')) {
                wp_die('Unauthorized user');
            }

            // ভ্যালু নেওয়া
            $enabled = isset($_POST['ads_enable_order_autosave']) ? 1 : 0;
            $session_time = isset($_POST['ads_order_autosave_session_time']) ? intval($_POST['ads_order_autosave_session_time']) : 5;

            // Validation
            if ($session_time < 1) {
                $session_time = 1;
            } elseif ($session_time > 1440) {
                $session_time = 1440;
            }

            // অপশন সেভ
            update_option('ads_enable_order_autosave', $enabled);
            update_option('ads_order_autosave_session_time', $session_time);

            // success query param
            wp_redirect(add_query_arg('settings-updated', 'true', $_SERVER['REQUEST_URI']));
            exit;
        }
    }


    public function handle_update_abandoned_note() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ic_note_nonce')) {
            wp_send_json_error(array('reason' => 'Security check failed'));
        }

        // Get and validate parameters
        $lead_id = isset($_POST['lead_id']) ? intval($_POST['lead_id']) : 0;
        $note = isset($_POST['note']) ? sanitize_textarea_field($_POST['note']) : '';

        if ($lead_id <= 0) {
            wp_send_json_error(array('reason' => 'Invalid lead ID'));
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';

        // Update the note in the database
        $result = $wpdb->update(
            $table_name,
            array('note' => $note),
            array('id' => $lead_id),
            array('%s'),
            array('%d')
        );

        if ($result === false) {
            wp_send_json_error(array('reason' => 'Database update failed'));
        }

        // Return success response
        wp_send_json_success(array(
            'message' => 'Note updated successfully',
            'note' => $note
        ) );
    }

    public function handle_export_incomplete_orders() {
        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_die('Unauthorized user');
        }

        // Verify nonce
        if (!isset($_POST['export_abandoned_checkouts_nonce']) ||
            !wp_verify_nonce($_POST['export_abandoned_checkouts_nonce'], 'export_abandoned_checkouts_action')) {
            wp_die('Security check failed');
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_incomplete_orders_tracker';

        // Get all incomplete orders with order_id
        $results = $wpdb->get_results(
            "SELECT * FROM $table_name WHERE status_to = 'ads-incomplete' ORDER BY created_at DESC",
            ARRAY_A
        );

        if (empty($results)) {
            wp_die('No incomplete orders found to export');
        }

        // Prepare CSV headers
        $filename = 'incomplete_orders_' . date('Y-m-d') . '.csv';
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=' . $filename);

        // Open output stream
        $output = fopen('php://output', 'w');

        // Add CSV headers
        fputcsv($output, [
            'ID',
            'Date',
            'First Name',
            'Last Name',
            'Phone',
            'Email',
            'Address',
            'City',
            'State',
            'Postcode',
            'Country',
            'Order Total',
            'Products',
            'Status',
            'Note'
        ]);

        // Add data rows
        foreach ($results as $row) {
            // Get WooCommerce order for additional data
            $order = wc_get_order($row['order_id']);

            // Initialize missing fields with empty values
            $billing_city = '';
            $billing_postcode = '';
            $billing_country = '';
            $products_list = '';

            // Get missing fields from WooCommerce order if it exists
            if ($order) {
                $billing_city = $order->get_billing_city();
                $billing_postcode = $order->get_billing_postcode();
                $billing_country = $order->get_billing_country();

                // Get all products from the order
                $items = $order->get_items();
                $product_names = array();

                foreach ($items as $item_id => $item) {
                    $product = $item->get_product();

                    if (!$product) {
                        continue;
                    }

                    $product_name = $product->get_name();
                    $quantity = $item->get_quantity();
                    
                    // Format: "Product Name (Qty: X)"
                    $product_names[] = sprintf(
                        '%s (Qty: %d)',
                        $product_name,
                        $quantity
                    );
                }

                // Join all products with comma and space
                $products_list = implode(', ', $product_names);
            }

            fputcsv($output, [
                $row['id'],
                $row['created_at'],
                $row['billing_first_name'],
                $row['billing_last_name'],
                $row['billing_phone'],
                $row['email'],
                $row['billing_address_1'],
                $billing_city,
                $row['billing_state'],
                $billing_postcode,
                $billing_country,
                $row['order_total'],
                $products_list,
                $row['status_to'],
                $row['note']
            ]);
        }

        // Close output stream
        fclose($output);

        // Terminate script
        exit;
    }


}