<?php
if (!defined('ABSPATH')) exit;
class VS_Core {
    private static function upload_error_message($code) {
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE:
                return 'File exceeds upload_max_filesize.';
            case UPLOAD_ERR_FORM_SIZE:
                return 'File exceeds MAX_FILE_SIZE.';
            case UPLOAD_ERR_PARTIAL:
                return 'File was only partially uploaded.';
            case UPLOAD_ERR_NO_FILE:
                return 'No file was uploaded.';
            case UPLOAD_ERR_NO_TMP_DIR:
                return 'Missing a temporary folder.';
            case UPLOAD_ERR_CANT_WRITE:
                return 'Failed to write file to disk.';
            case UPLOAD_ERR_EXTENSION:
                return 'A PHP extension stopped the file upload.';
            default:
                return 'Unknown upload error.';
        }
    }

    private static function normalize_product_type($type) {
        $type = sanitize_text_field((string) $type);
        $allowed = ['simple', 'variable', 'virtual', 'downloadable'];
        return in_array($type, $allowed, true) ? $type : 'simple';
    }

    private static function sanitize_variable_attributes_from_request() {
        $names = isset($_POST['attribute_name']) ? (array) $_POST['attribute_name'] : [];
        $values = isset($_POST['attribute_values']) ? (array) $_POST['attribute_values'] : [];

        $out = [];
        $count = min(count($names), count($values));
        for ($i = 0; $i < $count; $i++) {
            $name = sanitize_text_field(wp_unslash((string) $names[$i]));
            $raw = sanitize_text_field(wp_unslash((string) $values[$i]));
            if ($name === '' || $raw === '') {
                continue;
            }

            $slug = sanitize_title($name);
            if ($slug === '') {
                continue;
            }

            $vals = array_filter(array_map('trim', preg_split('/[|,]+/', $raw)));
            $vals = array_values(array_unique(array_map('sanitize_text_field', $vals)));
            if (empty($vals)) {
                continue;
            }

            $out[] = [
                'name' => $name,
                'slug' => $slug,
                'values' => $vals,
            ];
        }

        return $out;
    }

    private static function build_product_attributes_meta(array $attributes) {
        $meta = [];
        $pos = 0;
        foreach ($attributes as $attr) {
            $slug = $attr['slug'];
            $meta[$slug] = [
                'name' => $attr['name'],
                'value' => implode(' | ', (array) $attr['values']),
                'position' => $pos++,
                'is_visible' => 1,
                'is_variation' => 1,
                'is_taxonomy' => 0,
            ];
        }
        return $meta;
    }

    private static function parse_variations_from_request(array $allowed_attribute_slugs) {
        $titles = isset($_POST['variation_title']) ? (array) $_POST['variation_title'] : [];
        $attrs_json = isset($_POST['variation_attrs']) ? (array) $_POST['variation_attrs'] : [];
        $prices = isset($_POST['variation_price']) ? (array) $_POST['variation_price'] : [];
        $stocks = isset($_POST['variation_stock']) ? (array) $_POST['variation_stock'] : [];
        $skus = isset($_POST['variation_sku']) ? (array) $_POST['variation_sku'] : [];

        $out = [];
        $count = max(count($titles), count($attrs_json), count($prices), count($stocks), count($skus));
        for ($i = 0; $i < $count; $i++) {
            $title = isset($titles[$i]) ? sanitize_text_field(wp_unslash((string) $titles[$i])) : '';
            $price_raw = isset($prices[$i]) ? trim((string) $prices[$i]) : '';
            $stock_raw = isset($stocks[$i]) ? trim((string) $stocks[$i]) : '';
            $sku = isset($skus[$i]) ? sanitize_text_field(wp_unslash((string) $skus[$i])) : '';

            $price = ($price_raw === '') ? '' : (float) $price_raw;
            $stock = ($stock_raw === '') ? '' : (int) $stock_raw;

            $attrs = [];
            if (isset($attrs_json[$i]) && $attrs_json[$i] !== '') {
                // wp_magic_quotes adds slashes to quotes; remove them before json_decode.
                $raw_attrs = wp_unslash((string) $attrs_json[$i]);
                $raw_attrs = html_entity_decode($raw_attrs, ENT_QUOTES, 'UTF-8');
                $decoded = json_decode($raw_attrs, true);
                if (is_array($decoded)) {
                    foreach ($decoded as $k => $v) {
                        $k = sanitize_title((string) $k);
                        if (!in_array($k, $allowed_attribute_slugs, true)) {
                            continue;
                        }
                        $val = sanitize_text_field(wp_unslash((string) $v));
                        if ($val === '') continue;
                        $attrs[$k] = $val;
                    }
                }
            }

            // Fallback: infer attributes from the title like "Size:M / Color:Red".
            if (empty($attrs) && $title !== '' && str_contains($title, ':')) {
                $parts = preg_split('#\\s*/\\s*#', $title);
                foreach ((array) $parts as $part) {
                    $part = trim((string) $part);
                    if ($part === '' || !str_contains($part, ':')) continue;
                    [$n, $v] = array_pad(explode(':', $part, 2), 2, '');
                    $slug = sanitize_title($n);
                    $val = sanitize_text_field($v);
                    if ($slug === '' || $val === '') continue;
                    if (!in_array($slug, $allowed_attribute_slugs, true)) continue;
                    $attrs[$slug] = $val;
                }
            }

            if (empty($attrs)) {
                continue;
            }

            $out[] = [
                'title' => $title,
                'price' => $price,
                'stock' => $stock,
                'sku' => $sku,
                'attrs' => $attrs,
                'index' => $i,
            ];
        }

        return $out;
    }

    private static function delete_all_variations($product_id) {
        $variation_ids = get_posts([
            'post_type' => 'product_variation',
            'post_parent' => (int) $product_id,
            'post_status' => ['publish', 'private', 'draft'],
            'numberposts' => -1,
            'fields' => 'ids',
        ]);

        foreach ($variation_ids as $vid) {
            wp_delete_post((int) $vid, true);
        }
    }

    private static function sum_variation_stock($product_id) {
        $variation_ids = get_posts([
            'post_type' => 'product_variation',
            'post_parent' => (int) $product_id,
            'post_status' => ['publish', 'private', 'draft'],
            'numberposts' => -1,
            'fields' => 'ids',
        ]);

        $sum = 0;
        foreach ($variation_ids as $vid) {
            $s = get_post_meta((int) $vid, '_stock', true);
            if ($s === '' || $s === null) continue;
            $sum += (int) $s;
        }
        return $sum;
    }

    private static function extract_indexed_upload($field, $index) {
        if (empty($_FILES[$field]) || !is_array($_FILES[$field])) {
            return null;
        }
        $f = $_FILES[$field];
        if (!isset($f['name'][$index]) || $f['name'][$index] === '') {
            return null;
        }
        return [
            'name' => $f['name'][$index],
            'type' => $f['type'][$index] ?? '',
            'tmp_name' => $f['tmp_name'][$index] ?? '',
            'error' => $f['error'][$index] ?? UPLOAD_ERR_NO_FILE,
            'size' => $f['size'][$index] ?? 0,
        ];
    }

    private static function create_variable_variations($parent_id, array $variations, array $attribute_slugs) {
        $parent = get_post((int) $parent_id);
        $parent_title = $parent ? $parent->post_title : 'Product';

        $has_var_images = !empty($_FILES['variation_image']['name']) && is_array($_FILES['variation_image']['name']);
        if ($has_var_images) {
            require_once ABSPATH.'wp-admin/includes/file.php';
            require_once ABSPATH.'wp-admin/includes/media.php';
            require_once ABSPATH.'wp-admin/includes/image.php';
        }

        foreach ($variations as $v) {
            $title = $v['title'] !== '' ? $v['title'] : 'Variation';

            $var_id = wp_insert_post([
                'post_title' => $parent_title . ' - ' . $title,
                'post_status' => 'publish',
                'post_type' => 'product_variation',
                'post_parent' => (int) $parent_id,
                'menu_order' => (int) ($v['index'] ?? 0),
            ]);

            if (!$var_id) {
                continue;
            }

            wp_set_object_terms((int) $var_id, 'variation', 'product_type');

            if ($v['price'] === '') {
                delete_post_meta($var_id, '_regular_price');
                delete_post_meta($var_id, '_price');
            } else {
                update_post_meta($var_id, '_regular_price', (float) $v['price']);
                update_post_meta($var_id, '_price', (float) $v['price']);
            }

            if ($v['stock'] === '') {
                update_post_meta($var_id, '_manage_stock', 'no');
                delete_post_meta($var_id, '_stock');
                update_post_meta($var_id, '_stock_status', 'instock');
            } else {
                update_post_meta($var_id, '_manage_stock', 'yes');
                update_post_meta($var_id, '_stock', (int) $v['stock']);
                update_post_meta($var_id, '_stock_status', ((int) $v['stock'] > 0) ? 'instock' : 'outofstock');
            }

            update_post_meta($var_id, '_sku', $v['sku']);

            foreach ($attribute_slugs as $slug) {
                if (!isset($v['attrs'][$slug])) continue;
                update_post_meta($var_id, 'attribute_' . $slug, $v['attrs'][$slug]);
            }

            if ($has_var_images) {
                $file = self::extract_indexed_upload('variation_image', (int) $v['index']);
                if ($file && !empty($file['tmp_name']) && (int) $file['error'] === UPLOAD_ERR_OK) {
                    $_FILES['vs_variation_image_single'] = $file;
                    $attach_id = media_handle_upload('vs_variation_image_single', (int) $parent_id);
                    if (!is_wp_error($attach_id) && $attach_id) {
                        update_post_meta($var_id, '_thumbnail_id', (int) $attach_id);
                    }
                    unset($_FILES['vs_variation_image_single']);
                }
            }
        }

        if (function_exists('wc_delete_product_transients')) {
            wc_delete_product_transients((int) $parent_id);
        }
        if (class_exists('WC_Product_Variable')) {
            WC_Product_Variable::sync((int) $parent_id);
        }
    }



    public static function init() {
        // Remove admin_post handlers for AJAX version
        add_action('wp_ajax_vs_add_product', [__CLASS__, 'add_product_ajax']);
        add_action('wp_ajax_vs_delete_product', [__CLASS__, 'delete_product_ajax']);
        add_action('wp_ajax_vs_delete_multiple', [__CLASS__, 'delete_multiple_products']);
        add_action('wp_ajax_vs_restore_product', [__CLASS__, 'restore_product_ajax']);
        add_action('wp_ajax_vs_restore_multiple', [__CLASS__, 'restore_multiple_products']);
        add_action('wp_ajax_vs_refresh_restore_tab', [__CLASS__, 'refresh_restore_tab_ajax']);
        add_action('wp_ajax_vs_refresh_products_tab', [__CLASS__, 'refresh_products_tab_ajax']);
        add_action('wp_ajax_vs_edit_product', [__CLASS__, 'edit_product_ajax']);
        
        // Orders & Chat
        // Change status from vendor dashboard removed — do not register update handler anymore
        add_action('wp_ajax_vs_update_order_status', [__CLASS__, 'update_order_status_ajax']);
        add_action('wp_ajax_vs_delete_order', [__CLASS__, 'delete_order_ajax']);

        

       

        self::register_custom_statuses();
    }

    public static function register_custom_statuses() {
        register_post_status('pending_vendor', [
            'label'                     => _x('Pending Vendor Approval', 'post status', 'vendor-space'),
            'public'                    => false,
            'exclude_from_search'       => false,
            'show_in_admin_all_list'    => true,
            'show_in_admin_status_list' => true,
            'label_count'               => _n_noop('Pending Vendor Approval <span class="count">(%s)</span>', 'Pending Vendor Approval <span class="count">(%s)</span>', 'vendor-space'),
        ]);
    }
    

    public static function delete_order_ajax() {
        // نتحقق من الأمان الأساسي فقط
        check_ajax_referer('vs_orders_nonce', 'security');
        
        if (!is_user_logged_in()) {
             wp_send_json_error('Login required');
        }

        $order_id = intval($_POST['order_id']);
        $order = wc_get_order($order_id);
        
        if(!$order) wp_send_json_error('Order not found');
        
        // التحقق البسيط: هل هذا المستخدم هو صاحب منتج في هذا الطلب؟
        // Simple verification: Does this user own a product in this order?
        $user_id = get_current_user_id();
        $can_delete = false;

        if(current_user_can('administrator')) {
            $can_delete = true;
        } else {
            foreach($order->get_items() as $item){
                $prod = $item->get_product();
                if($prod && get_post_field('post_author', $prod->get_id()) == $user_id){
                    $can_delete = true; 
                    break;
                }
            }
        }
        
        if(!$can_delete){
            wp_send_json_error('Permission denied: You do not own products in this order.');
        }
        
        // تنفيذ الحذف النهائي
        $order->delete(true); 
        wp_send_json_success();
    }


