<?php
if (!defined('ABSPATH')) exit;

class VS_Categories {

    const TAXONOMY = 'product_cat';

    private static function is_vendor_user($user_id = 0): bool {
        if (!$user_id) {
            $user_id = get_current_user_id();
        }
        if (!$user_id) {
            return false;
        }
        // Treat anyone who can edit products as a vendor (compatible with other vendor plugins).
        if (user_can($user_id, 'edit_products')) {
            return true;
        }
        $u = get_userdata($user_id);
        $roles = ($u && is_array($u->roles)) ? $u->roles : [];
        return in_array('vendor', (array) $roles, true);
    }

    public static function init() {
        add_action('wp_ajax_vs_get_product_category', [__CLASS__, 'ajax_get_category']);
        add_action('wp_ajax_vs_create_product_category', [__CLASS__, 'ajax_create_category']);
        add_action('wp_ajax_vs_request_product_category', [__CLASS__, 'ajax_request_category']);
        add_action('wp_ajax_vs_list_category_requests', [__CLASS__, 'ajax_list_category_requests']);
        add_action('wp_ajax_vs_approve_category_request', [__CLASS__, 'ajax_approve_category_request']);
        add_action('wp_ajax_vs_reject_category_request', [__CLASS__, 'ajax_reject_category_request']);
        add_action('wp_ajax_vs_cancel_category_request', [__CLASS__, 'ajax_cancel_category_request']);
        add_action('wp_ajax_vs_update_product_category', [__CLASS__, 'ajax_update_category']);
        add_action('wp_ajax_vs_delete_product_category', [__CLASS__, 'ajax_delete_category']);
        add_action('wp_ajax_vs_bulk_delete_product_categories', [__CLASS__, 'ajax_bulk_delete_categories']);
        add_action('wp_ajax_vs_get_category_excludes', [__CLASS__, 'ajax_get_category_excludes']);
    }

    public static function get_pending_count(): int {
        $pending_cat = get_posts([
            'post_type' => 'vs_category_request',
            'post_status' => 'pending',
            'numberposts' => -1,
            'fields' => 'ids',
        ]);
        return is_array($pending_cat) ? count($pending_cat) : 0;
    }

    private static function current_user_can_manage_terms(): bool {
        $tax = get_taxonomy(self::TAXONOMY);
        $manage_cap = ($tax && isset($tax->cap) && isset($tax->cap->manage_terms)) ? $tax->cap->manage_terms : 'manage_product_terms';
        return current_user_can('administrator') || current_user_can($manage_cap);
    }

    private static function require_manage_terms_or_die() {
        check_ajax_referer('vs_nonce', 'security');

        if (!is_user_logged_in()) {
            wp_send_json_error(__('Login required.', 'vendor-space'));
        }

        if (!taxonomy_exists(self::TAXONOMY)) {
            wp_send_json_error(__('Taxonomy not available.', 'vendor-space'));
        }

        if (!self::current_user_can_manage_terms()) {
            wp_send_json_error(__('Permission denied.', 'vendor-space'));
        }
    }

    public static function ajax_create_category() {
        self::require_manage_terms_or_die();

        $name = sanitize_text_field((string) ($_POST['name'] ?? ''));
        $slug_raw = (string) ($_POST['slug'] ?? '');
        $slug = $slug_raw !== '' ? sanitize_title($slug_raw) : '';
        $parent = absint($_POST['parent'] ?? 0);
        $description = sanitize_textarea_field((string) ($_POST['description'] ?? ''));

        if ($name === '') {
            wp_send_json_error(__('Category name is required.', 'vendor-space'));
        }

        $args = [
            'parent' => $parent,
            'description' => $description,
        ];
        if ($slug !== '') {
            $args['slug'] = $slug;
        }

        $created = wp_insert_term($name, self::TAXONOMY, $args);
        if (is_wp_error($created)) {
            wp_send_json_error($created->get_error_message());
        }

        $term_id = (int) ($created['term_id'] ?? 0);
        $term = $term_id ? get_term($term_id, self::TAXONOMY) : null;

        $parent_name = '';
        if ($term && !is_wp_error($term) && (int) $term->parent > 0) {
            $pt = get_term((int) $term->parent, self::TAXONOMY);
            if ($pt && !is_wp_error($pt)) {
                $parent_name = (string) $pt->name;
            }
        }

        wp_send_json_success([
            'term_id' => $term_id,
            'name' => $term ? $term->name : $name,
            'slug' => $term ? $term->slug : $slug,
            'parent' => ($term && !is_wp_error($term)) ? (int) $term->parent : $parent,
            'parent_name' => $parent_name,
            'description' => ($term && !is_wp_error($term)) ? (string) $term->description : $description,
            'count' => ($term && !is_wp_error($term)) ? (int) $term->count : 0,
        ]);
    }

    /**
     * Vendors can request a category — this creates a private request post.
     */
    public static function ajax_request_category() {
        // Wrap handler in error conversion so PHP warnings/errors return JSON instead of a 500
        check_ajax_referer('vs_nonce', 'security');

        set_error_handler(function($severity, $message, $file, $line) {
            throw new \ErrorException($message, 0, $severity, $file, $line);
        });

        try {
            if (!is_user_logged_in()) {
                restore_error_handler();
                wp_send_json_error(__('Login required.', 'vendor-space'));
            }

	            $user = wp_get_current_user();
	            if (!self::is_vendor_user((int) $user->ID)) {
	                restore_error_handler();
	                wp_send_json_error(__('Permission denied.', 'vendor-space'));
	            }

            $name = sanitize_text_field((string) ($_POST['name'] ?? ''));
            $slug_raw = (string) ($_POST['slug'] ?? '');
            $slug = $slug_raw !== '' ? sanitize_title($slug_raw) : '';
            $parent = absint($_POST['parent'] ?? 0);
            $description = sanitize_textarea_field((string) ($_POST['description'] ?? ''));

            if ($name === '') {
                restore_error_handler();
                wp_send_json_error(__('Category name is required.', 'vendor-space'));
            }

            // Create request post
            $post_id = wp_insert_post([
                'post_title' => $name,
                'post_content' => $description,
                'post_status' => 'pending',
                'post_type' => 'vs_category_request',
                'post_author' => $user->ID,
            ]);

            if (is_wp_error($post_id) || $post_id <= 0) {
                restore_error_handler();
                wp_send_json_error(__('Could not create request.', 'vendor-space'));
            }

            update_post_meta($post_id, '_vs_cr_slug', $slug);
            update_post_meta($post_id, '_vs_cr_parent', $parent);
            update_post_meta($post_id, '_vs_cr_status', 'pending');

            // Notify admins via email (best-effort)
            try {
                $admins = get_users(['capability' => 'manage_options']);
                $subject = __('New Category Request', 'vendor-space');
                $message = sprintf(__('Vendor %s requested a new category: %s', 'vendor-space'), $user->display_name, $name) . "\n\n";
                $message .= admin_url('admin.php?page=vs-category-requests');
                if (is_array($admins)) {
                    foreach ($admins as $a) {
                        if (!empty($a->user_email)) wp_mail($a->user_email, $subject, $message);
                    }
                }
            } catch (\Throwable $t) {
                error_log('VS: failed to notify admins about category request: ' . $t->getMessage());
            }

            restore_error_handler();
            wp_send_json_success(['message' => __('Request submitted. An administrator will review it.', 'vendor-space')]);
        } catch (\Throwable $e) {
            restore_error_handler();
            error_log('VS ajax_request_category error: ' . $e->getMessage() . " in " . $e->getFile() . ':' . $e->getLine());
            wp_send_json_error(__('An internal error occurred while processing the request.', 'vendor-space'));
        }
    }

