<?php
/**
 * Name: Custom Post Type Builder
 * Description: Create custom post types with easy or advanced mode using simple intuitive interface for building movies, products, events, portfolios, or any custom content
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Real Estate Listings",
 *     "description": "Create 'Properties' custom post type with archive page and custom fields for real estate agent's MLS listings."
 *   },
 *   {
 *     "title": "Team Member Profiles",
 *     "description": "Build 'Team' post type for company about page showing all employees with bios, photos, and contact information."
 *   },
 *   {
 *     "title": "Product Documentation",
 *     "description": "Develop 'Docs' custom post type separate from blog for software documentation with different archive structure."
 *   }
 * ]
 * Added: 2025-08-20
 * Tags: custom-post-types, cpt, post-types, builder, content-types
 * WhereToFind: {
 *   "location": "Switchboard → CPT Builder",
 *   "url": "admin.php?page=cpt-builder",
 *   "instructions": "Manage your custom post types from dedicated dashboard",
 *   "newTab": false
 * }
 */

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

class SwitchboardCPTBuilder {

    public function __construct() {
        // Register CPTs - must run after module is loaded (priority 10+)
        // But still early enough for WordPress to recognize them
        add_action('init', [$this, 'register_custom_post_types'], 11);

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

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

        // AJAX handler for stats only
        add_action('wp_ajax_get_cpt_stats', [$this, 'get_cpt_stats']);

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

        // Admin notices
        add_action('admin_notices', [$this, 'show_admin_notices']);

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

    /**
     * Add admin menu for CPT Builder
     */
    public function add_admin_menu() {
        add_submenu_page(
            'switchboard',
            'CPT Builder',
            'CPT Builder',
            'manage_options',
            'cpt-builder',
            [$this, 'render_admin_page']
        );
    }

    /**
     * Render admin page
     * Always show admin.php which handles routing internally
     */
    public function render_admin_page() {
        // Handle delete action
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['cpt'])) {
            $this->handle_delete();
            return;
        }