public static function edit_product_ajax() {
    check_ajax_referer('vs_edit_product', 'vs_edit_product_nonce');

    if(!current_user_can('edit_products') && !current_user_can('administrator')){
        wp_send_json_error('Permission denied.');
    }
    if (!current_user_can('upload_files')) {
        wp_send_json_error('You do not have permission to upload files.');
    }

    $pid = intval($_POST['product_id']);
    $prod = get_post($pid);
    $user_id = get_current_user_id();

    if(!$prod || ($prod->post_author != $user_id && !current_user_can('administrator'))){
        wp_send_json_error('Cannot edit this product.');
    }

    // تحديث البيانات الأساسية
    $product_type = self::normalize_product_type($_POST['product_type'] ?? '');

    $regular_price = 0;
    $sale_price_raw = '';
    $sale_price = '';
    $final_price = 0;

    if ($product_type !== 'variable') {
        $regular_price = isset($_POST['product_price']) ? floatval($_POST['product_price']) : 0;
        $sale_price_raw = isset($_POST['product_sale_price']) ? trim((string) $_POST['product_sale_price']) : '';
        $sale_price = ($sale_price_raw === '') ? '' : floatval($sale_price_raw);
        $final_price = ($sale_price !== '' && $sale_price >= 0) ? $sale_price : $regular_price;
    }

    $status = isset($_POST['product_status']) ? sanitize_text_field($_POST['product_status']) : 'publish';
    $manual_approval = VS_Admin_Settings::get_option('vendors', 'manual_vendor_approval') === 'yes';
    
    if (!current_user_can('administrator') && $status === 'publish' && $manual_approval) {
        $status = 'pending';
    }
    if (!in_array($status, ['publish', 'draft', 'pending'], true)) {
        $status = 'publish';
    }
    
    // Store original status for frontend notification
    $original_status = isset($_POST['product_status']) ? sanitize_text_field($_POST['product_status']) : 'publish';
    $status_was_changed = !current_user_can('administrator') && $original_status === 'publish' && $status === 'pending';


    $short_desc = isset($_POST['product_short_desc']) ? sanitize_textarea_field($_POST['product_short_desc']) : '';
    $product_name = sanitize_text_field($_POST['product_name'] ?? '');
    $product_desc = sanitize_textarea_field($_POST['product_desc'] ?? '');

    wp_update_post([
        'ID' => $pid,
        'post_title' => $product_name,
        'post_content' => $product_desc,
        'post_excerpt' => $short_desc,
        'post_status' => $status,
    ]);

    update_post_meta($pid, '_sku', sanitize_text_field($_POST['product_sku'] ?? ''));
    wp_set_object_terms($pid, $product_type, 'product_type');

    $stock_total = null;
    if ($product_type === 'variable') {
        // Parent price/stock are driven by variations.
        delete_post_meta($pid, '_price');
        delete_post_meta($pid, '_regular_price');
        delete_post_meta($pid, '_sale_price');
        delete_post_meta($pid, '_stock');
        update_post_meta($pid, '_manage_stock', 'no');

        $attributes = self::sanitize_variable_attributes_from_request();
        if (empty($attributes)) {
            wp_send_json_error('Variable product requires attributes.');
        }

        $attr_meta = self::build_product_attributes_meta($attributes);
        update_post_meta($pid, '_product_attributes', $attr_meta);

        $attribute_slugs = array_values(array_map(function ($a) { return $a['slug']; }, $attributes));
        $variations = self::parse_variations_from_request($attribute_slugs);
        if (empty($variations)) {
            $vc_title = isset($_POST['variation_title']) ? count((array) $_POST['variation_title']) : 0;
            $vc_attrs = isset($_POST['variation_attrs']) ? count((array) $_POST['variation_attrs']) : 0;
            wp_send_json_error('Variable product requires variations. Received variation_title=' . $vc_title . ', variation_attrs=' . $vc_attrs . ', attrs=' . implode(',', $attribute_slugs));
        }

        self::delete_all_variations($pid);
        self::create_variable_variations($pid, $variations, $attribute_slugs);
        $stock_total = self::sum_variation_stock($pid);
    } else {
        // If switching away from variable, remove old variations/attributes.
        self::delete_all_variations($pid);
        delete_post_meta($pid, '_product_attributes');

        update_post_meta($pid, '_price', $final_price);
        update_post_meta($pid, '_regular_price', $regular_price);
        if ($sale_price === '') {
            delete_post_meta($pid, '_sale_price');
        } else {
            update_post_meta($pid, '_sale_price', $sale_price);
        }
 // ===== STOCK (WooCommerce Compatible) =====
    $stock = intval($_POST['product_stock'] ?? 0);

    // Get WooCommerce product object
    $product_obj = wc_get_product($new_product_id);

    if ($product_obj) {

        // Enable stock management
        $product_obj->set_manage_stock(true);

        // Set stock quantity
        $product_obj->set_stock_quantity($stock);

        // Prevent ordering when stock is 0
        $product_obj->set_backorders('no');

        // Set stock status
        if ($stock > 0) {
            $product_obj->set_stock_status('instock');
        } else {
            $product_obj->set_stock_status('outofstock');
        }

        // Save product
        $product_obj->save();
    }    }

    $product_cat = isset($_POST['product_cat']) ? intval($_POST['product_cat']) : 0;
    $default_product_cat = absint(get_option('default_product_cat'));
    if ($default_product_cat <= 0) {
        $fallback_uncat = term_exists('uncategorized', 'product_cat');
        if (is_array($fallback_uncat) && !empty($fallback_uncat['term_id'])) {
            $default_product_cat = (int) $fallback_uncat['term_id'];
        } elseif (is_int($fallback_uncat)) {
            $default_product_cat = $fallback_uncat;
        }
    }
    $category_to_assign = $product_cat > 0 ? $product_cat : $default_product_cat;
    if ($category_to_assign > 0) {
        wp_set_object_terms($pid, [$category_to_assign], 'product_cat');
    } else {
        wp_set_object_terms($pid, [], 'product_cat');
    }

    $remove_featured = isset($_POST['remove_featured']) ? intval($_POST['remove_featured']) : 0;
    $remove_gallery_ids_raw = isset($_POST['remove_gallery_ids']) ? sanitize_text_field($_POST['remove_gallery_ids']) : '';
    $remove_gallery_ids = $remove_gallery_ids_raw ? array_filter(array_map('intval', explode(',', $remove_gallery_ids_raw))) : [];

    if ($remove_featured && empty($_FILES['featured_image']['name'])) {
        delete_post_thumbnail($pid);
    }

    $needs_media = !empty($_FILES['featured_image']['name']) || !empty($_FILES['product_images']['name'][0]);
    if ($needs_media) {
        require_once ABSPATH.'wp-admin/includes/file.php';
        require_once ABSPATH.'wp-admin/includes/media.php';
        require_once ABSPATH.'wp-admin/includes/image.php';
    }

    if (!empty($_FILES['featured_image']['name'])) {
        if (!empty($_FILES['featured_image']['error']) && $_FILES['featured_image']['error'] !== UPLOAD_ERR_OK) {
            wp_send_json_error(self::upload_error_message((int) $_FILES['featured_image']['error']));
        }
        $featured_id = media_handle_upload('featured_image', $pid);
        if (is_wp_error($featured_id) || !$featured_id) {
            wp_send_json_error($featured_id->get_error_message());
        }
        set_post_thumbnail($pid, $featured_id);
        if ((int) get_post_thumbnail_id($pid) !== (int) $featured_id) {
            update_post_meta($pid, '_thumbnail_id', (int) $featured_id);
        }
    }

    $current_gallery_meta = get_post_meta($pid, '_product_image_gallery', true);
    $current_gallery_ids = $current_gallery_meta ? array_filter(array_map('intval', explode(',', $current_gallery_meta))) : [];
    if (!empty($remove_gallery_ids)) {
        $current_gallery_ids = array_values(array_diff($current_gallery_ids, $remove_gallery_ids));
    }

    // تحديث الصور إذا تم رفع أي صورة
    if(!empty($_FILES['product_images']['name'][0])){
        $gallery_ids = [];
        foreach($_FILES['product_images']['name'] as $key=>$val){
            if (!empty($_FILES['product_images']['error'][$key]) && $_FILES['product_images']['error'][$key] !== UPLOAD_ERR_OK) {
                wp_send_json_error(self::upload_error_message((int) $_FILES['product_images']['error'][$key]));
            }
            $file = [
                'name'=>$_FILES['product_images']['name'][$key],
                'type'=>$_FILES['product_images']['type'][$key],
                'tmp_name'=>$_FILES['product_images']['tmp_name'][$key],
                'error'=>$_FILES['product_images']['error'][$key],
                'size'=>$_FILES['product_images']['size'][$key]
            ];
            $_FILES['file'] = $file;
            $attach_id = media_handle_upload('file', $pid);
            if (is_wp_error($attach_id) || !$attach_id) {
                wp_send_json_error($attach_id->get_error_message());
            }
            $gallery_ids[] = $attach_id;
        }
        if(!empty($gallery_ids)){
            $current_gallery_ids = array_merge($current_gallery_ids, $gallery_ids);
        }
    }

    if (!empty($current_gallery_ids)) {
        update_post_meta($pid, '_product_image_gallery', implode(',', $current_gallery_ids));
    } else {
        delete_post_meta($pid, '_product_image_gallery');
    }

    $img = get_the_post_thumbnail($pid, [80,80]) ?: 'No Image';
    $featured_id = get_post_thumbnail_id($pid);
    $featured_url = $featured_id ? wp_get_attachment_image_url($featured_id, 'thumbnail') : '';
    $gallery_urls = [];
    foreach ($current_gallery_ids as $gid) {
        $gurl = wp_get_attachment_image_url($gid, 'thumbnail');
        if ($gurl) $gallery_urls[] = $gurl;
    }

    $price_out = get_post_meta($pid, '_price', true);
    $stock_out = ($stock_total !== null) ? $stock_total : get_post_meta($pid, '_stock', true);

    // Build category display name for dynamic row update
    $cat_terms_out = wp_get_post_terms($pid, 'product_cat', ['fields' => 'names']);
    $cats_out = (!is_wp_error($cat_terms_out) && !empty($cat_terms_out)) ? implode(', ', $cat_terms_out) : '—';
    $cat_ids_out = wp_get_post_terms($pid, 'product_cat', ['fields' => 'ids']);
    $cat_id_out = (!is_wp_error($cat_ids_out) && !empty($cat_ids_out)) ? (int) $cat_ids_out[0] : 0;

    $manual_approval = VS_Admin_Settings::get_option('vendors', 'manual_vendor_approval') === 'yes';
    $is_pending_approval = !current_user_can('administrator') && $status === 'pending' && $manual_approval;

    $vendor_user = get_userdata($prod->post_author);
    $vendor_email = $vendor_user ? $vendor_user->user_email : '';
    $vendor_name = $vendor_user ? $vendor_user->display_name : '';

    $is_pending_vendor = $prod->post_status === 'pending_vendor';

    // Force clean buffer aggressively
    while (ob_get_level()) {
        ob_end_clean();
    }

    wp_send_json_success([
        'product_id' => $pid,
        'product_status' => $status,
        'product_type' => $product_type,
        'price' => $price_out,
        'stock' => $stock_out,
        'cats' => $cats_out,
        'cat_id' => $cat_id_out,
        'img_html' => $img,
        'featured_id' => $featured_id,
        'featured_url' => $featured_url,
        'gallery_ids' => $current_gallery_ids,
        'gallery_urls' => $gallery_urls,
        'vendor_email' => $vendor_email,
        'vendor_name' => $vendor_name,
        'pending_approval' => $is_pending_approval || $is_pending_vendor,
        'pending_message' => $is_pending_vendor ? __('⏳ Product assigned to vendor and waiting for their approval.', 'vendor-space') : ($is_pending_approval ? __('⏳ Your product has been updated and submitted for review!\n\nIt will remain hidden from customers until an administrator approves it. Thank you for your patience!', 'vendor-space') : ''),
    ]);
}