    public static function ajax_list_category_requests() {
        check_ajax_referer('vs_nonce', 'security');

        if (!is_user_logged_in()) {
            wp_send_json_error(__('Login required.', 'vendor-space'));
        }

        $user = wp_get_current_user();
        $is_admin = current_user_can('manage_options');

        $args = [
            'post_type' => 'vs_category_request',
            'post_status' => $is_admin ? ['pending'] : ['pending', 'publish', 'draft'],
            'numberposts' => -1,
            'orderby' => 'date',
            'order' => 'DESC'
        ];

        if (!$is_admin) {
            // Non-admins (vendors) only see their own requests
            $args['author'] = $user->ID;
        }

        $posts = get_posts($args);
        $rows = [];
        foreach ($posts as $p) {
            $rows[] = [
                'id' => (int) $p->ID,
                'title' => $p->post_title,
                'content' => wp_trim_words($p->post_content, 30),
                'author_id' => (int) $p->post_author,
                'author_name' => get_the_author_meta('display_name', $p->post_author),
                'status' => get_post_meta($p->ID, '_vs_cr_status', true) ?: $p->post_status,
                'slug' => get_post_meta($p->ID, '_vs_cr_slug', true),
                'parent' => (int) get_post_meta($p->ID, '_vs_cr_parent', true),
                'date' => $p->post_date,
            ];
        }

        wp_send_json_success(['requests' => $rows]);
    }

