<?php
/**
 * Name: Bulk Page Creator
 * Description: Quickly create multiple standard business pages with predefined templates for About, Contact, Privacy Policy, Terms of Service, and other common pages with clicks
 * Category: Content
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Location Pages Creation",
 *     "description": "Generate 50 location landing pages at once for multi-location businesses (dentists, restaurants, franchises) with consistent structure."
 *   },
 *   {
 *     "title": "Service Pages Setup",
 *     "description": "Create 20+ individual service pages for agencies or service providers instead of manually creating each page one by one."
 *   },
 *   {
 *     "title": "Documentation Structure",
 *     "description": "Build out complete documentation hierarchy with 100+ pages in organized structure for software or product documentation."
 *   }
 * ]
 * Added: 2025-08-12
 * Tags: pages, bulk, create, business, templates
 * WhereToFind: {
 *   "location": "Pages List",
 *   "url": "edit.php?post_type=page",
 *   "instructions": "Check for newly created pages after using the bulk creator",
 *   "newTab": false
 * }
 */

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

class SwitchboardBulkPageCreator {
    
    public function __construct() {
        add_action('wp_ajax_switchboard_create_bulk_pages', [$this, 'ajax_create_pages']);
        
        // Register with data registry
        $this->register_with_data_registry();
    }
    