public static function delete_multiple_products() {
    check_ajax_referer('vs_delete_product_nonce', 'security');

    if(!current_user_can('delete_products')){
        wp_send_json_error('Permission denied.');
    }

    $ids = isset($_POST['products']) ? array_map('intval', $_POST['products']) : [];
    $mode = isset($_POST['mode']) ? sanitize_text_field($_POST['mode']) : 'permanent';

    if(empty($ids)) wp_send_json_error('No products selected.');

    $user_id = get_current_user_id();
    foreach($ids as $pid){
        $prod = get_post($pid);
        if($prod && ($prod->post_author == $user_id || current_user_can('administrator'))) {
            if ($mode === 'trash') {
                wp_trash_post($pid);
            } else {
                wp_delete_post($pid, true);
            }
        }
    }

    wp_send_json_success();
}

    public static function add_product_ajax() {
        check_ajax_referer('vs_add_product', 'vs_add_product_nonce');

if(!current_user_can('edit_products') && !current_user_can('administrator')){
    wp_send_json_error('Permission denied.');
}
        if (!current_user_can('upload_files')) {
            wp_send_json_error('You do not have permission to upload files.');
        }

        $user_id = get_current_user_id();
        $product_type = self::normalize_product_type($_POST['product_type'] ?? '');

        $regular_price = 0;
        $sale_price_raw = '';
        $sale_price = '';
        $final_price = 0;

        if ($product_type !== 'variable') {
            $regular_price = isset($_POST['product_price']) ? floatval($_POST['product_price']) : 0;
            $sale_price_raw = isset($_POST['product_sale_price']) ? trim((string) $_POST['product_sale_price']) : '';
            $sale_price = ($sale_price_raw === '') ? '' : floatval($sale_price_raw);
            $final_price = ($sale_price !== '' && $sale_price >= 0) ? $sale_price : $regular_price;
        }

        $status = isset($_POST['product_status']) ? sanitize_text_field($_POST['product_status']) : 'publish';
        $manual_approval = VS_Admin_Settings::get_option('vendors', 'manual_vendor_approval') === 'yes';

        if (!in_array($status, ['publish', 'draft', 'pending'], true)) {
            $status = 'publish';
        }

        // If admin assigns a vendor, enforce pending_vendor status so vendor must approve
        $assigned_vendor = isset($_POST['product_vendor']) ? intval($_POST['product_vendor']) : 0;
        if (current_user_can('administrator') && $assigned_vendor > 0) {
            // verify vendor exists and is not banned
            $vuser = get_userdata($assigned_vendor);
            $v_ok = false;
            if ($vuser) {
                $v_status = get_user_meta($assigned_vendor, 'vs_vendor_status', true) ?: 'active';
                $is_vendor_role = in_array('vendor', (array) $vuser->roles, true);
                $can_edit_products = user_can($assigned_vendor, 'edit_products');
                if ($v_status !== 'deleted' && ($is_vendor_role || $can_edit_products)) {
                    $v_ok = true;
                }
            }
            if ($v_ok) {
                $status = 'pending_vendor';
            } else {
                // invalid vendor selection, ignore
                $assigned_vendor = 0;
            }
        } else {
            // Non-admin users: if publish not allowed and manual approval required, force pending
            if (!current_user_can('administrator') && $status === 'publish' && $manual_approval) $status = 'pending';
        }


        $short_desc = isset($_POST['product_short_desc']) ? sanitize_textarea_field($_POST['product_short_desc']) : '';
        $product_name = sanitize_text_field($_POST['product_name'] ?? '');
        $product_desc = sanitize_textarea_field($_POST['product_desc'] ?? '');

        $new_product_id = wp_insert_post([
            'post_title'   => $product_name,
            'post_content' => $product_desc,
            'post_excerpt' => $short_desc,
            'post_type'    => 'product',
            'post_status'  => $status,
            'post_author'  => ($assigned_vendor > 0 ? $assigned_vendor : $user_id),
        ]);

        if(!$new_product_id) wp_send_json_error('Failed to create product.');

        update_post_meta($new_product_id, '_sku', sanitize_text_field($_POST['product_sku'] ?? ''));
        wp_set_object_terms($new_product_id, $product_type, 'product_type');

        $stock_total = null;
        if ($product_type === 'variable') {
            // Parent price/stock are driven by variations.
            delete_post_meta($new_product_id, '_price');
            delete_post_meta($new_product_id, '_regular_price');
            delete_post_meta($new_product_id, '_sale_price');
            delete_post_meta($new_product_id, '_stock');
            update_post_meta($new_product_id, '_manage_stock', 'no');

            $attributes = self::sanitize_variable_attributes_from_request();
            if (empty($attributes)) {
                wp_send_json_error('Variable product requires attributes.');
            }

            $attr_meta = self::build_product_attributes_meta($attributes);
            update_post_meta($new_product_id, '_product_attributes', $attr_meta);

            $attribute_slugs = array_values(array_map(function ($a) { return $a['slug']; }, $attributes));
            $variations = self::parse_variations_from_request($attribute_slugs);
            if (empty($variations)) {
                $vc_title = isset($_POST['variation_title']) ? count((array) $_POST['variation_title']) : 0;
                $vc_attrs = isset($_POST['variation_attrs']) ? count((array) $_POST['variation_attrs']) : 0;
                wp_send_json_error('Variable product requires variations. Received variation_title=' . $vc_title . ', variation_attrs=' . $vc_attrs . ', attrs=' . implode(',', $attribute_slugs));
            }

            self::delete_all_variations($new_product_id);
            self::create_variable_variations($new_product_id, $variations, $attribute_slugs);
            $stock_total = self::sum_variation_stock($new_product_id);
        } else {

    // ===== PRICE =====
    update_post_meta($new_product_id, '_price', $final_price);
    update_post_meta($new_product_id, '_regular_price', $regular_price);

    if ($sale_price === '') {
        delete_post_meta($new_product_id, '_sale_price');
    } else {
        update_post_meta($new_product_id, '_sale_price', $sale_price);
    }

    // ===== STOCK (WooCommerce Compatible) =====
    $stock = intval($_POST['product_stock'] ?? 0);

    // Get WooCommerce product object
    $product_obj = wc_get_product($new_product_id);

    if ($product_obj) {

        // Enable stock management
        $product_obj->set_manage_stock(true);

        // Set stock quantity
        $product_obj->set_stock_quantity($stock);

        // Prevent ordering when stock is 0
        $product_obj->set_backorders('no');

        // Set stock status
        if ($stock > 0) {
            $product_obj->set_stock_status('instock');
        } else {
            $product_obj->set_stock_status('outofstock');
        }

        // Save product
        $product_obj->save();
    }
}

        $product_cat = isset($_POST['product_cat']) ? intval($_POST['product_cat']) : 0;
        $default_product_cat = absint(get_option('default_product_cat'));
        if ($default_product_cat <= 0) {
            $fallback_uncat = term_exists('uncategorized', 'product_cat');
            if (is_array($fallback_uncat) && !empty($fallback_uncat['term_id'])) {
                $default_product_cat = (int) $fallback_uncat['term_id'];
            } elseif (is_int($fallback_uncat)) {
                $default_product_cat = $fallback_uncat;
            }
        }
        $category_to_assign = $product_cat > 0 ? $product_cat : $default_product_cat;
        if ($category_to_assign > 0) {
            wp_set_object_terms($new_product_id, [$category_to_assign], 'product_cat');
        }

        $needs_media = !empty($_FILES['featured_image']['name']) || !empty($_FILES['product_images']['name'][0]);
        if ($needs_media) {
            require_once ABSPATH.'wp-admin/includes/file.php';
            require_once ABSPATH.'wp-admin/includes/media.php';
            require_once ABSPATH.'wp-admin/includes/image.php';
        }

        $has_featured = false;
        if (!empty($_FILES['featured_image']['name'])) {
            if (!empty($_FILES['featured_image']['error']) && $_FILES['featured_image']['error'] !== UPLOAD_ERR_OK) {
                wp_send_json_error(self::upload_error_message((int) $_FILES['featured_image']['error']));
            }
            $featured_id = media_handle_upload('featured_image', $new_product_id);
            if (is_wp_error($featured_id) || !$featured_id) {
                wp_send_json_error($featured_id->get_error_message());
            }
            set_post_thumbnail($new_product_id, $featured_id);
            if ((int) get_post_thumbnail_id($new_product_id) !== (int) $featured_id) {
                update_post_meta($new_product_id, '_thumbnail_id', (int) $featured_id);
            }
            $has_featured = true;
        }

        // Upload images
        if(!empty($_FILES['product_images']['name'][0])){
            $gallery_ids = [];
            foreach($_FILES['product_images']['name'] as $key=>$val){
                if (!empty($_FILES['product_images']['error'][$key]) && $_FILES['product_images']['error'][$key] !== UPLOAD_ERR_OK) {
                    wp_send_json_error(self::upload_error_message((int) $_FILES['product_images']['error'][$key]));
                }
                $file = [
                    'name'=>$_FILES['product_images']['name'][$key],
                    'type'=>$_FILES['product_images']['type'][$key],
                    'tmp_name'=>$_FILES['product_images']['tmp_name'][$key],
                    'error'=>$_FILES['product_images']['error'][$key],
                    'size'=>$_FILES['product_images']['size'][$key]
                ];
                $_FILES['file'] = $file;
                $attach_id = media_handle_upload('file', $new_product_id);
                if (is_wp_error($attach_id) || !$attach_id) {
                    wp_send_json_error($attach_id->get_error_message());
                }
                if(!$has_featured){
                    set_post_thumbnail($new_product_id, $attach_id);
                    if ((int) get_post_thumbnail_id($new_product_id) !== (int) $attach_id) {
                        update_post_meta($new_product_id, '_thumbnail_id', (int) $attach_id);
                    }
                    $has_featured = true;
                } else {
                    $gallery_ids[] = $attach_id;
                }
            }
            if(!empty($gallery_ids)){
                update_post_meta($new_product_id, '_product_image_gallery', implode(',', $gallery_ids));
            }
        }

        $product = get_post($new_product_id);
        $price = get_post_meta($new_product_id, '_price', true);
        $stock = ($stock_total !== null) ? $stock_total : get_post_meta($new_product_id, '_stock', true);
        $regular_price = get_post_meta($new_product_id, '_regular_price', true);
        $sale_price = get_post_meta($new_product_id, '_sale_price', true);
        $sku = get_post_meta($new_product_id, '_sku', true);
        $type_terms = wp_get_post_terms($new_product_id, 'product_type', ['fields' => 'slugs']);
        $product_type = !empty($type_terms) ? $type_terms[0] : 'simple';
        $cat_terms = wp_get_post_terms($new_product_id, 'product_cat', ['fields' => 'ids']);
        $product_cat = !empty($cat_terms) ? $cat_terms[0] : '';
        $short_desc = $product ? $product->post_excerpt : '';
        $img = get_the_post_thumbnail($new_product_id, [80,80]) ?: 'No Image';
        $featured_id = get_post_thumbnail_id($new_product_id);
        $featured_url = $featured_id ? wp_get_attachment_image_url($featured_id, 'thumbnail') : '';
        $gallery_meta = get_post_meta($new_product_id, '_product_image_gallery', true);
        $gallery_ids = $gallery_meta ? array_filter(array_map('intval', explode(',', $gallery_meta))) : [];
        $gallery_urls = [];
        foreach ($gallery_ids as $gid) {
            $gurl = wp_get_attachment_image_url($gid, 'thumbnail');
            if ($gurl) $gallery_urls[] = $gurl;
        }

        $manual_approval = VS_Admin_Settings::get_option('vendors', 'manual_vendor_approval') === 'yes';
        $is_pending_approval = !current_user_can('administrator') && $product && $product->post_status === 'pending' && $manual_approval;
        $is_pending_vendor = $product && $product->post_status === 'pending_vendor';
        
        $vendor_user = get_userdata($user_id);
        $vendor_email = $vendor_user ? $vendor_user->user_email : '';
        $vendor_name = $vendor_user ? $vendor_user->display_name : '';

        // حساب عدد الطلبات المعلقة الجديد للتاج
        $pending_count = 0;
        if (current_user_can('administrator')) {
            $pending_args = [
                'post_type'   => 'product',
                'post_status' => 'pending',
                'numberposts' => -1,
                'fields'      => 'ids'
            ];
            $pending_posts = get_posts($pending_args);
            $pending_count = count($pending_posts);
        }

        // Force clean buffer aggressively
        while (ob_get_level()) {
            ob_end_clean();
        }

        wp_send_json_success([
            'product_id' => $new_product_id,
            'title' => $product ? $product->post_title : '',
            'desc' => $product ? $product->post_content : '',
            'short_desc' => $short_desc,
            'price' => $price,
            'regular_price' => $regular_price,
            'sale_price' => $sale_price,
            'stock' => $stock,
            'sku' => $sku,
            'product_type' => $product_type,
            'product_status' => $product ? $product->post_status : 'publish',
            'product_cat' => $product_cat,
            'img_html' => $img,
            'featured_id' => $featured_id,
            'featured_url' => $featured_url,
            'gallery_ids' => $gallery_ids,
            'gallery_urls' => $gallery_urls,
            'permalink' => get_permalink($new_product_id),
            'vendor_email' => $vendor_email,
            'vendor_name' => $vendor_name,
            'pending_approval' => $is_pending_approval,
            'manual_approval_enabled' => $manual_approval,
            'pending_message' => $is_pending_approval ? __('⏳ Your product has been submitted for review!\n\nIt will not be visible to customers until an administrator approves it. Please be patient - our team will review it shortly.', 'vendor-space') : '',
            'pending_requests_count' => $pending_count,
        ]);
        
        // Notify assigned vendor by email if an admin assigned this product to them
        if (!empty($assigned_vendor) && $assigned_vendor > 0 && $assigned_vendor !== $user_id) {
            $assigned_user = get_userdata($assigned_vendor);
            if ($assigned_user) {
                $to = $assigned_user->user_email;
                $name = $assigned_user->display_name ?: $assigned_user->user_login;
                $subject = sprintf(__('A new product was assigned to you: %s', 'vendor-space'), $product_name);
                $product_link = get_edit_post_link($new_product_id, '');
                $msg = '';
                $msg .= '<p>' . sprintf(__('Hello %s,', 'vendor-space'), esc_html($name)) . '</p>';
                $msg .= '<p>' . sprintf(__('An administrator has created a new product and assigned it to you: <strong>%s</strong>.', 'vendor-space'), esc_html($product_name)) . '</p>';
                $msg .= '<p>' . __('The product is currently pending and requires your review/approval. You can view or edit it here:', 'vendor-space') . '</p>';
                $msg .= '<p><a href="' . esc_url($product_link) . '">' . esc_html($product_link) . '</a></p>';
                $msg .= '<p>' . __('If you believe this is a mistake, please contact the site administrator.', 'vendor-space') . '</p>';
                $headers = ['Content-Type: text/html; charset=UTF-8'];
                // Suppress errors from wp_mail; it's okay if mail fails silently
                @wp_mail($to, wp_strip_all_tags($subject), $msg, $headers);
            }
        }
        
    }

    public static function delete_product_ajax() {
        check_ajax_referer('vs_delete_product_nonce', 'security');

if(!current_user_can('delete_products')){
    wp_send_json_error('Permission denied.');
}

        $pid = intval($_POST['product_id']);
        $mode = isset($_POST['mode']) ? sanitize_text_field($_POST['mode']) : 'permanent';
        $prod = get_post($pid);
        $user_id = get_current_user_id();

        if($prod && ($prod->post_author == $user_id || current_user_can('administrator'))) {
            if ($mode === 'trash') {
                wp_trash_post($pid);
            } else {
                wp_delete_post($pid, true);
            }
            wp_send_json_success();
        } else {
            wp_send_json_error('Cannot delete product.');
        }
    }

    public static function restore_product_ajax() {
        check_ajax_referer('vs_delete_product_nonce', 'security');
        if(!current_user_can('edit_products')) wp_send_json_error('Permission denied.');

        $pid = intval($_POST['product_id']);
        $prod = get_post($pid);
        $user_id = get_current_user_id();

        if($prod && ($prod->post_author == $user_id || current_user_can('administrator'))) {
            wp_untrash_post($pid);
            wp_send_json_success();
        } else {
            wp_send_json_error('Cannot restore product.');
        }
    }

    public static function restore_multiple_products() {
        check_ajax_referer('vs_delete_product_nonce', 'security');

        if(!current_user_can('edit_products')){
            wp_send_json_error('Permission denied.');
        }

        $ids = isset($_POST['products']) ? array_map('intval', $_POST['products']) : [];
        if(empty($ids)) wp_send_json_error('No products selected.');

        $user_id = get_current_user_id();
        foreach($ids as $pid){
            $prod = get_post($pid);
            if($prod && ($prod->post_author == $user_id || current_user_can('administrator'))) {
                wp_untrash_post($pid);
            }
        }

        wp_send_json_success();
    }

    public static function refresh_restore_tab_ajax() {
        check_ajax_referer('vs_nonce', 'security');
        if (!is_user_logged_in()) wp_send_json_error('Not logged in');
        
        $user = wp_get_current_user();
        if (!class_exists('VS_Restore')) {
            require_once VS_PATH . 'includes/class-vs-restore.php';
        }
        
        $html = VS_Restore::render($user);
        wp_send_json_success($html);
    }

    public static function refresh_products_tab_ajax() {
        check_ajax_referer('vs_nonce', 'security');
        if (!is_user_logged_in()) wp_send_json_error('Not logged in');
        
        if (!class_exists('VS_Dashboard')) {
            require_once VS_PATH . 'includes/class-vs-dashboard.php';
        }
        
        $user = wp_get_current_user();
        if (method_exists('VS_Dashboard', 'render_products_tab_content')) {
             $html = VS_Dashboard::render_products_tab_content($user);
             wp_send_json_success($html);
        } else {
             wp_send_json_error('Products refresh not implemented yet');
        }
    }

    public static function update_order_status_ajax() {
        check_ajax_referer('vs_orders_nonce', 'security');
        
        if(!current_user_can('edit_shop_orders') && !current_user_can('vendor')){
             // Allow if they are vendor (we need to trust them or check order ownership)
        }
        
        $order_id = intval($_POST['order_id']);
        $new_status = sanitize_text_field($_POST['status']);
        $order = wc_get_order($order_id);
        
        if(!$order) wp_send_json_error('Order not found');
        
        // Check if vendor has products in this order
        $user_id = get_current_user_id();
        $is_vendor_order = false;
        foreach($order->get_items() as $item){
            $prod = $item->get_product();
            if($prod && get_post_field('post_author', $prod->get_id()) == $user_id){
                $is_vendor_order = true; 
                break;
            }
        }
        
        if(!$is_vendor_order && !current_user_can('administrator')){
            wp_send_json_error('Permission denied');
        }
        
        try {
            $order->update_status($new_status, 'Updated by Vendor via Dashboard');
        } catch (Exception $e) {
            // Even if it fails internally, if the status actually changed, we might want to say success.
            // But let's log it and proceed.
            error_log('VS Status Update Error: ' . $e->getMessage());
        }
        
        // Force clean buffer aggressively
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        wp_send_json_success();
        wp_die();

    }

    // Chat handlers moved to includes/class-vs-chat.php
}