    public static function ajax_approve_category_request() {
        check_ajax_referer('vs_nonce', 'security');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'vendor-space'));
        }

        $post_id = intval($_POST['request_id'] ?? 0);
        if ($post_id <= 0) wp_send_json_error(__('Invalid request.', 'vendor-space'));

        $request = get_post($post_id);
        if (!$request || $request->post_type !== 'vs_category_request') wp_send_json_error(__('Request not found.', 'vendor-space'));

        $name = $request->post_title;
        $desc = $request->post_content;
        $slug = get_post_meta($post_id, '_vs_cr_slug', true);
        $parent = intval(get_post_meta($post_id, '_vs_cr_parent', true));

        $args = ['description' => $desc];
        if ($slug) $args['slug'] = sanitize_title($slug);
        if ($parent > 0) $args['parent'] = $parent;

        $created = wp_insert_term($name, self::TAXONOMY, $args);
        if (is_wp_error($created)) {
            wp_send_json_error($created->get_error_message());
        }

        update_post_meta($post_id, '_vs_cr_status', 'approved');
        wp_update_post(['ID' => $post_id, 'post_status' => 'publish']);

        $vendor = get_userdata($request->post_author);
        if ($vendor && !empty($vendor->user_email)) {
            wp_mail($vendor->user_email, __('Category Request Approved', 'vendor-space'), sprintf(__('Your category request "%s" was approved.', 'vendor-space'), $name));
        }

        $term = get_term($created['term_id'], self::TAXONOMY);
        if (!$term || is_wp_error($term)) {
            wp_send_json_error(__('Term created but failed to retrieve data.', 'vendor-space'));
        }

        $parent_name = '';
        if ($term->parent > 0) {
            $pt = get_term($term->parent, self::TAXONOMY);
            if ($pt && !is_wp_error($pt)) {
                $parent_name = $pt->name;
            }
        }

        wp_send_json_success([
            'term_id' => (int) $term->term_id,
            'name' => $term->name,
            'slug' => $term->slug,
            'parent' => (int) $term->parent,
            'parent_name' => $parent_name,
            'description' => $term->description,
            'count' => (int) $term->count,
            'pending_count' => self::get_pending_count(),
        ]);
    }

    public static function ajax_reject_category_request() {
        check_ajax_referer('vs_nonce', 'security');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'vendor-space'));
        }

        $post_id = intval($_POST['request_id'] ?? 0);
        if ($post_id <= 0) wp_send_json_error(__('Invalid request.', 'vendor-space'));

        $request = get_post($post_id);
        if (!$request || $request->post_type !== 'vs_category_request') wp_send_json_error(__('Request not found.', 'vendor-space'));

        update_post_meta($post_id, '_vs_cr_status', 'rejected');
        wp_update_post(['ID' => $post_id, 'post_status' => 'draft']);

        $vendor = get_userdata($request->post_author);
        if ($vendor && !empty($vendor->user_email)) {
            wp_mail($vendor->user_email, __('Category Request Rejected', 'vendor-space'), sprintf(__('Your category request "%s" was rejected by an administrator.', 'vendor-space'), $request->post_title));
        }

        wp_send_json_success([ 'pending_count' => self::get_pending_count() ]);
    }

    public static function ajax_cancel_category_request() {
        check_ajax_referer('vs_nonce', 'security');

        if (!is_user_logged_in()) {
            wp_send_json_error(__('Login required.', 'vendor-space'));
        }

        $post_id = intval($_POST['request_id'] ?? 0);
        if ($post_id <= 0) wp_send_json_error(__('Invalid request.', 'vendor-space'));

        $request = get_post($post_id);
        if (!$request || $request->post_type !== 'vs_category_request') {
            wp_send_json_error(__('Request not found.', 'vendor-space'));
        }

        $user_id = get_current_user_id();
        if ($request->post_author != $user_id && !current_user_can('manage_options')) {
            wp_send_json_error(__('Permission denied.', 'vendor-space'));
        }

        $status = get_post_meta($post_id, '_vs_cr_status', true) ?: $request->post_status;
        if ($status !== 'pending') {
            wp_send_json_error(__('Only pending requests can be cancelled.', 'vendor-space'));
        }

        $deleted = wp_delete_post($post_id, true);
        if (!$deleted) {
            wp_send_json_error(__('Could not cancel request.', 'vendor-space'));
        }

        wp_send_json_success([
            'message' => __('Request cancelled.', 'vendor-space'),
            'pending_count' => self::get_pending_count()
        ]);
    }

    public static function ajax_get_category() {
        self::require_manage_terms_or_die();

        $term_id = absint($_POST['term_id'] ?? 0);
        if ($term_id <= 0) {
            wp_send_json_error(__('Invalid category.', 'vendor-space'));
        }

        $term = get_term($term_id, self::TAXONOMY);
        if (!$term || is_wp_error($term)) {
            wp_send_json_error(__('Category not found.', 'vendor-space'));
        }

        wp_send_json_success([
            'term_id' => (int) $term->term_id,
            'name' => (string) $term->name,
            'slug' => (string) $term->slug,
            'parent' => (int) $term->parent,
            'description' => (string) $term->description,
        ]);
    }

    public static function ajax_update_category() {
        self::require_manage_terms_or_die();

        $term_id = absint($_POST['term_id'] ?? 0);
        if ($term_id <= 0) {
            wp_send_json_error(__('Invalid category.', 'vendor-space'));
        }

        $existing = get_term($term_id, self::TAXONOMY);
        if (!$existing || is_wp_error($existing)) {
            wp_send_json_error(__('Category not found.', 'vendor-space'));
        }

        $name = sanitize_text_field((string) ($_POST['name'] ?? ''));
        $slug_raw = (string) ($_POST['slug'] ?? '');
        $slug = $slug_raw !== '' ? sanitize_title($slug_raw) : '';
        $parent = absint($_POST['parent'] ?? 0);
        $description = sanitize_textarea_field((string) ($_POST['description'] ?? ''));

        if ($name === '') {
            wp_send_json_error(__('Category name is required.', 'vendor-space'));
        }

        $args = [
            'name' => $name,
            'parent' => $parent,
            'description' => $description,
        ];
        if ($slug !== '') {
            $args['slug'] = $slug;
        }

        $updated = wp_update_term($term_id, self::TAXONOMY, $args);
        if (is_wp_error($updated)) {
            wp_send_json_error($updated->get_error_message());
        }

        $term = get_term($term_id, self::TAXONOMY);
        $parent_name = '';
        if ($term && !is_wp_error($term) && (int) $term->parent > 0) {
            $pt = get_term((int) $term->parent, self::TAXONOMY);
            if ($pt && !is_wp_error($pt)) {
                $parent_name = (string) $pt->name;
            }
        }
        wp_send_json_success([
            'term_id' => $term_id,
            'name' => $term && !is_wp_error($term) ? $term->name : $name,
            'slug' => $term && !is_wp_error($term) ? $term->slug : $slug,
            'parent' => ($term && !is_wp_error($term)) ? (int) $term->parent : $parent,
            'parent_name' => $parent_name,
            'description' => ($term && !is_wp_error($term)) ? (string) $term->description : $description,
            'count' => ($term && !is_wp_error($term)) ? (int) $term->count : 0,
        ]);
    }

    public static function ajax_delete_category() {
        self::require_manage_terms_or_die();

        $term_id = absint($_POST['term_id'] ?? 0);
        if ($term_id <= 0) {
            wp_send_json_error(__('Invalid category.', 'vendor-space'));
        }

        $existing = get_term($term_id, self::TAXONOMY);
        if (!$existing || is_wp_error($existing)) {
            wp_send_json_error(__('Category not found.', 'vendor-space'));
        }

        $deleted = wp_delete_term($term_id, self::TAXONOMY);
        if (is_wp_error($deleted)) {
            wp_send_json_error($deleted->get_error_message());
        }
        if (!$deleted) {
            wp_send_json_error(__('Could not delete category.', 'vendor-space'));
        }

        wp_send_json_success([
            'term_id' => $term_id,
        ]);
    }

    public static function ajax_bulk_delete_categories() {
        self::require_manage_terms_or_die();

        $term_ids = $_POST['term_ids'] ?? [];
        if (!is_array($term_ids) || empty($term_ids)) {
            wp_send_json_error(__('No categories selected.', 'vendor-space'));
        }

        $deleted_ids = [];
        $errors = [];

        foreach ($term_ids as $tid) {
            $tid = absint($tid);
            if ($tid <= 0) continue;

            $deleted = wp_delete_term($tid, self::TAXONOMY);
            if (is_wp_error($deleted)) {
                $errors[] = sprintf(__('ID %d: %s', 'vendor-space'), $tid, $deleted->get_error_message());
            } elseif ($deleted) {
                $deleted_ids[] = $tid;
            } else {
                $errors[] = sprintf(__('ID %d: Could not delete.', 'vendor-space'), $tid);
            }
        }

        if (empty($deleted_ids) && !empty($errors)) {
            wp_send_json_error(implode("\n", $errors));
        }

        wp_send_json_success([
            'deleted_ids' => $deleted_ids,
            'errors' => $errors,
        ]);
    }

    public static function ajax_get_category_excludes() {
        self::require_manage_terms_or_die();

        $term_id = absint($_POST['term_id'] ?? 0);
        if ($term_id <= 0) {
            wp_send_json_error(__('Invalid category.', 'vendor-space'));
        }

        $existing = get_term($term_id, self::TAXONOMY);
        if (!$existing || is_wp_error($existing)) {
            wp_send_json_error(__('Category not found.', 'vendor-space'));
        }

        $excludes = [$term_id];
        $children = get_term_children($term_id, self::TAXONOMY);
        if (is_array($children)) {
            $excludes = array_merge($excludes, $children);
        }

        wp_send_json_success([
            'excludes' => array_map('intval', $excludes),
        ]);
    }

    public static function render($user) {
        $can_manage = taxonomy_exists(self::TAXONOMY) && self::current_user_can_manage_terms();
        $terms = [];
        $cats_json = [];
        
        if (taxonomy_exists(self::TAXONOMY)) {
            $raw_cats = get_terms([
                'taxonomy'   => self::TAXONOMY,
                'hide_empty' => false,
                'orderby'    => 'name',
                'order'      => 'ASC',
            ]);

            if (!is_wp_error($raw_cats) && is_array($raw_cats)) {
                $terms = $raw_cats;
                $cat_map = [];
                foreach ($raw_cats as $t) { $cat_map[$t->term_id] = $t; }
                foreach ($raw_cats as $t) {
                    $path_parts = [$t->name];
                    $parent_id  = $t->parent;
                    while ($parent_id && isset($cat_map[$parent_id])) {
                        array_unshift($path_parts, $cat_map[$parent_id]->name);
                        $parent_id = $cat_map[$parent_id]->parent;
                    }
                    $cats_json[] = [
                        'id'    => (int) $t->term_id,
                        'name'  => $t->name,
                        'depth' => count($path_parts) - 1,
                        'path'  => implode(' > ', $path_parts),
                        'count' => (int) $t->count
                    ];
                }
            }
        }

        ob_start();
        ?>
        <div class="vs-tab" id="tab-product-categories" style="display:none;">
            <div class="vs-dashboard-header" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; border-bottom: 2px solid #2563eb; padding-bottom: 10px;">
                <h2 style="margin:0; font-size:24px; color:#1e293b;"><?php echo esc_html__('Product Categories', 'vendor-space'); ?></h2>
                <?php if ($can_manage): ?>
                    <div style="display:flex; gap:8px;">
                        <button type="button" id="vs-bulk-delete-categories-btn"
                            style="display:none; background:#991b1b;color:#fff;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;transition:0.2s;">
                            <i class="fas fa-trash-alt"></i> <?php echo esc_html__('Delete Selected', 'vendor-space'); ?>
                        </button>
                        <button type="button" id="vs-add-category-btn"
                            style="background:#2563eb;color:#fff;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;transition:0.2s;">
                            <i class="fas fa-plus"></i> <?php echo esc_html__('Add Category', 'vendor-space'); ?>
                        </button>
                        <button type="button" id="vs-open-requests-btn"
                            style="background:#ef4444;color:#fff;border:none;padding:8px 16px;border-radius:8px;cursor:pointer;font-size:13px;font-weight:600;display:flex;align-items:center;gap:6px;transition:0.2s;">
                            <i class="fas fa-list"></i> <?php echo esc_html__('Requests', 'vendor-space'); ?>
                        </button>
                    </div>
                <?php endif; ?>
            </div>

	            <?php if (!$can_manage): ?>
	                <?php if (is_user_logged_in() && self::is_vendor_user()) : ?>
	                    <input type="hidden" id="vs-categories-security" value="<?php echo esc_attr(wp_create_nonce('vs_nonce')); ?>">
	                    <div class="vs-card" style="padding:18px; border:1px solid #e2e8f0; border-radius:12px; background:#fff;">
	                        <p><?php echo esc_html__('You cannot manage categories directly. You can request a new category and an administrator will review it.', 'vendor-space'); ?></p>
	                        <div style="margin-top:12px;">
	                            <button type="button" id="vs-request-category-btn" class="vs-btn vs-btn--primary" style="background:#2563eb;color:#fff;padding:8px 14px;border-radius:8px;"> <i class="fas fa-plus"></i> <?php echo esc_html__('Request Category', 'vendor-space'); ?></button>
	                        </div>
	                    </div>

	                    <div class="vs-card" style="padding:18px; border:1px solid #e2e8f0; border-radius:12px; background:#fff; margin-top:14px;">
	                        <div style="display:flex; align-items:center; justify-content:space-between; gap:10px; margin-bottom:10px;">
	                            <h3 style="margin:0; font-size:16px; color:#0f172a;"><?php echo esc_html__('My Category Requests', 'vendor-space'); ?></h3>
	                            <button type="button" id="vs-refresh-vendor-category-requests" class="vs-btn vs-btn--secondary" style="padding:6px 10px;border-radius:8px;">
	                                <?php echo esc_html__('Refresh', 'vendor-space'); ?>
	                            </button>
	                        </div>
	                        <div id="vs-vendor-category-requests-empty" class="vs-empty-state" style="display:none;">
    <div class="vs-empty-state__icon">
        <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
            <path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/>
            <path d="m3.3 7 8.7 5 8.7-5"/>
            <path d="M12 22V12"/>
        </svg>
    </div>
    <p class="vs-empty-state__text">
        <?php echo esc_html__('No category requests yet.', 'vendor-space'); ?>
    </p>
</div>
<style>
    .vs-empty-state {
    padding: 40px 20px;
    border-radius: 12px;
    background: #f8fafc;
    border: 2px dashed #e2e8f0; /* إطار متقطع يعطي إيحاء بالفراغ */
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 12px;
}

.vs-empty-state__icon {
    color: #94a3b8; /* لون رمادي هادئ للأيقونة */
    background: #ffffff;
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
}

.vs-empty-state__text {
    margin: 0;
    font-size: 15px;
    font-weight: 500;
    color: #64748b;
}

/* ─── Unified Premium Custom Select Styles (Shared) ─── */
:root {
    --vs-primary: #6366f1;
    --vs-primary-light: #eef2ff;
    --vs-secondary: #0ea5e9;
    --vs-secondary-light: #f0f9ff;
    --vs-text-main: #1e293b;
    --vs-text-muted: #64748b;
    --vs-border: #d1d5db;
    --vs-shadow-lg: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
}

.vs-cat-select-wrap {
    position: relative;
    margin-bottom: 5px;
}

.vs-custom-select {
    position: relative;
    width: 100%;
}

.vs-select-trigger {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
    min-height: 44px;
    padding: 0 14px;
    background: #ffffff;
    border: 1.5px solid var(--vs-border);
    border-radius: 12px;
    cursor: text;
    transition: all 0.2s ease;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.is-open .vs-select-trigger,
.vs-select-trigger:focus-within {
    border-color: var(--vs-secondary);
    box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.12);
    transform: translateY(-1px);
}

.vs-select-search {
    flex: 1;
    border: none !important;
    outline: none !important;
    font-size: 14px;
    font-weight: 500;
    color: var(--vs-text-main);
    background: transparent;
    padding: 10px 0;
}

.vs-select-dropdown {
    position: absolute;
    top: calc(100% + 8px);
    left: 0;
    right: 0;
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 12px;
    box-shadow: var(--vs-shadow-lg);
    z-index: 99999;
    overflow: hidden;
    animation: vsCatSlideDown 0.2s ease;
}

@keyframes vsCatSlideDown {
    from { opacity: 0; transform: translateY(-8px); }
    to { opacity: 1; transform: translateY(0); }
}

.vs-form-parent-list, #vs-parent-modal-listbox {
    list-style: none !important;
    margin: 0 !important;
    padding: 6px 0 !important;
    max-height: 250px;
    overflow-y: auto;
}