    private function register_with_data_registry() {
        if (class_exists('Switchboard_Data_Registry')) {
            $registry = Switchboard_Data_Registry::get_instance();
            $registry->auto_register($this, __FILE__);
        }
    }
    
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_bulk-page-creator_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => [],
            'transients' => []
        ];
    }
    
    /**
     * Render settings panel for Bulk Page Creator
     * 
     * Displays an interactive UI for quickly creating multiple standard business pages:
     * - Two-column layout: Available pages | Selected pages
     * - Real-time selection tracking with visual feedback
     * - Progress bar for batch page creation
     * - Prevents duplicate page creation (checks existing slugs)
     * - Categorized page templates (About, Services, Legal, etc.)
     * 
     * Note: Uses IIFE and event unbinding to prevent state persistence issues
     * 
     * @param array $settings Current module settings (not used)
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        // Get pages and existing slugs
        $pages = $this->get_standard_pages();
        $categories = array_unique(array_column($pages, 'category'));
        $existing_pages = get_pages(['post_status' => 'publish,draft']);
        $existing_slugs = array_map(function($page) {
            return $page->post_name;
        }, $existing_pages);
        ?>
        <input type="hidden" name="module" value="bulk-page-creator">
        <div class="sb-sp-group">
        <p class="sb-sp-description"><?php esc_html_e('Quickly create standard business pages. Click pages to add them to your creation list.', 'wpswitchboard'); ?></p>
        </div>

        <div class="sb-sp-grid-2">
            <!-- Left: Available Pages -->
            <div>
                <h4 class="sb-sp-heading-sm"><?php esc_html_e('Available Pages', 'wpswitchboard'); ?></h4>
                <div class="sb-sp-card" style="max-height: 600px; overflow-y: auto;">
                    <?php foreach ($categories as $category): ?>
                        <div style="border-top: 1px solid #e5e7eb; padding: 12px 16px; background: #f9fafb; font-weight: 600; font-size: 13px; color: #374151;">
                                <?php echo esc_html($category); ?>
                            </div>
                            
                            <?php foreach ($pages as $page):
                                if ($page['category'] !== $category) continue;
                                $exists = in_array($page['slug'], $existing_slugs);
                                $disabled = $exists ? 'disabled' : '';
                                $title = $exists ? esc_attr__('Page already exists', 'wpswitchboard') : esc_attr__('Click to add', 'wpswitchboard');
                            ?>
                            <div class="page-item available <?php echo esc_attr($disabled); ?>" style="padding: 12px 16px; border-bottom: 1px solid #e5e7eb; display: flex; align-items: center; justify-content: space-between; cursor: <?php echo $disabled ? 'not-allowed' : 'pointer'; ?>; transition: all 0.15s ease; <?php echo $disabled ? 'opacity: 0.6;' : ''; ?>"
                                     data-name="<?php echo esc_attr($page['name']); ?>"
                                     data-slug="<?php echo esc_attr($page['slug']); ?>"
                                     title="<?php echo esc_attr($title); ?>">
                                <span style="font-size: 14px; color: #111827;"><?php echo esc_html($page['name']); ?></span>
                                    <?php if ($exists): ?>
                                    <span class="dashicons dashicons-yes" style="color: var(--primary-500); font-size: 16px; width: 16px; height: 16px;"></span>
                                    <?php else: ?>
                                    <span style="color: var(--primary-500); font-size: 18px; font-weight: 600;">+</span>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- Right: Selected Pages -->
            <div>
                <h4 class="sb-sp-heading-sm"><?php esc_html_e('Pages to Create', 'wpswitchboard'); ?> (<span id="selected-count">0</span>)</h4>

                <div id="selected-pages" class="sb-sp-card" style="min-height: 200px; max-height: 400px; overflow-y: auto; margin-bottom: 16px;">
                    <p style="padding: 20px; text-align: center; color: #64748b; font-size: 14px; margin: 0;"><?php esc_html_e('Click pages on the left to add them', 'wpswitchboard'); ?></p>
                </div>

                <div class="sb-sp-group">
                    <label class="sb-sp-label"><?php esc_html_e('Page Status', 'wpswitchboard'); ?></label>
                    <select id="page-status" class="sb-sp-select">
                        <option value="draft"><?php esc_html_e('Draft', 'wpswitchboard'); ?></option>
                        <option value="publish"><?php esc_html_e('Published', 'wpswitchboard'); ?></option>
                    </select>
                </div>

                <button type="button" id="create-pages-btn" class="button button-primary" style="width: 100%;" disabled><?php esc_html_e('Create Selected Pages', 'wpswitchboard'); ?></button>

                <div id="creation-progress" style="display: none; margin-top: 16px;">
                    <div style="background: #e5e7eb; border-radius: 8px; height: 24px; overflow: hidden;">
                        <div id="progress-bar" style="width: 0%; background: var(--primary-500); height: 100%; transition: width 0.3s;"></div>
                    </div>
                    <p id="progress-text" style="text-align: center; margin: 8px 0 0 0; font-size: 13px; color: #64748b;"></p>
                </div>
            </div>
        </div>
        
        <style>
            .page-item.available:not(.disabled):hover {
                background: var(--primary-50) !important;
                border-color: var(--primary-500) !important;
            }
            .page-item.selected {
                padding: 12px 16px;
                border-bottom: 1px solid #e5e7eb;
                display: flex;
                align-items: center;
                justify-content: space-between;
                cursor: pointer;
                transition: all 0.15s ease;
            }
            .page-item.selected:hover {
                background: var(--primary-50) !important;
            }
            .page-item.selected .remove-icon {
                color: #dc2626;
                font-size: 18px;
                font-weight: bold;
                cursor: pointer;
            }
        </style>
        
        <script>
        (function($) {
            const i18n = {
                clickToAdd: <?php echo json_encode(esc_html__('Click pages on the left to add them', 'wpswitchboard')); ?>,
                complete: <?php echo json_encode(esc_html__('Complete!', 'wpswitchboard')); ?>,
                created: <?php echo json_encode(esc_html__('Created', 'wpswitchboard')); ?>,
                pagesSuccessfully: <?php echo json_encode(esc_html__('pages successfully', 'wpswitchboard')); ?>,
                failed: <?php echo json_encode(esc_html__('failed', 'wpswitchboard')); ?>,
                creatingPages: <?php echo json_encode(esc_html__('Creating pages...', 'wpswitchboard')); ?>,
                of: <?php echo json_encode(esc_html__('of', 'wpswitchboard')); ?>
            };

            // Clean up any existing event handlers for bulk page creator
            $(document).off('click', '.page-item.available:not(.disabled)');
            $(document).off('click', '.page-item.selected');
            $('#create-pages-btn').off('click');

            // Initialize fresh state
            let selectedPages = [];
            
            console.log('[Bulk Page Creator] Initializing with fresh state');
            
            // Add page
            $(document).on('click', '.page-item.available:not(.disabled)', function() {
                const name = $(this).data('name');
                const slug = $(this).data('slug');
                
                console.log('[Bulk Page Creator] Adding page:', name, '- Current count before:', selectedPages.length);
                
                selectedPages.push({ name, slug });
                
                console.log('[Bulk Page Creator] Current count after:', selectedPages.length);
                
                const item = `<div class="page-item selected" data-slug="${slug}">
                    <span class="sb-sp-text-sm">${name}</span>
                    <span class="remove-icon">×</span>
                </div>`;
                
                $('#selected-pages p').remove();
                $('#selected-pages').append(item);
                
                $(this).addClass('disabled').css({
                    'opacity': '0.5',
                    'cursor': 'not-allowed',
                    'background': '#fafafa'
                });
                
                updateUI();
            });
            
            // Remove page
            $(document).on('click', '.page-item.selected', function() {
                const slug = $(this).data('slug');
                
                console.log('[Bulk Page Creator] Removing page:', slug, '- Current count before:', selectedPages.length);
                
                selectedPages = selectedPages.filter(p => p.slug !== slug);
                $(this).remove();
                
                console.log('[Bulk Page Creator] Current count after:', selectedPages.length);
                
                $('.page-item.available[data-slug="' + slug + '"]').removeClass('disabled').css({
                    'opacity': '1',
                    'cursor': 'pointer',
                    'background': ''
                });
                
                if (selectedPages.length === 0) {
                    $('#selected-pages').html('<p class="sb-sp-text-gray">' + i18n.clickToAdd + '</p>');
                }
                
                updateUI();
            });
            
            // Create pages
            $('#create-pages-btn').on('click', function() {
                if (selectedPages.length === 0) return;
                
                console.log('[Bulk Page Creator] Creating pages, total:', selectedPages.length);
                
                const status = $('#page-status').val();
                
                $(this).prop('disabled', true);
                $('#creation-progress').show();
                
                let created = 0;
                let failed = 0;
                const total = selectedPages.length;
                
                function createNextPage(index) {
                    if (index >= total) {
                        console.log('[Bulk Page Creator] Finished creating pages. Created:', created, 'Failed:', failed);
                        $('#progress-bar').css('width', '100%').text(i18n.complete);
                        $('#progress-text').text(i18n.created + ' ' + created + ' ' + i18n.pagesSuccessfully + (failed > 0 ? ', ' + failed + ' ' + i18n.failed : ''));
                        
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                        return;
                    }
                    
                    const page = selectedPages[index];
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'switchboard_create_bulk_pages',
                            name: page.name,
                            slug: page.slug,
                            status: status,
                            nonce: '<?php echo esc_attr(wp_create_nonce('bulk_pages')); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                created++;
                                console.log('[Bulk Page Creator] Created page:', page.name);
                            } else {
                                failed++;
                                console.log('[Bulk Page Creator] Failed to create page:', page.name, response);
                            }
                        },
                        error: function() {
                            failed++;
                            console.log('[Bulk Page Creator] Error creating page:', page.name);
                        },
                        complete: function() {
                            const progress = Math.round(((index + 1) / total) * 100);
                            $('#progress-bar').css('width', progress + '%').text(progress + '%');
                            $('#progress-text').text(i18n.creatingPages + ' ' + (index + 1) + ' ' + i18n.of + ' ' + total);
                            
                            createNextPage(index + 1);
                        }
                    });
                }
                
                createNextPage(0);
            });
            
            function updateUI() {
                $('#selected-count').text(selectedPages.length);
                $('#create-pages-btn').prop('disabled', selectedPages.length === 0);
                console.log('[Bulk Page Creator] UI updated, count:', selectedPages.length);
            }
        })(jQuery);
        </script>
        <?php
    }
    
    public function get_standard_pages() {
        return [
            // Essential Pages
            ['name' => 'Home', 'slug' => 'home', 'category' => 'Essential'],
            ['name' => 'About Us', 'slug' => 'about', 'category' => 'Essential'],
            ['name' => 'Contact', 'slug' => 'contact', 'category' => 'Essential'],
            ['name' => 'Services', 'slug' => 'services', 'category' => 'Essential'],
            ['name' => 'Blog', 'slug' => 'blog', 'category' => 'Essential'],
            
            // Legal Pages
            ['name' => 'Privacy Policy', 'slug' => 'privacy-policy', 'category' => 'Legal'],
            ['name' => 'Terms of Service', 'slug' => 'terms-of-service', 'category' => 'Legal'],
            ['name' => 'Cookie Policy', 'slug' => 'cookie-policy', 'category' => 'Legal'],
            ['name' => 'Disclaimer', 'slug' => 'disclaimer', 'category' => 'Legal'],
            ['name' => 'Refund Policy', 'slug' => 'refund-policy', 'category' => 'Legal'],
            
            // Business Pages
            ['name' => 'Pricing', 'slug' => 'pricing', 'category' => 'Business'],
            ['name' => 'FAQ', 'slug' => 'faq', 'category' => 'Business'],
            ['name' => 'Testimonials', 'slug' => 'testimonials', 'category' => 'Business'],
            ['name' => 'Portfolio', 'slug' => 'portfolio', 'category' => 'Business'],
            ['name' => 'Case Studies', 'slug' => 'case-studies', 'category' => 'Business'],
            ['name' => 'Careers', 'slug' => 'careers', 'category' => 'Business'],
            ['name' => 'Team', 'slug' => 'team', 'category' => 'Business'],
            
            // Support Pages
            ['name' => 'Support', 'slug' => 'support', 'category' => 'Support'],
            ['name' => 'Help Center', 'slug' => 'help', 'category' => 'Support'],
            ['name' => 'Documentation', 'slug' => 'docs', 'category' => 'Support'],
            ['name' => 'Knowledge Base', 'slug' => 'knowledge-base', 'category' => 'Support'],
            
            // E-commerce Pages
            ['name' => 'Shop', 'slug' => 'shop', 'category' => 'E-commerce'],
            ['name' => 'Cart', 'slug' => 'cart', 'category' => 'E-commerce'],
            ['name' => 'Checkout', 'slug' => 'checkout', 'category' => 'E-commerce'],
            ['name' => 'My Account', 'slug' => 'my-account', 'category' => 'E-commerce'],
            ['name' => 'Shipping', 'slug' => 'shipping', 'category' => 'E-commerce'],
            
            // Other Pages
            ['name' => 'Sitemap', 'slug' => 'sitemap', 'category' => 'Other'],
            ['name' => 'Thank You', 'slug' => 'thank-you', 'category' => 'Other'],
            ['name' => '404 Page', 'slug' => '404', 'category' => 'Other'],
        ];
    }
    
    public function render_page() {
        $pages = $this->get_standard_pages();
        $categories = array_unique(array_column($pages, 'category'));
        
        // Check for existing pages
        $existing_pages = get_pages(['post_status' => 'publish,draft']);
        $existing_slugs = array_map(function($page) {
            return $page->post_name;
        }, $existing_pages);
        
        ?>
        <div class="wrap">
            <h1>Bulk Page Creator</h1>
            <p>Quickly create standard business pages. Click pages to add them to your creation list.</p>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-top: 30px;">
                <!-- Left: Available Pages -->
                <div>
                    <div class="sb-sp-card">
                        <h2 class="sb-sp-m-0">Available Pages</h2>
                        
                        <?php foreach ($categories as $category): ?>
                            <div style="margin-bottom: 25px;">
                                <h3 class="sb-sp-heading">
                                    <?php echo esc_html($category); ?>
                                </h3>
                                <div class="available-pages-group">
                                    <?php foreach ($pages as $page): 
                                        if ($page['category'] !== $category) continue;
                                        $exists = in_array($page['slug'], $existing_slugs);
                                        $disabled = $exists ? 'disabled' : '';
                                        $style = $exists ? 'opacity: 0.4; cursor: not-allowed;' : 'cursor: pointer;';
                                        $title = $exists ? 'Page already exists' : 'Click to add';
                                    ?>
                                        <div class="page-tag available <?php echo esc_attr($disabled); ?>"
                                             data-name="<?php echo esc_attr($page['name']); ?>"
                                             data-slug="<?php echo esc_attr($page['slug']); ?>"
                                             title="<?php echo esc_attr($title); ?>"
                                             class="sb-sp-inline-block">
                                            <?php echo esc_html($page['name']); ?>
                                            <?php if ($exists): ?>
                                                <span class="dashicons dashicons-yes" style="color: #00a32a; font-size: 14px; width: 14px; height: 14px;"></span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <!-- Right: Selected Pages -->
                <div>
                    <div class="sb-sp-card">
                        <h2 class="sb-sp-m-0">Pages to Create (<span id="selected-count">0</span>)</h2>
                        
                        <div id="selected-pages" style="min-height: 100px; padding: 15px; background: #f6f7f7; border: 2px dashed #c3c4c7; border-radius: 4px; margin-bottom: 20px;">
                            <p class="sb-sp-text-muted">Click pages on the left to add them</p>
                        </div>
                        
                        <div class="sb-sp-mb-4">
                            <label class="sb-sp-label">Page Status</label>
                            <select id="page-status" class="sb-sp-select">
                                <option value="draft">Draft</option>
                                <option value="publish">Published</option>
                            </select>
                        </div>
                        
                        <button id="create-pages-btn" class="button button-primary button-large sb-sp-w-full" disabled>
                            Create Selected Pages
                        </button>
                        
                        <div id="creation-progress" style="display: none;" class="sb-sp-mt-4">
                            <div style="background: #f0f0f1; border-radius: 4px; height: 30px; overflow: hidden;">
                                <div id="progress-bar" style="background: #2271b1; height: 100%; width: 0%; transition: width 0.3s; display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 600;"></div>
                            </div>
                            <p id="progress-text" class="sb-sp-text-center"></p>
                        </div>
                        
                        <div id="creation-results" style="display: none;" class="sb-sp-mt-4"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <style>
            .page-tag.available:not(.disabled):hover {
                background: #e0e0e0 !important;
                border-color: #8c8f94 !important;
            }
            .page-tag.selected {
                background: #2271b1 !important;
                color: white !important;
                border-color: #2271b1 !important;
                cursor: pointer !important;
            }
            .page-tag.selected:hover {
                background: #135e96 !important;
            }
        </style>
        
        <script>
        jQuery(document).ready(function($) {
            let selectedPages = [];
            
            // Add page
            $(document).on('click', '.page-tag.available:not(.disabled)', function() {
                const name = $(this).data('name');
                const slug = $(this).data('slug');
                
                selectedPages.push({ name, slug });
                
                // Add to selected area
                const tag = `<div class="page-tag selected sb-sp-inline-block" data-slug="${slug}">
                    ${name} <span style="margin-left: 4px;">×</span>
                </div>`;
                
                $('#selected-pages p').remove();
                $('#selected-pages').append(tag);
                
                // Mark as selected
                $(this).addClass('disabled').css({
                    'opacity': '0.4',
                    'cursor': 'not-allowed'
                });
                
                updateUI();
            });
            
            // Remove page
            $(document).on('click', '.page-tag.selected', function() {
                const slug = $(this).data('slug');
                
                selectedPages = selectedPages.filter(p => p.slug !== slug);
                
                $(this).remove();
                
                // Unmark in available
                $(`.page-tag.available[data-slug="${slug}"]`).removeClass('disabled').css({
                    'opacity': '1',
                    'cursor': 'pointer'
                });
                
                if (selectedPages.length === 0) {
                    $('#selected-pages').html('<p class="sb-sp-text-gray">Click pages on the left to add them</p>');
                }
                
                updateUI();
            });
            
            // Create pages
            $('#create-pages-btn').on('click', function() {
                if (selectedPages.length === 0) return;
                
                const status = $('#page-status').val();
                
                $(this).prop('disabled', true);
                $('#creation-progress').show();
                $('#creation-results').hide();
                
                let created = 0;
                let failed = 0;
                const total = selectedPages.length;
                
                function createNextPage(index) {
                    if (index >= total) {
                        // Done
                        $('#progress-bar').css('width', '100%').text('Complete!');
                        $('#progress-text').text(`Created ${created} pages successfully${failed > 0 ? `, ${failed} failed` : ''}`);
                        
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                        return;
                    }
                    
                    const page = selectedPages[index];
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'switchboard_create_bulk_pages',
                            name: page.name,
                            slug: page.slug,
                            status: status,
                            nonce: '<?php echo esc_js(wp_create_nonce('bulk_pages')); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                created++;
                            } else {
                                failed++;
                            }
                        },
                        error: function() {
                            failed++;
                        },
                        complete: function() {
                            const progress = Math.round(((index + 1) / total) * 100);
                            $('#progress-bar').css('width', progress + '%').text(progress + '%');
                            $('#progress-text').text(`Creating pages... ${index + 1} of ${total}`);
                            
                            createNextPage(index + 1);
                        }
                    });
                }
                
                createNextPage(0);
            });
            
            function updateUI() {
                $('#selected-count').text(selectedPages.length);
                $('#create-pages-btn').prop('disabled', selectedPages.length === 0);
            }
        });
        </script>
        <?php
    }
    
    public function ajax_create_pages() {
        check_ajax_referer('bulk_pages', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(esc_html__('Unauthorized', 'wpswitchboard'));
        }

        if (!isset($_POST['name'], $_POST['slug'], $_POST['status'])) {
            wp_send_json_error(esc_html__('Missing required parameters', 'wpswitchboard'));
        }

        $name = sanitize_text_field(wp_unslash($_POST['name']));
        $slug = sanitize_title(wp_unslash($_POST['slug']));
        $status = sanitize_key($_POST['status']);

        // Validate status
        if (!in_array($status, ['draft', 'publish'], true)) {
            $status = 'draft'; // Default to draft if invalid
        }
        
        // Check if page already exists
        $existing = get_page_by_path($slug);
        if ($existing) {
            wp_send_json_error(esc_html__('Page already exists', 'wpswitchboard'));
        }
        
        // Create page
        $page_id = wp_insert_post([
            'post_title' => $name,
            'post_name' => $slug,
            'post_type' => 'page',
            'post_status' => $status,
            'post_content' => '<!-- wp:paragraph --><p>This is the ' . esc_html($name) . ' page.</p><!-- /wp:paragraph -->'
        ]);
        
        if (is_wp_error($page_id)) {
            wp_send_json_error($page_id->get_error_message());
        }
        
        wp_send_json_success([
            'page_id' => $page_id,
            'edit_url' => get_edit_post_link($page_id, 'raw')
        ]);
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardBulkPageCreator();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
