<?php
/**
 * Name: Custom Taxonomy Builder
 * Description: Create custom taxonomies with easy or advanced mode using simple intuitive interface for building categories, tags, or hierarchical classification systems for any post type
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Recipe Categories",
 *     "description": "Create 'Cuisine' and 'Meal Type' taxonomies for food blog to filter recipes by multiple criteria beyond standard categories."
 *   },
 *   {
 *     "title": "Product Attributes",
 *     "description": "Build 'Brand', 'Color', and 'Size' taxonomies for fashion e-commerce site to enable advanced product filtering."
 *   },
 *   {
 *     "title": "Location Organization",
 *     "description": "Add 'Region' and 'City' taxonomies to organize business listings or real estate by geographic area."
 *   }
 * ]
 * Added: 2025-08-28
 * Tags: taxonomy, custom-taxonomy, categories, tags, builder
 * WhereToFind: {
 *   "location": "Switchboard > Taxonomy Builder",
 *   "url": "admin.php?page=custom-taxonomy-builder",
 *   "instructions": "Access the dedicated Taxonomy Builder page to create and manage custom taxonomies with a beautiful interface",
 *   "newTab": false
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardCustomTaxonomyBuilder {

    public function __construct() {
        // Register taxonomies - must run after module is loaded
        // Priority 11 ensures it runs after WPML/Polylang initialization (priority 10)
        add_action('init', [$this, 'register_custom_taxonomies'], 11);

        // Admin menu
        add_action('admin_menu', [$this, 'add_admin_menu']);

        // Enqueue admin assets
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);

        // Form submission handler (WordPress standard way)
        add_action('admin_post_taxonomy_builder_save', [$this, 'handle_save']);

        // AJAX handlers (keep for backward compatibility if needed)
        add_action('wp_ajax_delete_taxonomy', [$this, 'delete_taxonomy']);

        // Debug helper
        if (isset($_GET['taxonomy_debug']) && current_user_can('manage_options')) {
            add_action('admin_notices', [$this, 'show_debug_info']);
        }
    }

    /**
     * Add admin menu for Custom Taxonomy Builder
     */
    public function add_admin_menu() {
        add_submenu_page(
            'switchboard',
            __('Taxonomy Builder', 'wpswitchboard'),
            __('Taxonomy Builder', 'wpswitchboard'),
            'manage_options',
            'custom-taxonomy-builder',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Enqueue admin assets only on our page
     */
    public function enqueue_admin_assets($hook) {
        // Check if we're on the taxonomy builder page (check both hook and GET parameter)
        $is_tax_page = (
            (isset($_GET['page']) && $_GET['page'] === 'custom-taxonomy-builder') ||
            strpos($hook, 'custom-taxonomy-builder') !== false
        );

        if (!$is_tax_page) {
            return;
        }

        // Enqueue the main Switchboard admin CSS (contains all sb-mp-* and sb-sp-* classes)
        if (defined('SWITCHBOARD_URL') && defined('SWITCHBOARD_VERSION')) {
            wp_enqueue_style(
                'switchboard-admin',
                SWITCHBOARD_URL . 'switchboard-admin.css',
                [],
                SWITCHBOARD_VERSION
            );
        }

        // Ensure jQuery is loaded
        wp_enqueue_script('jquery');
    }
    
    /**
     * Render the admin page for Custom Taxonomy Builder
     */
    public function render_admin_page() {
        // Handle delete action
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['tax'])) {
            $this->handle_delete();
            return;
        }

        // Determine which view to show
        $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : '';

        if ($action === 'add' || $action === 'edit') {
            // Show edit page
            $edit_file = plugin_dir_path(__FILE__) . '../../assets/custom-taxonomy-builder/admin.php';
            if (file_exists($edit_file)) {
                include $edit_file;
            } else {
                echo '<div class="wrap"><h1>' . esc_html__('Admin page not found', 'wpswitchboard') . '</h1></div>';
            }
        } else {
            // Show list page
            $list_file = plugin_dir_path(__FILE__) . '../../assets/custom-taxonomy-builder/admin.php';
            if (file_exists($list_file)) {
                include $list_file;
            } else {
                echo '<div class="wrap"><h1>' . esc_html__('List page not found', 'wpswitchboard') . '</h1></div>';
            }
        }
    }

    /**
     * Handle delete action
     */
    private function handle_delete() {
        $tax_slug = isset($_GET['tax']) ? sanitize_key($_GET['tax']) : '';
        $nonce = isset($_GET['_wpnonce']) ? $_GET['_wpnonce'] : '';

        if (empty($tax_slug)) {
            wp_die(esc_html__('Taxonomy slug is required', 'wpswitchboard'));
        }

        if (!wp_verify_nonce($nonce, 'delete_tax_' . $tax_slug)) {
            wp_die(esc_html__('Security check failed', 'wpswitchboard'));
        }

        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied', 'wpswitchboard'));
        }

        $taxonomies = get_option('switchboard_custom_taxonomies', []);
        $taxonomies = array_filter($taxonomies, function($tax) use ($tax_slug) {
            return $tax['slug'] !== $tax_slug;
        });

        update_option('switchboard_custom_taxonomies', array_values($taxonomies));
        flush_rewrite_rules();

        wp_redirect(add_query_arg([
            'page' => 'custom-taxonomy-builder',
            'message' => 'deleted'
        ], admin_url('admin.php')));
        exit;
    }

    /**
     * Handle form submission (WordPress admin_post_ action)
     */
    public function handle_save() {
        // Verify nonce
        if (!isset($_POST['taxonomy_builder_nonce']) || !wp_verify_nonce($_POST['taxonomy_builder_nonce'], 'taxonomy_builder_save')) {
            wp_die(esc_html__('Security check failed', 'wpswitchboard'));
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Permission denied', 'wpswitchboard'));
        }

        // Get form data
        $is_edit = !empty($_POST['is_edit']);
        $original_slug = $is_edit ? sanitize_key($_POST['original_slug']) : '';

        // Collect and sanitize data
        $tax_data = [
            'name' => sanitize_text_field($_POST['tax_name']),
            'plural_name' => sanitize_text_field($_POST['tax_plural_name']),
            'slug' => sanitize_key($_POST['tax_slug']),
            'hierarchical' => isset($_POST['tax_type']) && $_POST['tax_type'] === 'hierarchical',
            'rewrite_slug' => sanitize_text_field($_POST['tax_rewrite_slug']),
            'post_types' => isset($_POST['tax_post_types']) && is_array($_POST['tax_post_types']) ? array_map('sanitize_key', $_POST['tax_post_types']) : [],
            'public' => !empty($_POST['tax_public']),
            'show_in_rest' => !empty($_POST['tax_show_in_rest']),
            'show_admin_column' => !empty($_POST['tax_show_admin_column']),
            'show_tagcloud' => !empty($_POST['tax_show_tagcloud']),
        ];

        // Validate required fields
        if (empty($tax_data['name']) || empty($tax_data['slug'])) {
            wp_die(esc_html__('Name and slug are required', 'wpswitchboard'));
        }

        // Validate slug format
        if (!preg_match('/^[a-z0-9_-]+$/', $tax_data['slug'])) {
            wp_die(esc_html__('Slug must contain only lowercase letters, numbers, underscores, and hyphens', 'wpswitchboard'));
        }

        // Validate at least one post type
        if (empty($tax_data['post_types'])) {
            wp_die(esc_html__('Please select at least one post type', 'wpswitchboard'));
        }

        // Get existing taxonomies
        $taxonomies = get_option('switchboard_custom_taxonomies', []);

        // Update or add
        $found = false;
        foreach ($taxonomies as $key => $tax) {
            if ($tax['slug'] === ($is_edit ? $original_slug : $tax_data['slug'])) {
                $taxonomies[$key] = $tax_data;
                $found = true;
                break;
            }
        }

        if (!$found) {
            // Check if slug already exists (when adding new)
            foreach ($taxonomies as $tax) {
                if ($tax['slug'] === $tax_data['slug']) {
                    wp_die(esc_html__('A custom taxonomy with this slug already exists', 'wpswitchboard'));
                }
            }
            $taxonomies[] = $tax_data;
        }

        // Save
        update_option('switchboard_custom_taxonomies', $taxonomies);

        // Flush rewrite rules
        flush_rewrite_rules();

        // Redirect with success message
        $redirect_url = add_query_arg([
            'page' => 'custom-taxonomy-builder',
            'action' => 'edit',
            'tax' => $tax_data['slug'],
            'message' => $is_edit ? 'updated' : 'created'
        ], admin_url('admin.php'));

        wp_redirect($redirect_url);
        exit;
    }

    /**
     * Show admin notices after actions
     */
    public function show_admin_notices() {
        if (!isset($_GET['page']) || $_GET['page'] !== 'custom-taxonomy-builder') {
            return;
        }

        if (!isset($_GET['message'])) {
            return;
        }

        $message = sanitize_text_field($_GET['message']);
        $messages = [
            'created' => __('Custom taxonomy created successfully!', 'wpswitchboard'),
            'updated' => __('Custom taxonomy updated successfully!', 'wpswitchboard'),
            'deleted' => __('Custom taxonomy deleted successfully!', 'wpswitchboard'),
        ];

        if (isset($messages[$message])) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html($messages[$message]) . '</p></div>';
        }
    }

    /**
     * Register custom taxonomies on init
     */
    public function register_custom_taxonomies() {
        $taxonomies = get_option('switchboard_custom_taxonomies', []);
        
        if (empty($taxonomies)) {
            return;
        }
        
        foreach ($taxonomies as $tax) {
            if (empty($tax['slug'])) {
                continue;
            }
            
            $args = [
                'labels' => [
                    'name' => $tax['plural_name'] ?? $tax['name'] . 's',
                    'singular_name' => $tax['name'],
                    'menu_name' => $tax['plural_name'] ?? $tax['name'] . 's',
                    'all_items' => sprintf(__('All %s', 'wpswitchboard'), $tax['plural_name'] ?? $tax['name'] . 's'),
                    'edit_item' => sprintf(__('Edit %s', 'wpswitchboard'), $tax['name']),
                    'view_item' => sprintf(__('View %s', 'wpswitchboard'), $tax['name']),
                    'update_item' => sprintf(__('Update %s', 'wpswitchboard'), $tax['name']),
                    'add_new_item' => sprintf(__('Add New %s', 'wpswitchboard'), $tax['name']),
                    'new_item_name' => sprintf(__('New %s Name', 'wpswitchboard'), $tax['name']),
                    'parent_item' => sprintf(__('Parent %s', 'wpswitchboard'), $tax['name']),
                    'parent_item_colon' => sprintf(__('Parent %s:', 'wpswitchboard'), $tax['name']),
                    'search_items' => sprintf(__('Search %s', 'wpswitchboard'), $tax['plural_name'] ?? $tax['name'] . 's'),
                    'popular_items' => sprintf(__('Popular %s', 'wpswitchboard'), $tax['plural_name'] ?? $tax['name'] . 's'),
                    'separate_items_with_commas' => sprintf(__('Separate %s with commas', 'wpswitchboard'), $tax['plural_name'] ?? $tax['name'] . 's'),
                    'add_or_remove_items' => sprintf(__('Add or remove %s', 'wpswitchboard'), $tax['plural_name'] ?? $tax['name'] . 's'),
                    'choose_from_most_used' => sprintf(__('Choose from the most used %s', 'wpswitchboard'), $tax['plural_name'] ?? $tax['name'] . 's'),
                    'not_found' => sprintf(__('No %s found', 'wpswitchboard'), $tax['plural_name'] ?? $tax['name'] . 's'),
                ],
                'hierarchical' => !empty($tax['hierarchical']),
                'public' => isset($tax['public']) ? (bool) $tax['public'] : true,
                'show_ui' => true,
                'show_admin_column' => !empty($tax['show_admin_column']),
                'show_in_nav_menus' => true,
                'show_tagcloud' => !empty($tax['show_tagcloud']),
                'show_in_rest' => !empty($tax['show_in_rest']),
                'query_var' => true,
                'rewrite' => [
                    'slug' => !empty($tax['rewrite_slug']) ? $tax['rewrite_slug'] : $tax['slug'],
                    'with_front' => false,
                ],
            ];
            
            $post_types = !empty($tax['post_types']) && is_array($tax['post_types']) ? $tax['post_types'] : ['post'];
            
            register_taxonomy($tax['slug'], $post_types, $args);
        }
    }
    
    /**
     * AJAX handler for saving taxonomy (kept for backward compatibility)
     */
    public function save_taxonomy() {
        check_ajax_referer('switchboard_settings', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }
        
        $tax_data = json_decode(stripslashes($_POST['tax_data']), true);
        
        if (empty($tax_data['name']) || empty($tax_data['slug'])) {
            wp_send_json_error(['message' => __('Name and slug are required', 'wpswitchboard')]);
        }
        
        $taxonomies = get_option('switchboard_custom_taxonomies', []);
        
        if (!empty($tax_data['is_edit'])) {
            // Update existing
            foreach ($taxonomies as $key => $tax) {
                if ($tax['slug'] === $tax_data['slug']) {
                    $taxonomies[$key] = $tax_data;
                    break;
                }
            }
        } else {
            // Add new
            $taxonomies[] = $tax_data;
        }
        
        update_option('switchboard_custom_taxonomies', $taxonomies);
        flush_rewrite_rules();
        
        wp_send_json_success(['message' => __('Taxonomy saved successfully', 'wpswitchboard')]);
    }
    
    /**
     * AJAX handler for deleting taxonomy
     */
    public function delete_taxonomy() {
        check_ajax_referer('switchboard_settings', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }
        
        $slug = sanitize_key($_POST['slug']);
        
        $taxonomies = get_option('switchboard_custom_taxonomies', []);
        $taxonomies = array_filter($taxonomies, function($tax) use ($slug) {
            return $tax['slug'] !== $slug;
        });
        
        update_option('switchboard_custom_taxonomies', array_values($taxonomies));
        flush_rewrite_rules();
        
        wp_send_json_success(['message' => __('Taxonomy deleted successfully', 'wpswitchboard')]);
    }
    
    /**
     * AJAX handler for getting taxonomy data
     */
    public function get_taxonomy_data() {
        check_ajax_referer('switchboard_settings', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied', 'wpswitchboard')]);
        }
        
        $slug = sanitize_key($_POST['slug']);
        $taxonomies = get_option('switchboard_custom_taxonomies', []);
        
        foreach ($taxonomies as $tax) {
            if ($tax['slug'] === $slug) {
                wp_send_json_success(['taxonomy' => $tax]);
                return;
            }
        }
        
        wp_send_json_error(['message' => __('Taxonomy not found', 'wpswitchboard')]);
    }
    
    /**
     * Register data locations for Switchboard
     */
    public function register_data_locations() {
        return [
            'switchboard_custom_taxonomies' => [
                'label' => __('Custom Taxonomies', 'wpswitchboard'),
                'description' => __('Custom taxonomy configurations', 'wpswitchboard'),
            ],
        ];
    }
}

$switchboard_instance = new SwitchboardCustomTaxonomyBuilder();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