.vs-form-parent-list li, #vs-parent-modal-listbox li {
    padding: 10px 15px !important;
    transition: all 0.15s ease !important;
}

.vs-form-parent-list li:hover, #vs-parent-modal-listbox li:hover {
    background: var(--vs-secondary-light) !important;
}

/* Highlight */
mark.vs-highlight {
    background: #fef08a;
    color: #854d0e;
    padding: 0 1px;
    border-radius: 2px;
    font-weight: 700;
}
</style>
	                        <div style="overflow:auto;">
	                            <table id="vs-vendor-category-requests-table" style="width:100%; border-collapse:collapse;">
	                                <thead>
	                                    <tr style="background:#f8fafc; border-bottom:1px solid #e2e8f0;">
	                                        <th style="padding:8px; text-align:left;">ID</th>
	                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Category', 'vendor-space'); ?></th>
	                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Description', 'vendor-space'); ?></th>
	                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Status', 'vendor-space'); ?></th>
	                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Date', 'vendor-space'); ?></th>
	                                        <th style="padding:8px; text-align:right;"><?php echo esc_html__('Actions', 'vendor-space'); ?></th>
	                                    </tr>
	                                </thead>
	                                <tbody></tbody>
	                            </table>
	                        </div>
	                    </div>
	                    <div id="vs-category-modal" class="vs-modal" style="display:none;">
	                        <div class="vs-modal__dialog">
	                            <div class="vs-modal__header">
	                                <strong id="vs-category-modal-title">Request Category</strong>
                                <button type="button" id="vs-category-modal-close" class="vs-modal__close" aria-label="Close">×</button>
                            </div>

                            <form id="vs-category-form" class="vs-modal__body">
                                <input type="hidden" id="vs-category-term-id" value="">

                                <div style="display:grid; gap:6px;">
                                    <label for="vs-category-name">Name</label>
                                    <input id="vs-category-name" type="text" required>
                                </div>

                                <div style="display:grid; gap:6px;">
                                    <label for="vs-category-slug">Slug (optional)</label>
                                    <input id="vs-category-slug" type="text">
                                </div>

                                <div class="vs-cat-select-wrap" id="vs-form-parent-wrap" style="display:grid; gap:6px; position:relative;">
    <label for="vs-form-parent-search">Parent Category</label>
    
    <input type="hidden" id="vs-category-parent-id" name="vs_category_parent" value="0">

    <div class="vs-custom-select" id="vs-form-parent-container">
        <div class="vs-select-trigger" style="display:flex; align-items:center; border:1px solid #cbd5e1; border-radius:8px; padding:6px 12px; background:#fff;">
            <input type="text" 
                   id="vs-form-parent-search" 
                   class="vs-select-search" 
                   placeholder="Search for parent..." 
                   autocomplete="off"
                   style="border:none; outline:none; flex:1; font-size:14px;">
            <span class="vs-form-parent-clear" style="display:none; cursor:pointer; color:#94a3b8; font-size:18px;">&times;</span>
        </div>

        <div class="vs-form-parent-dropdown" style="display:none; position:absolute; top:100%; left:0; right:0; background:white; border:1px solid #e2e8f0; border-radius:8px; box-shadow:0 10px 15px -3px rgba(0,0,0,0.1); z-index:99999; max-height:200px; overflow-y:auto; margin-top:5px;">
            <ul class="vs-form-parent-list" style="list-style:none; padding:0; margin:0;">
                </ul>
        </div>
    </div>