        // Always include admin.php which handles all views (list, add, edit)
        $admin_file = plugin_dir_path(__FILE__) . '../../assets/cpt-builder/admin.php';
        if (file_exists($admin_file)) {
            include $admin_file;
        } else {
            echo '<div class="wrap"><h1>' . esc_html__('Admin page not found', 'wpswitchboard') . '</h1></div>';
        }
    }

    /**
     * Handle delete action
     */
    private function handle_delete() {
        if (!isset($_GET['cpt'])) {
            wp_die(esc_html__('No CPT specified', 'wpswitchboard'));
        }

        $slug = sanitize_key($_GET['cpt']);

        // Verify nonce
        if (!wp_verify_nonce($_GET['_wpnonce'], 'delete_cpt_' . $slug)) {
            wp_die(esc_html__('Security check failed', 'wpswitchboard'));
        }

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

        // Delete CPT
        $cpts = get_option('switchboard_custom_post_types', []);
        $found = false;

        foreach ($cpts as $key => $cpt) {
            if ($cpt['slug'] === $slug) {
                unset($cpts[$key]);
                $found = true;
                break;
            }
        }

        if ($found) {
            update_option('switchboard_custom_post_types', array_values($cpts));
            flush_rewrite_rules();

            // Redirect with success message
            wp_redirect(add_query_arg([
                'page' => 'cpt-builder',
                'message' => 'deleted'
            ], admin_url('admin.php')));
            exit;
        } else {
            wp_die(esc_html__('CPT not found', 'wpswitchboard'));
        }
    }

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

        if (!$is_cpt_page) {
            return;
        }

        // Enqueue the main Switchboard admin CSS (contains all global module styles)
        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_settings() method removed - CPT Builder uses dedicated admin page
    // Settings icon redirects to admin.php?page=cpt-builder (configured in switchboard.php)

    /**
     * Show debug info
     */
    public function show_debug_info() {
        $cpts = get_option('switchboard_custom_post_types', []);
        $active_modules = get_option('switchboard_active_modules', []);

        echo '<div class="notice notice-info" class="p-5">';
        echo '<h2>CPT Builder Debug Info</h2>';

        echo '<p><strong>Module Active:</strong> ';
        echo in_array('cpt-builder', $active_modules) ? 'YES' : 'NO';
        echo '</p>';

        echo '<p><strong>Saved CPTs:</strong> ' . count($cpts) . '</p>';

        if (!empty($cpts)) {
            echo '<h3 class="sb-sp-heading">CPT Details:</h3>';
            foreach ($cpts as $cpt) {
                echo '<div style="background: #f5f5f5; padding: 10px; margin: 10px 0; border-left: 4px solid #2271b1;">';
                echo '<p><strong>Name:</strong> ' . esc_html($cpt['name']) . '</p>';
                echo '<p><strong>Slug:</strong> ' . esc_html($cpt['slug']) . '</p>';
                echo '<p><strong>Registered:</strong> ';
                if (post_type_exists($cpt['slug'])) {
                    echo 'YES';
                    $obj = get_post_type_object($cpt['slug']);
                    echo '<br>- Show in Menu: ' . ($obj->show_in_menu ? 'Yes' : 'No');
                    echo '<br>- Show UI: ' . ($obj->show_ui ? 'Yes' : 'No');
                    echo '<br>- Public: ' . ($obj->public ? 'Yes' : 'No');
                } else {
                    echo 'NO';
                }
                echo '</p>';
                echo '<pre class="bg-white">' . print_r($cpt, true) . '</pre>';
                echo '</div>';
            }
        }

        echo '<p><a href="' . admin_url('admin.php?page=switchboard') . '" class="button button-primary">Go to Switchboard</a></p>';
        echo '<p><a href="' . admin_url('admin.php?page=cpt-builder') . '" class="button button-secondary">Go to CPT Builder</a></p>';
        echo '</div>';
    }

    /**
     * Register custom post types on init
     */
    public function register_custom_post_types() {
        $cpts = get_option('switchboard_custom_post_types', []);

        if (empty($cpts)) {
            return;
        }

        foreach ($cpts as $cpt) {
            if (empty($cpt['slug'])) {
                continue;
            }

            $labels = [
                'name' => $cpt['plural_name'] ?? $cpt['name'],
                'singular_name' => $cpt['name'],
                'menu_name' => $cpt['menu_name'] ?? $cpt['plural_name'] ?? $cpt['name'],
                'add_new' => _x('Add New', 'custom post type', 'wpswitchboard'),
                'add_new_item' => sprintf(__('Add New %s', 'wpswitchboard'), $cpt['name']),
                'edit_item' => sprintf(__('Edit %s', 'wpswitchboard'), $cpt['name']),
                'new_item' => sprintf(__('New %s', 'wpswitchboard'), $cpt['name']),
                'view_item' => sprintf(__('View %s', 'wpswitchboard'), $cpt['name']),
                'search_items' => sprintf(__('Search %s', 'wpswitchboard'), $cpt['plural_name'] ?? $cpt['name']),
                'not_found' => sprintf(__('No %s found', 'wpswitchboard'), strtolower($cpt['plural_name'] ?? $cpt['name'])),
                'not_found_in_trash' => sprintf(__('No %s found in trash', 'wpswitchboard'), strtolower($cpt['plural_name'] ?? $cpt['name'])),
            ];

            $args = [
                'labels' => $labels,
                'public' => isset($cpt['public']) ? (bool)$cpt['public'] : true,
                'publicly_queryable' => isset($cpt['publicly_queryable']) ? (bool)$cpt['publicly_queryable'] : true,
                'show_ui' => isset($cpt['show_ui']) ? (bool)$cpt['show_ui'] : true,
                'show_in_menu' => isset($cpt['show_in_menu']) ? (bool)$cpt['show_in_menu'] : true,
                'show_in_nav_menus' => isset($cpt['show_in_nav_menus']) ? (bool)$cpt['show_in_nav_menus'] : true,
                'show_in_rest' => isset($cpt['show_in_rest']) ? (bool)$cpt['show_in_rest'] : true,
                'has_archive' => isset($cpt['has_archive']) ? (bool)$cpt['has_archive'] : true,
                'hierarchical' => isset($cpt['hierarchical']) ? (bool)$cpt['hierarchical'] : false,
                'menu_position' => isset($cpt['menu_position']) ? intval($cpt['menu_position']) : 5,
                'menu_icon' => !empty($cpt['menu_icon']) ? $cpt['menu_icon'] : 'dashicons-admin-post',
                'supports' => !empty($cpt['supports']) ? $cpt['supports'] : ['title', 'editor', 'thumbnail'],
                'rewrite' => [
                    'slug' => !empty($cpt['rewrite_slug']) ? $cpt['rewrite_slug'] : $cpt['slug'],
                    'with_front' => isset($cpt['with_front']) ? (bool)$cpt['with_front'] : true,
                ],
                'capability_type' => !empty($cpt['capability_type']) ? $cpt['capability_type'] : 'post',
                'map_meta_cap' => true,
            ];

            // Add taxonomies if specified
            if (!empty($cpt['taxonomies'])) {
                $args['taxonomies'] = $cpt['taxonomies'];
            }

            register_post_type($cpt['slug'], $args);
        }
    }

    /**
     * Handle form submission (WordPress admin_post_ action)
     * This is the reliable, standard WordPress way
     */
    public function handle_save() {
        // Verify nonce
        if (!isset($_POST['cpt_builder_nonce']) || !wp_verify_nonce($_POST['cpt_builder_nonce'], 'cpt_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
        $cpt_data = [
            'name' => sanitize_text_field($_POST['cpt_name']),
            'plural_name' => sanitize_text_field($_POST['cpt_plural_name']),
            'slug' => sanitize_key($_POST['cpt_slug']),
            'menu_icon' => sanitize_text_field($_POST['cpt_menu_icon']),
            'menu_position' => intval($_POST['cpt_menu_position']),
            'rewrite_slug' => sanitize_text_field($_POST['cpt_rewrite_slug']),
            'supports' => isset($_POST['cpt_supports']) && is_array($_POST['cpt_supports']) ? array_map('sanitize_text_field', $_POST['cpt_supports']) : [],
            'public' => !empty($_POST['cpt_public']),
            'show_in_rest' => !empty($_POST['cpt_show_in_rest']),
            'has_archive' => !empty($_POST['cpt_has_archive']),
            'hierarchical' => !empty($_POST['cpt_hierarchical']),
        ];

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

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

        // Check for reserved post types
        $reserved_types = ['post', 'page', 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block'];
        if (in_array($cpt_data['slug'], $reserved_types)) {
            wp_die(esc_html__('This slug is reserved by WordPress', 'wpswitchboard'));
        }

        // Get existing CPTs
        $cpts = get_option('switchboard_custom_post_types', []);

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

        if (!$found) {
            // Check if slug already exists (when adding new)
            foreach ($cpts as $cpt) {
                if ($cpt['slug'] === $cpt_data['slug']) {
                    wp_die(esc_html__('A custom post type with this slug already exists', 'wpswitchboard'));
                }
            }
            $cpts[] = $cpt_data;
        }

        // Save
        update_option('switchboard_custom_post_types', $cpts);

        // Flush rewrite rules
        flush_rewrite_rules();

        // Redirect with success message
        $redirect_url = add_query_arg([
            'page' => 'cpt-builder',
            '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'] !== 'cpt-builder') {
            return;
        }

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

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

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

    /**
     * AJAX: Get CPT statistics
     */
    public function get_cpt_stats() {
        check_ajax_referer('switchboard_settings', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => esc_html__('Permission denied', 'wpswitchboard')]);
        }

        $cpts = get_option('switchboard_custom_post_types', []);

        $stats = [
            'total_cpts' => count($cpts),
            'registered_cpts' => 0,
            'total_posts' => 0,
            'avg_supports' => 0,
        ];

        if (!empty($cpts)) {
            $total_supports = 0;

            foreach ($cpts as $cpt) {
                // Check if registered
                if (post_type_exists($cpt['slug'])) {
                    $stats['registered_cpts']++;

                    // Count posts
                    $count_posts = wp_count_posts($cpt['slug']);
                    if ($count_posts) {
                        $stats['total_posts'] += intval($count_posts->publish ?? 0);
                    }
                }

                // Count supports
                $total_supports += count($cpt['supports'] ?? []);
            }

            // Calculate average
            $stats['avg_supports'] = $stats['total_cpts'] > 0 ? round($total_supports / $stats['total_cpts'], 1) : 0;
        }

        wp_send_json_success($stats);
    }

    /**
     * Register data locations for cleanup system
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_custom_post_types',
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
        ];
    }
}

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