<?php
function tulipwork_orderstock_stock_page() {
    if (!current_user_can('tulipwork_orderstock_access_stock')) {
        wp_die(esc_html__('You do not have permission to access this page.', 'orderstock'));
    }

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

    $multi_store_enabled = tulipwork_orderstock_is_premium() && get_option('orderstock_pro_central_kitchen_enabled', 0);
    $user_id = get_current_user_id();
    $assigned_stores = $multi_store_enabled ? get_user_meta($user_id, '_orderstock_assigned_stores', true) : [];
    $assigned_stores = is_array($assigned_stores) && !empty($assigned_stores) ? $assigned_stores : null;

    $selected_store = $multi_store_enabled && isset($_GET['store_filter']) ? intval($_GET['store_filter']) : 0;
    $filtered_store = $selected_store;
    if ($multi_store_enabled && $assigned_stores && $selected_store && !in_array($selected_store, $assigned_stores)) {
        $filtered_store = 0;
    }

    if (!apply_filters('tulipwork_orderstock_user_can_access_stock_page', true, $filtered_store)) {
        wp_die(esc_html__('You do not have permission to manage stock for this store.', 'orderstock'));
    }

    $stores = $multi_store_enabled && $assigned_stores 
        ? get_posts(['post_type' => 'tulipwork_store', 'posts_per_page' => -1, 'post__in' => $assigned_stores]) 
        : get_posts(['post_type' => 'tulipwork_store', 'posts_per_page' => -1]);

    $suppliers = get_posts(['post_type' => 'tulipwork_supplier', 'posts_per_page' => -1]);
    $selected_supplier = isset($_GET['supplier_filter']) ? sanitize_text_field(wp_unslash($_GET['supplier_filter'])) : '';
    $categories = get_terms(['taxonomy' => 'tulipwork_prod_cat', 'hide_empty' => true]);
    $selected_category = isset($_GET['product_category']) ? intval($_GET['product_category']) : '';
    $transient_key = 'tulipwork_stock_' . get_current_user_id();

    if (!isset($_POST['update_stock'])) delete_transient($transient_key);
    $manual_stock = get_transient($transient_key) ?: [];

    if (isset($_POST['update_stock']) && isset($_POST['stock']) && check_admin_referer('tulipwork_stock_nonce', 'stock_nonce')) {
        $stock_data = wp_unslash($_POST['stock']);
        $success = false;
        $error_message = '';
    
        // Vérifier l'existence de la table si multistore est activé
        if ($multi_store_enabled && $filtered_store) {
            $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
            if (!$table_exists) {
                error_log("OrderStock Pro: Table $table_name does not exist. Stock updates cannot be saved in multistore mode.");
                $error_message = esc_html__('Error: Stock table does not exist. Please contact support to initialize the database.', 'orderstock');
            }
        }
    
        if (!$error_message) {
            foreach ($stock_data as $product_id => $data) {
                $product_id = intval($product_id);
                if (!get_post($product_id) || get_post_type($product_id) !== 'tulipwork_product') {
                    error_log("OrderStock Pro: Invalid product ID $product_id skipped during stock update.");
                    continue;
                }
                $stock = isset($data['stock']) && is_numeric($data['stock']) ? floatval($data['stock']) : 0;
    
                if ($multi_store_enabled && $filtered_store) {
                    // Vérifier que le magasin est valide
                    if (!get_post($filtered_store) || get_post_type($filtered_store) !== 'tulipwork_store') {
                        error_log("OrderStock Pro: Invalid store ID $filtered_store for stock update.");
                        $error_message = esc_html__('Error: Invalid store selected. Stock not updated.', 'orderstock');
                        break;
                    }
    
                    $exists = $wpdb->get_var($wpdb->prepare(
                        "SELECT id FROM $table_name WHERE store_id = %d AND product_id = %d",
                        $filtered_store,
                        $product_id
                    ));
    
                    if ($exists) {
                        $result = $wpdb->update(
                            $table_name,
                            ['stock' => $stock],
                            ['store_id' => $filtered_store, 'product_id' => $product_id],
                            ['%f'],
                            ['%d', '%d']
                        );
                        if ($result === false) {
                            error_log("OrderStock Pro: Failed to update stock for product $product_id, store $filtered_store: " . $wpdb->last_error);
                            $error_message = esc_html__('Error: Failed to update stock for some products. Please try again.', 'orderstock');
                        } else {
                            $success = true;
                        }
                    } else {
                        $result = $wpdb->insert(
                            $table_name,
                            [
                                'store_id' => $filtered_store,
                                'product_id' => $product_id,
                                'stock' => $stock,
                                'daily_sales' => 0
                            ],
                            ['%d', '%d', '%f', '%f']
                        );
                        if ($result === false) {
                            error_log("OrderStock Pro: Failed to insert stock for product $product_id, store $filtered_store: " . $wpdb->last_error);
                            $error_message = esc_html__('Error: Failed to insert stock for some products. Please try again.', 'orderstock');
                        } else {
                            $success = true;
                        }
                    }
                } else {
                    // Mode non-multistore : sauvegarde via post meta
                    if (update_post_meta($product_id, '_stock', $stock)) {
                        $success = true;
                    } else {
                        error_log("OrderStock Pro: Failed to update post meta stock for product $product_id.");
                        $error_message = esc_html__('Error: Failed to update stock for some products. Please try again.', 'orderstock');
                    }
                }
            }
        }
    
        // Afficher le message approprié
        if ($success && !$error_message) {
            echo '<div class="orderstock-notice orderstock-notice--success"><p>' . esc_html__('Stock updated successfully for this page!', 'orderstock') . '</p></div>';
        } elseif ($error_message) {
            echo '<div class="orderstock-notice orderstock-notice--error"><p>' . esc_html($error_message) . '</p></div>';
        }
    }

    wp_enqueue_style('tulipwork_orderstock-admin-css', plugins_url('orderstock/includes/css/orderstock-admin.css'), [], OrderStock::get_version());

    $paged = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $posts_per_page = 60;
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('Stock', 'orderstock'); ?></h1>
        <div class="order-filters">
            <?php if ($multi_store_enabled) : ?>
                <form method="get" action="">
                    <input type="hidden" name="page" value="tulipwork_orderstock">
                    
                        <label for="store_filter"><?php esc_html_e('Filter by Store', 'orderstock'); ?>:</label>
                        <select id="store_filter" name="store_filter" onchange="this.form.submit()">
                            <option value=""><?php esc_html_e('Select a store', 'orderstock'); ?></option>
                            <?php foreach ($stores as $store) : ?>
                                <option value="<?php echo esc_attr($store->ID); ?>" <?php selected($selected_store, $store->ID); ?>><?php echo esc_html($store->post_title); ?></option>
                            <?php endforeach; ?>
                        </select>

                </form>
                <?php if ($selected_store && $selected_store !== $filtered_store) : ?>
                    <p class="orderstock-pro-notice"><?php esc_html_e('You do not have permission to manage stock for the selected store. Please select a store from your assigned stores.', 'orderstock'); ?></p>
                <?php endif; ?>
            <?php endif; ?>
            <?php if ($multi_store_enabled && !$filtered_store) : ?>
                <p class="orderstock-pro-notice"><?php esc_html_e('Please select a store to manage stock.', 'orderstock'); ?></p>
            <?php else : ?>
                <form method="get" action="">
                    <input type="hidden" name="page" value="tulipwork_orderstock">
                    <?php if ($multi_store_enabled) : ?><input type="hidden" name="store_filter" value="<?php echo esc_attr($filtered_store); ?>"><?php endif; ?>
                    <?php if ($selected_category) : ?>
                        <input type="hidden" name="product_category" value="<?php echo esc_attr($selected_category); ?>">
                    <?php endif; ?>
                    <label for="supplier_filter"><?php esc_html_e('Filter by Supplier', 'orderstock'); ?>:</label>
                    <select id="supplier_filter" name="supplier_filter" onchange="this.form.submit()">
                        <option value=""><?php esc_html_e('All Suppliers', 'orderstock'); ?></option>
                        <?php foreach ($suppliers as $supplier) : ?>
                            <option value="<?php echo esc_attr($supplier->ID); ?>" <?php selected($selected_supplier, $supplier->ID); ?>><?php echo esc_html($supplier->post_title); ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>
                <form method="get" action="">
                    <input type="hidden" name="page" value="tulipwork_orderstock">
                    <?php if ($multi_store_enabled) : ?><input type="hidden" name="store_filter" value="<?php echo esc_attr($filtered_store); ?>"><?php endif; ?>
                    <!-- Ajouter le filtre de fournisseur actuel comme champ caché -->
                    <?php if ($selected_supplier) : ?>
                        <input type="hidden" name="supplier_filter" value="<?php echo esc_attr($selected_supplier); ?>">
                    <?php endif; ?>
                    <label for="product_category"><?php esc_html_e('Filter by Category', 'orderstock'); ?>:</label>
                    <select id="product_category" name="product_category" onchange="this.form.submit()">
                        <option value=""><?php esc_html_e('All Categories', 'orderstock'); ?></option>
                        <?php foreach ($categories as $category) : ?>
                            <option value="<?php echo esc_attr($category->term_id); ?>" <?php selected($selected_category, $category->term_id); ?>><?php echo esc_html($category->name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>
            </div> <!-- Fin de .order-filters -->
            <form method="post" action="">
                <?php wp_nonce_field('tulipwork_stock_nonce', 'stock_nonce'); ?>
                <?php if (!tulipwork_orderstock_is_premium()) : ?>
                <table class="wp-list-table widefat fixed striped tulipwork-orderstock-table">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Product', 'orderstock'); ?></th>
                            <th class="stock-page-categories"><?php esc_html_e('Categories', 'orderstock'); ?></th>
                            <th><?php esc_html_e('Current Stock', 'orderstock'); ?></th>
                            <th class="stock-page-supplier"><?php esc_html_e('Main Supplier', 'orderstock'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $products = [];
                        if ($multi_store_enabled && $filtered_store) {
                            $query = $wpdb->prepare(
                                "SELECT p.ID, p.post_title
                                FROM {$wpdb->posts} p
                                INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id
                                WHERE p.post_type = 'tulipwork_product'
                                AND p.post_status = 'publish'
                                AND pm.meta_key = '_assigned_stores'
                                AND pm.meta_value LIKE %s",
                                '%' . $filtered_store . '%'
                            );
                            if ($selected_supplier) {
                                $query .= $wpdb->prepare(
                                    " AND EXISTS (
                                        SELECT 1 FROM {$wpdb->postmeta} pm2
                                        WHERE pm2.post_id = p.ID
                                        AND pm2.meta_key = '_supplier'
                                        AND pm2.meta_value = %d
                                    )",
                                    $selected_supplier
                                );
                            }
                            if ($selected_category) {
                                $query .= $wpdb->prepare(
                                    " AND EXISTS (
                                        SELECT 1 FROM {$wpdb->term_relationships} tr
                                        JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
                                        WHERE tr.object_id = p.ID
                                        AND tt.taxonomy = 'tulipwork_prod_cat'
                                        AND tt.term_id = %d
                                    )",
                                    $selected_category
                                );
                            }
                            $offset = ($paged - 1) * $posts_per_page;
                            $query .= " ORDER BY p.post_title ASC LIMIT $offset, $posts_per_page";
                            $results = $wpdb->get_results($query);
                            foreach ($results as $result) {
                                $products[] = get_post($result->ID);
                            }
                            $total_query = str_replace("SELECT p.ID, p.post_title", "SELECT COUNT(p.ID)", $query);
                            $total_query = preg_replace('/LIMIT \d+, \d+$/', '', $total_query);
                            $total_products = $wpdb->get_var($total_query);
                            $max_num_pages = ceil($total_products / $posts_per_page);
                        } else {
                            $args = [
                                'post_type' => 'tulipwork_product',
                                'posts_per_page' => $posts_per_page,
                                'paged' => $paged,
                                'post_status' => 'publish',
                                'orderby' => 'title',
                                'order' => 'ASC'
                            ];
                        
                            // Initialiser meta_query si nécessaire
                            $meta_query = [];
                            if ($selected_supplier) {
                                $meta_query[] = [
                                    'key' => '_supplier',
                                    'value' => $selected_supplier,
                                    'compare' => '='
                                ];
                            }
                            if ($multi_store_enabled && $assigned_stores) {
                                $meta_query[] = [
                                    'key' => '_assigned_stores',
                                    'value' => $assigned_stores,
                                    'compare' => 'IN'
                                ];
                            }
                            if (!empty($meta_query)) {
                                $args['meta_query'] = $meta_query;
                                if (count($meta_query) > 1) {
                                    $args['meta_query']['relation'] = 'AND';
                                }
                            }
                        
                            // Ajouter tax_query pour la catégorie
                            if ($selected_category) {
                                $args['tax_query'] = [
                                    [
                                        'taxonomy' => 'tulipwork_prod_cat',
                                        'field' => 'term_id',
                                        'terms' => $selected_category
                                    ]
                                ];
                            }
                        
                            // Si les deux filtres sont présents, s'assurer qu'ils sont combinés correctement
                            if ($selected_supplier && $selected_category) {
                                $args['meta_query']['relation'] = 'AND';
                                $args['tax_query']['relation'] = 'AND';
                            }
                        
                            $query = new WP_Query($args);
                            $products = $query->posts;
                            $max_num_pages = $query->max_num_pages;
                        }

                        if (empty($products)) {
                            echo '<tr><td colspan="4">' . esc_html__('No products found for this store, supplier, or category.', 'orderstock') . '</td></tr>';
                        } else {
                            foreach ($products as $product) :
                                if ($multi_store_enabled && $filtered_store) {
                                    $stock = $wpdb->get_var($wpdb->prepare(
                                        "SELECT stock FROM $table_name WHERE store_id = %d AND product_id = %d",
                                        $filtered_store,
                                        $product->ID
                                    ));
                                    $stock = $stock !== null ? floatval($stock) : 0;
                                } else {
                                    $stock = floatval(get_post_meta($product->ID, '_stock', true));
                                }
                                $decimal_precision = intval(get_post_meta($product->ID, '_decimal_precision', true)) ?: 0;
                                $display_stock = number_format($stock, $decimal_precision, '.', '');
                                $supplier = get_post_meta($product->ID, '_supplier', true);
                                $categories = wp_get_post_terms($product->ID, 'tulipwork_prod_cat', ['fields' => 'names']);
                                $category_list = !empty($categories) && !is_wp_error($categories) ? implode(', ', $categories) : esc_html__('Uncategorized', 'orderstock');
                                // Récupérer l'unité de conditionnement
                                $packaging_unit = get_post_meta($product->ID, '_packaging_unit', true) ?: 'N/A';
                                $packaging_units = [
                                    'unit' => esc_html__('Unit', 'orderstock'),
                                    'pack' => esc_html__('Pack', 'orderstock'),
                                    'box' => esc_html__('Box', 'orderstock'),
                                    'kg' => esc_html__('kg', 'orderstock'),
                                    'L' => esc_html__('L', 'orderstock')
                                ];
                                $display_packaging_unit = isset($packaging_units[$packaging_unit]) ? $packaging_units[$packaging_unit] : esc_html($packaging_unit);
                                ?>
                                <tr>
                                    <td><?php echo esc_html($product->post_title); ?></td>
                                    <td class="stock-page-categories"><?php echo esc_html($category_list); ?></td>
                                    <td>
                                        <input type="number" name="stock[<?php echo esc_attr($product->ID); ?>][stock]" value="<?php echo esc_attr($display_stock); ?>" step="any" min="0" />
                                        <br><small><?php echo esc_html($display_packaging_unit); ?></small>
                                    </td>
                                    <?php
                                    $supplier_id = get_post_meta($product->ID, '_supplier', true);
                                    $supplier_post = $supplier_id ? get_post($supplier_id) : null;
                                    $supplier_name = $supplier_post ? $supplier_post->post_title : esc_html__('None', 'orderstock');
                                    ?>
                                    <td class="stock-page-supplier"><?php echo esc_html($supplier_name); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php } ?>
                    </tbody>
                </table>
            <?php else : ?>
                <?php
                // Appeler la logique Pro pour les utilisateurs Pro, en mode monostore ou multistore
                do_action('tulipwork_orderstock_stock_page_before_products', [
                    'filtered_store' => $filtered_store,
                    'selected_supplier' => $selected_supplier,
                    'selected_category' => $selected_category,
                    'paged' => $paged,
                    'posts_per_page' => $posts_per_page,
                    'assigned_stores' => $assigned_stores,
                    'manual_stock' => $manual_stock
                ]);
                ?>
            <?php endif; ?>
                <div class="tablenav">
                    <?php
                    if (isset($max_num_pages) && $max_num_pages > 1) {
                        echo wp_kses_post(paginate_links([
                            'base' => add_query_arg('paged', '%#%'),
                            'format' => '',
                            'prev_text' => '«',
                            'next_text' => '»',
                            'total' => $max_num_pages,
                            'current' => $paged,
                        ]));
                    }
                    ?>
                </div>
                <p>
                    <input type="submit" name="update_stock" class="button button-primary" value="<?php esc_attr_e('Update Stock', 'orderstock'); ?>" /><br>
                    <small><?php esc_html_e('Updates apply to the current page only.', 'orderstock'); ?></small>
                </p>
                <?php do_action('tulipwork_orderstock_stock_page_after_update_button'); ?>
            </form>
        <?php endif; ?>
    </div>
    <?php
}