</div>
<script>
(function() {
    const ALL_CATS = <?php echo wp_json_encode($cats_json); ?>;
    
    const wrap         = document.getElementById('vs-form-parent-wrap');
    const searchInput  = document.getElementById('vs-form-parent-search');
    const dropdown     = wrap.querySelector('.vs-form-parent-dropdown');
    const listUl       = wrap.querySelector('.vs-form-parent-list');
    const hiddenInput  = document.getElementById('vs-category-parent-id');
    const clearBtn     = wrap.querySelector('.vs-form-parent-clear');

    function renderOptions(query = '') {
        if (!listUl) return;
        listUl.innerHTML = '';
        const q = query.toLowerCase().trim();
        
        if (!q) {
            const noneLi = document.createElement('li');
            noneLi.style.padding = "10px 15px";
            noneLi.innerHTML = `<div style="color:#94a3b8; font-style:italic; font-size:13px; cursor:pointer;">— None —</div>`;
            noneLi.onclick = () => selectItem(0, '');
            listUl.appendChild(noneLi);
        }

        const filtered = ALL_CATS.filter(cat => 
            cat.name.toLowerCase().includes(q) || cat.path.toLowerCase().includes(q)
        );

        filtered.forEach(cat => {
            const li = document.createElement('li');
            li.style.padding = "10px 15px";
            li.style.cursor = "pointer";
            li.style.borderBottom = "1px solid #f1f5f9";
            
            li.innerHTML = `
                <div style="margin-left:${cat.depth * 15}px; display:flex; flex-direction:column;">
                    <span class="cat-name" style="font-weight:600; color:#1e293b; font-size:14px;">${cat.name}</span>
                    <span class="cat-path" style="color:#64748b; font-size:11px;">${cat.path}</span>
                </div>
            `;
            
            li.onclick = () => selectItem(cat.id, cat.name);
            li.onmouseover = () => li.style.background = "#f0f9ff";
            li.onmouseout = () => li.style.background = "transparent";
            listUl.appendChild(li);
        });

        if (q && filtered.length === 0) {
            listUl.innerHTML = '<li style="padding:15px; text-align:center; color:#94a3b8; font-size:12px;">No results found</li>';
        }
    }

    function selectItem(id, name) {
        hiddenInput.value = id;
        searchInput.value = name;
        dropdown.style.display = 'none';
        if (clearBtn) clearBtn.style.display = id === 0 ? 'none' : 'block';
    }

    // المستمعات (Events)
    searchInput.onfocus = () => {
        renderOptions(searchInput.value);
        dropdown.style.display = 'block';
    };

    searchInput.oninput = (e) => {
        renderOptions(e.target.value);
    };

    if (clearBtn) {
        clearBtn.onclick = (e) => {
            e.stopPropagation();
            selectItem(0, '');
        };
    }

    document.addEventListener('click', (e) => {
        if (!wrap.contains(e.target)) dropdown.style.display = 'none';
    });

    // معالجة إرسال النموذج (Request)
    const categoryForm = document.getElementById('vs-category-request-form'); // تأكد من الـ ID للفورم
    if (categoryForm) {
        categoryForm.onsubmit = function(e) {
            // هنا يمكنك إضافة كود AJAX الخاص بك
            console.log('Parent ID selected:', hiddenInput.value);
            console.log('Description:', document.getElementById('vs-category-description').value);
        };
    }
})();
</script>                                <div style="display:grid; gap:6px;">
                                    <label for="vs-category-description">Description (optional)</label>
                                    <textarea id="vs-category-description" rows="3"></textarea>
                                </div>

                                <div class="vs-modal__footer">
                                    <button type="button" id="vs-category-cancel" class="vs-btn vs-btn--secondary">Cancel</button>
                                    <button type="submit" id="vs-category-save" class="vs-btn vs-btn--primary">Request</button>
                                </div>
                            </form>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="vs-card" style="padding:18px; border:1px solid #e2e8f0; border-radius:12px; background:#fff;">
                        <div style="background:#fef2f2; color:#991b1b; padding:12px 14px; border-radius:10px; font-weight:600;">
                            <?php echo esc_html__('You do not have permission to manage product categories.', 'vendor-space'); ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <input type="hidden" id="vs-categories-security" value="<?php echo esc_attr(wp_create_nonce('vs_nonce')); ?>">

                <div class="vs-card" style="padding:0; overflow:hidden; border-radius:12px; border:1px solid #e2e8f0; background:#fff;">
                    <table class="vs-categories-table" style="width:100%; border-collapse:collapse;">
                        <thead>
                            <tr style="background: #f8fafc; border-bottom: 1px solid #e2e8f0;">
                                <th style="padding: 15px 20px; width: 40px; background-color: #f8fafc;">
                                    <input type="checkbox" id="vs-select-all-categories" style="cursor:pointer; width:18px; height:18px;">
                                </th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Name', 'vendor-space'); ?></th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Slug', 'vendor-space'); ?></th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Parent', 'vendor-space'); ?></th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc;"><?php echo esc_html__('Count', 'vendor-space'); ?></th>
                                <th style="padding: 15px 20px; font-weight: 600; color: #475569;background-color: #f8fafc; text-align:right;"><?php echo esc_html__('Actions', 'vendor-space'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($terms) || is_wp_error($terms)): ?>
                                <tr>
                                    <td colspan="6" style="padding:40px; text-align:center; color:#6b7280;">No categories found.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($terms as $t):
                                    if (!($t instanceof WP_Term)) continue;
                                    $parent_name = '';
                                    if ((int) $t->parent > 0) {
                                        $pt = get_term((int) $t->parent, self::TAXONOMY);
                                        if ($pt && !is_wp_error($pt)) {
                                            $parent_name = $pt->name;
                                        }
                                    }
                                ?>
                                    <tr id="vs-cat-row-<?php echo (int) $t->term_id; ?>" style="border-bottom:1px solid #f1f5f9;">
                                        <td style="padding:15px; width: 40px;">
                                            <input type="checkbox" class="vs-cat-checkbox" value="<?php echo (int) $t->term_id; ?>" style="cursor:pointer; width:18px; height:18px;">
                                        </td>
                                        <td style="padding:15px; font-weight:600; color:#1e293b;"><?php echo esc_html($t->name); ?></td>
                                        <td style="padding:15px; color:#475569;"><?php echo esc_html($t->slug); ?></td>
                                        <td style="padding:15px; color:#475569;"><?php echo esc_html($parent_name); ?></td>
                                        <td style="padding:15px; color:#475569;"><?php echo (int) $t->count; ?></td>
                                        <td style="padding:15px; text-align:right;">
                                            <div style="display:inline-flex; gap:10px; flex-wrap:wrap; justify-content:flex-end;">
                                                <button type="button"
                                                    class="vs-edit-category-btn"
                                                    data-term-id="<?php echo (int) $t->term_id; ?>"
                                                    data-name="<?php echo esc_attr($t->name); ?>"
                                                    data-slug="<?php echo esc_attr($t->slug); ?>"
                                                    data-parent="<?php echo (int) $t->parent; ?>"
                                                    data-description="<?php echo esc_attr($t->description); ?>"
                                                    style="background:#0ea5e9; color:white; border:none; padding:8px 14px; border-radius:8px; cursor:pointer; font-size:13px; font-weight:600; display:flex; align-items:center; gap:6px;">
                                                    <i class="fas fa-pen"></i> Edit
                                                </button>

                                                <button type="button"
                                                    class="vs-delete-category-btn"
                                                    data-term-id="<?php echo (int) $t->term_id; ?>"
                                                    style="background:#fff; color:#ef4444; border:1px solid #fca5a5; padding:8px 14px; border-radius:8px; cursor:pointer; font-size:13px; font-weight:600; display:flex; align-items:center; gap:6px;">
                                                    <i class="fas fa-trash-alt"></i> Delete
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                    <div class="vs-orders-pagination" id="vs-categories-pagination"
                        style="margin:15px 20px 18px;display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap;">
                    </div>
                </div>

                <div id="vs-category-modal" class="vs-modal">
                    <div class="vs-modal__dialog">
                        <div class="vs-modal__header">
                            <strong id="vs-category-modal-title">Add Category</strong>
                            <button type="button" id="vs-category-modal-close" class="vs-modal__close" aria-label="Close">×</button>
                        </div>

                        <form id="vs-category-form" class="vs-modal__body">
                            <input type="hidden" id="vs-category-term-id" value="">

                            <div style="display:grid; gap:6px;">
                                <label for="vs-category-name">Name</label>
                                <input id="vs-category-name" type="text" required>
                            </div>

                            <div style="display:grid; gap:6px;">
                                <label for="vs-category-slug">Slug (optional)</label>
                                <input id="vs-category-slug" type="text">
                            </div>

    <div class="vs-field full vs-parent-modal-wrap" style="position:relative;">
    <label for="vs-parent-modal-search">Parent Category</label>

    

    <input type="hidden" id="vs-category-parent" name="vs_category_parent" value="0">

    <div class="vs-custom-select vs-parent-modal-dropdown" id="vs-parent-modal-dropdown">
        
        <div class="vs-select-trigger" style="display: flex; align-items: center; border: 1px solid #cbd5e1; border-radius: 8px; padding: 6px 12px; background: #fff;">
            <input 
                type="text" 
                id="vs-parent-modal-search" 
                class="vs-select-search" 
                placeholder="Search for parent..." 
                autocomplete="off"
                style="flex: 1; border: none; outline: none; font-size: 14px;"
            >
            <span id="vs-parent-modal-clear" style="cursor: pointer; color: #94a3b8; display: none; padding: 0 5px;">&times;</span>
            <span style="color: #94a3b8; font-size: 10px; margin-left: 5px;">▼</span>
        </div>

        <div class="vs-select-dropdown" id="vs-parent-modal-listbox-wrap" style="display: none; position: absolute; width: 100%; background: #fff; border: 1px solid #cbd5e1; border-radius: 8px; box-shadow: 0 10px 15px rgba(0,0,0,0.1); z-index: 99999; max-height: 200px; overflow-y: auto;">
            <ul id="vs-parent-modal-listbox" style="list-style: none; padding: 0; margin: 0;">
                </ul>
        </div>
    </div>
</div>
<script>
(function() {
    // 1. جلب البيانات الممررة من PHP
    const MODAL_CATS = <?php echo wp_json_encode($cats_json); ?>;
    
    // 2. ربط عناصر الـ DOM الخاصة بمودال الـ Parent فقط
    const searchEl    = document.getElementById('vs-parent-modal-search');
    const listWrap    = document.getElementById('vs-parent-modal-listbox-wrap');
    const listEl      = document.getElementById('vs-parent-modal-listbox');
    const hiddenInput = document.getElementById('vs-category-parent');
    const clearBtn    = document.getElementById('vs-parent-modal-clear');
    const dropdownWrap = document.getElementById('vs-parent-modal-dropdown');

    if (!searchEl || !listEl) return; // تأمين الكود في حال عدم وجود العناصر

    // 3. بناء الخيارات
    function buildModalOptions(query) {
        const q = (query || '').toLowerCase().trim();
        listEl.innerHTML = '';

        // خيار "بلا قسم أب" (None)
        const noneLi = document.createElement('li');
        noneLi.innerHTML = '<span style="font-weight:500; color:#64748b;">-- No parent (None) --</span>';
        noneLi.style.cssText = "padding: 8px 12px; cursor: pointer; border-bottom: 1px solid #f1f5f9;";
        noneLi.addEventListener('click', () => selectOption(0, ''));
        listEl.appendChild(noneLi);

        // فلترة وبناء الأقسام
        MODAL_CATS.forEach(cat => {
            const nameMatch = cat.name.toLowerCase().includes(q);
            const pathMatch = cat.path.toLowerCase().includes(q);
            
            if (q && !nameMatch && !pathMatch) return;

            const li = document.createElement('li');
            li.style.cssText = `
                padding: 8px 12px;
                cursor: pointer;
                border-bottom: 1px solid #f1f5f9;
                padding-left: ${12 + (cat.depth * 15)}px;
            `;
            li.innerHTML = `
                <div style="font-weight: 500; color: #1e293b; font-size:14px;">${cat.name}</div>
                ${cat.depth > 0 ? `<div style="font-size: 11px; color: #94a3b8;">${cat.path}</div>` : ''}
            `;
            
            li.addEventListener('click', () => selectOption(cat.id, cat.name));
            listEl.appendChild(li);
        });
    }

    // 4. دالة الاختيار
    function selectOption(id, name) {
        hiddenInput.value = id;
        searchEl.value = id === 0 ? '' : name;
        clearBtn.style.display = id !== 0 ? 'block' : 'none';
        listWrap.style.display = 'none';
        dropdownWrap.classList.remove('is-open');
    }

    // 5. الأحداث (Events)
    searchEl.addEventListener('focus', () => {
        buildModalOptions(searchEl.value);
        listWrap.style.display = 'block';
        dropdownWrap.classList.add('is-open');
    });

    searchEl.addEventListener('input', () => {
        buildModalOptions(searchEl.value);
    });

    clearBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        selectOption(0, '');
        searchEl.focus();
    });

    // إغلاق القائمة عند الضغط في أي مكان خارجها
    document.addEventListener('click', (e) => {
        if (!dropdownWrap.contains(e.target)) {
            listWrap.style.display = 'none';
            dropdownWrap.classList.remove('is-open');
        }
    });

    // البناء الأولي
    buildModalOptions('');
})();
</script>

                            <div style="display:grid; gap:6px;">
                                <label for="vs-category-description">Description (optional)</label>
                                <textarea id="vs-category-description" rows="3"></textarea>
                            </div>

                            <div class="vs-modal__footer">
                                <button type="button" id="vs-category-cancel" class="vs-btn vs-btn--secondary">Cancel</button>
                                <button type="submit" id="vs-category-save" class="vs-btn vs-btn--primary">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div id="vs-requests-modal" class="vs-modal" style="display:none;">
                    <div class="vs-modal__dialog" style="width:900px; max-width:95%;">
                        <div class="vs-modal__header">
                            <strong><?php echo esc_html__('Category Requests', 'vendor-space'); ?></strong>
                            <button type="button" id="vs-requests-modal-close" class="vs-modal__close" aria-label="Close">×</button>
                        </div>
                        <div class="vs-modal__body" style="padding:12px; background:#fff;">
                            <input type="hidden" id="vs-categories-security" value="<?php echo esc_attr(wp_create_nonce('vs_nonce')); ?>">
                            <table id="vs-requests-table" style="width:100%; border-collapse:collapse;">
                                <thead>
                                    <tr style="background:#f8fafc; border-bottom:1px solid #e2e8f0;">
                                        <th style="padding:8px; text-align:left;">ID</th>
                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Category', 'vendor-space'); ?></th>
                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Vendor', 'vendor-space'); ?></th>
                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Description', 'vendor-space'); ?></th>
                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Status', 'vendor-space'); ?></th>
                                        <th style="padding:8px; text-align:left;"><?php echo esc_html__('Date', 'vendor-space'); ?></th>
                                        <th style="padding:8px; text-align:right;"><?php echo esc_html__('Actions', 'vendor-space'); ?></th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <script>
            function selectCat(id, name) {
    selectedId = id;
    document.getElementById('vs-category-parent').value = id; // ربط القيمة بالفورم
    searchEl.value = id === 0 ? '' : name;
    clearBtn.style.display = id !== 0 ? 'flex' : 'none';
    closeDropdown();
}

        </script>
        <style>
            /* تحسينات عامة للمودال */
.vs-modal {
    display: none; 
    position: fixed;
    z-index: 9999;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(15, 23, 42, 0.6); /* خلفية داكنة شفافة */
    backdrop-filter: blur(4px); /* تأثير ضبابي للخلفية */
    align-items: center;
    justify-content: center;
}

.vs-modal__dialog {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    width: 100%;
    max-width: 500px;
    overflow: hidden;
    animation: vsModalFadeIn 0.3s ease-out;
}

@keyframes vsModalFadeIn {
    from { opacity: 0; transform: translateY(-20px); }
    to { opacity: 1; transform: translateY(0); }
}

/* الرأس (Header) */
.vs-modal__header {
    padding: 1.25rem 1.5rem;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f8fafc;
}

.vs-modal__header strong {
    font-size: 1.1rem;
    color: #1e293b;
    font-weight: 600;
}

.vs-modal__close {
    background: transparent;
    border: none;
    font-size: 1.5rem;
    color: #94a3b8;
    cursor: pointer;
    transition: color 0.2s;
}

.vs-modal__close:hover { color: #ef4444; }

/* الجسم (Body) */
.vs-modal__body {
    padding: 1.5rem;
    display: grid;
    gap: 1.25rem;
}

.vs-modal__body label {
    font-weight: 500;
    font-size: 0.9rem;
    color: #475569;
    margin-bottom: -0.5rem;
}

.vs-modal__body input, 
.vs-modal__body select, 
.vs-modal__body textarea {
    width: 100%;
    padding: 0.625rem 0.875rem;
    border: 1px solid #cbd5e1;
    border-radius: 8px;
    font-size: 0.95rem;
    transition: border-color 0.2s, box-shadow 0.2s;
}

.vs-modal__body input:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* التذييل (Footer) */
.vs-modal__footer {
    padding: 1.25rem 1.5rem;
    background: #f8fafc;
    border-top: 1px solid #e2e8f0;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* الأزرار */
.vs-btn {
    padding: 0.6rem 1.2rem;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    border: none;
}

.vs-btn--secondary {
    background: #fff;
    border: 1px solid #cbd5e1;
    color: #64748b;
}

.vs-btn--secondary:hover { background: #f1f5f9; }

.vs-btn--primary {
    background: #3b82f6;
    color: white;
}

.vs-btn--primary:hover { background: #2563eb; }

.vs-btn--cancel {
    background: #fff1f2;
    color: #e11d48;
    border: 1px solid #fecdd3;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 11px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.vs-btn--cancel:hover {
    background: #e11d48;
    color: #ffffff;
    border-color: #e11d48;
    transform: translateY(-1px);
    box-shadow: 0 4px 6px -1px rgba(225, 29, 72, 0.2);
}

.vs-btn--cancel i {
    font-size: 13px;
}

/* تحسين الجدول */
#vs-requests-table {
    border-radius: 8px;
    overflow: hidden;
}

#vs-requests-table th {
    background: #f1f5f9;
    color: #475569;
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.75rem;
    letter-spacing: 0.05em;
}

#vs-requests-table td {
    padding: 12px;
    border-bottom: 1px solid #f1f5f9;
    color: #1e293b;
}

#vs-requests-table tr:hover { background: #f8fafc; }


/* تحسين شكل القائمة المنسدلة داخل المودال */
.vs-cat-select-wrap .vs-select-trigger {
    background: #fff;
    border: 1px solid #cbd5e1;
    border-radius: 8px;
    padding: 4px 12px;
    display: flex;
    align-items: center;
}

.vs-cat-select-wrap .vs-select-dropdown {
    position: absolute;
    width: 100%;
    background: white;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
    z-index: 100;
    max-height: 200px;
    overflow-y: auto;
}

.vs-cat-option {
    padding: 8px 12px;
    cursor: pointer;
    display: flex;
    flex-direction: column;
}

.vs-cat-option:hover { background: #f8fafc; }
.vs-cat-name { font-weight: 500; font-size: 14px; color: #1e293b; }
.vs-cat-path { font-size: 11px; color: #94a3b8; }

/* إزاحة الأقسام الفرعية */
.vs-cat-option[style*="--cat-depth"] {
    padding-left: calc(12px + var(--cat-depth) * 15px);
}
/* حاوية القائمة المنسدلة */
.vs-parent-select-dropdown {
    border: 1px solid #cbd5e1 !important;
    border-radius: 8px !important;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1) !important;
    max-height: 250px !important;
    overflow-y: auto !important;
    background: #ffffff !important;
    margin-top: 4px;
}

/* قائمة العناصر */
.vs-parent-cat-list {
    list-style: none !important;
    padding: 0 !important;
    margin: 0 !important;
}

/* العنصر الفردي في القائمة */
.vs-parent-cat-list li {
    padding: 10px 15px !important;
    transition: all 0.2s ease;
    border-bottom: 1px solid #f1f5f9 !important;
    display: flex;
    flex-direction: column; /* ليكون الاسم فوق المسار */
}

/* تأثير عند تمرير الماوس */
.vs-parent-cat-list li:hover {
    background-color: #f0f9ff !important; /* لون أزرق فاتح جداً */
    border-left: 4px solid #3b82f6 !important; /* خط جانبي أزرق */
    cursor: pointer;
}

/* تلوين اسم القسم الرئيسي */
.vs-parent-cat-list li .cat-name {
    color: #1e293b; /* رمادي غامق جداً */
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 2px;
}

/* تلوين المسار (القسم الأب > القسم الحالي) */
.vs-parent-cat-list li .cat-path {
    color: #64748b; /* رمادي فاتح للمسار */
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* تمييز الأقسام الفرعية بإزاحة */
.vs-parent-cat-list li .indent-wrap {
    display: flex;
    align-items: center;
    gap: 8px;
}

/* أيقونة صغيرة قبل الأقسام الفرعية (اختياري) */
.vs-parent-cat-list li .indent-wrap::before {
    content: "↳";
    color: #cbd5e1;
    font-weight: bold;
}
        </style>
        <?php
        return ob_get_clean();
    }
}
