<?php
/**
 * AI Auto Tool - Legal Pages Generator Implementation
 * 
 * Automatically generates essential legal pages using AI
 * 
 * @package AIAutoTool
 */

if ( ! defined( 'ABSPATH' ) ) exit;

class AIautotool_Legal_Pages_Generator extends rendersetting {
    public $active = '';
    public $active_option_name = 'AIautotool_legal_pages_active';
    
    public function __construct() {
        $this->active = get_option($this->active_option_name, 'false');
        
        // Always register menu (even if inactive, so user can activate from menu)
        add_action('admin_menu', array($this, 'add_menu'), 20);
        
        // Always enqueue assets (needed for our dedicated page)
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
        
        if ($this->active === 'true') {
            // Register AJAX handlers
            add_action('wp_ajax_aiautotool_generate_legal_pages', array($this, 'ajax_generate_legal_pages'));
        }
    }
    
    /**
     * Add submenu page under AI Auto Tool
     */
    public function add_menu() {
        add_submenu_page(
            MENUSUBPARRENT,
            '<i class="fa-solid fa-file-contract"></i> ' . esc_html__('Legal Pages Generator','ai-auto-tool'),          
            '<i class="fa-solid fa-file-contract"></i> ' . esc_html__('Legal Pages Generator','ai-auto-tool'),    
            'manage_options',
            'legal-pages-generator',
            array($this, 'render_legal_pages_page')
        );
    }
    
    /**
     * Enqueue JavaScript and CSS
     */
    public function enqueue_assets($hook) {
        // Load on our specific page
        if (strpos($hook, 'legal-pages-generator') === false && strpos($hook, 'ai_auto_tool') === false) {
            return;
        }
        
        wp_enqueue_script(
            'aiautotool-legal-pages',
            plugins_url('assets/legal-pages.js', __FILE__),
            array('jquery'),
            filemtime(dirname(__FILE__) . '/assets/legal-pages.js'),
            true
        );
        
        wp_enqueue_style(
            'aiautotool-legal-pages',
            plugins_url('assets/legal-pages.css', __FILE__),
            array(),
            filemtime(dirname(__FILE__) . '/assets/legal-pages.css')
        );
        
        // Localize script with AJAX URL and nonce
        wp_localize_script('aiautotool-legal-pages', 'aiautotoolLegalPages', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('aiautotool_legal_pages_nonce'),
            'strings' => array(
                'generating' => __('Generating legal pages...', 'ai-auto-tool'),
                'success' => __('Legal pages generated successfully!', 'ai-auto-tool'),
                'error' => __('Error generating pages. Please try again.', 'ai-auto-tool'),
                'validationError' => __('Please fill in all required fields.', 'ai-auto-tool'),
            )
        ));
    }
    
    /**
     * Render dedicated Legal Pages page
     */
    public function render_legal_pages_page() {
        ?>
        <div class="aiautotool_container">
            <div class="ft-wrap-top"></div>
            <div class="wrap ft-wrap">
                <div class="ft-wrap-body">
                    <div class="ft-box">
                       
                        <div class="ft-main">
                            <div class="aiautotool_legal_pages_container">
                                <div class="autoblogging-header">
                                    <h2><i class="fa-solid fa-file-contract"></i> <?php esc_html_e('Legal Pages Generator', 'ai-auto-tool'); ?></h2>
                                    <p class="autoblogging-subtitle"><?php esc_html_e('Automatically generate essential legal pages for your website using AI. All pages will be created as drafts in English for your review.', 'ai-auto-tool'); ?></p>
                                </div>
                                
                                <div class="aiautotool-card">
                                    <div class="aiautotool-card-body">
                                        <div class="aiautotool-notice aiautotool-notice-warning">
                                            <i class="fa-solid fa-triangle-exclamation"></i>
                                            <strong><?php esc_html_e('Important:', 'ai-auto-tool'); ?></strong>
                                            <?php esc_html_e('AI-generated legal content should be reviewed by a legal professional before publishing. This tool provides a starting point, not a replacement for professional legal advice.', 'ai-auto-tool'); ?>
                                        </div>
                                        
                                        <form id="aiautotool-legal-pages-form" class="aiautotool-form">
                                            <div class="form-group">
                                                <label for="legal_pages_prompt">
                                                    <?php esc_html_e('Additional Context (Optional)', 'ai-auto-tool'); ?>
                                                    <span class="description"><?php esc_html_e('Provide specific details about your business or website', 'ai-auto-tool'); ?></span>
                                                </label>
                                                <textarea 
                                                    id="legal_pages_prompt" 
                                                    name="prompt" 
                                                    rows="4" 
                                                    class="large-text"
                                                    placeholder="<?php esc_attr_e('e.g., Tech startup providing AI-powered WordPress plugins...', 'ai-auto-tool'); ?>"
                                                ></textarea>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="legal_pages_email">
                                                    <?php esc_html_e('Contact Email', 'ai-auto-tool'); ?> <span class="required">*</span>
                                                </label>
                                                <input 
                                                    type="email" 
                                                    id="legal_pages_email" 
                                                    name="email" 
                                                    class="regular-text" 
                                                    required
                                                    value="<?php echo esc_attr(get_option('admin_email')); ?>"
                                                    placeholder="contact@example.com"
                                                />
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="legal_pages_phone">
                                                    <?php esc_html_e('Contact Phone (Optional)', 'ai-auto-tool'); ?>
                                                </label>
                                                <input 
                                                    type="tel" 
                                                    id="legal_pages_phone" 
                                                    name="phone" 
                                                    class="regular-text"
                                                    placeholder="+1-555-1234"
                                                />
                                            </div>
                                            
                                            <div class="form-group">
                                                <label for="legal_pages_address">
                                                    <?php esc_html_e('Contact Address (Optional)', 'ai-auto-tool'); ?>
                                                </label>
                                                <textarea 
                                                    id="legal_pages_address" 
                                                    name="address" 
                                                    rows="3" 
                                                    class="large-text"
                                                    placeholder="<?php esc_attr_e('123 Business Street, City, Country', 'ai-auto-tool'); ?>"
                                                ></textarea>
                                            </div>
                                            
                                            <div class="form-group">
                                                <h3><?php esc_html_e('Pages to Generate', 'ai-auto-tool'); ?></h3>
                                                <ul class="legal-pages-list">
                                                    <li><i class="fa-solid fa-check"></i> <?php esc_html_e('About Us', 'ai-auto-tool'); ?></li>
                                                    <li><i class="fa-solid fa-check"></i> <?php esc_html_e('Terms of Service / Terms & Conditions', 'ai-auto-tool'); ?></li>
                                                    <li><i class="fa-solid fa-check"></i> <?php esc_html_e('Privacy Policy', 'ai-auto-tool'); ?></li>
                                                    <li><i class="fa-solid fa-check"></i> <?php esc_html_e('Disclaimer', 'ai-auto-tool'); ?></li>
                                                    <li><i class="fa-solid fa-check"></i> <?php esc_html_e('Contact Us', 'ai-auto-tool'); ?></li>
                                                </ul>
                                            </div>
                                            
                                            <div class="form-actions">
                                                <button type="submit" class="button button-primary button-large" id="generate-legal-pages-btn">
                                                    <i class="fa-solid fa-wand-magic-sparkles"></i>
                                                    <?php esc_html_e('Generate Legal Pages', 'ai-auto-tool'); ?>
                                                </button>
                                            </div>
                                            
                                            <div id="legal-pages-progress" class="aiautotool-progress" style="display:none;">
                                                <div class="progress-bar">
                                                    <div class="progress-fill"></div>
                                                </div>
                                                <p class="progress-text"></p>
                                            </div>
                                            
                                            <div id="legal-pages-result" class="aiautotool-result" style="display:none;"></div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Render settings page (kept for backwards compatibility with tab system)
     */
    public function render_setting() {
        // Tab content - no longer used since we have dedicated page
        // Keeping for compatibility
    }
    
    /**
     * Render tab setting
     */
    public function render_tab_setting() {
        if ($this->active === 'true') {
            echo '<button href="#tool-legal-pages" class="nav-tab sotab"><i class="fa-solid fa-file-contract"></i> ' . esc_html__('Legal Pages', 'ai-auto-tool') . '</button>';
        }
    }
    
    /**
     * AJAX handler to generate legal pages
     */
    public function ajax_generate_legal_pages() {
        // Verify nonce
        check_ajax_referer('aiautotool_legal_pages_nonce', 'nonce');
        
        // Check user permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Insufficient permissions', 'ai-auto-tool')));
        }
        
        // Get form data
        $prompt = isset($_POST['prompt']) ? sanitize_textarea_field($_POST['prompt']) : '';
        $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : '';
        $phone = isset($_POST['phone']) ? sanitize_text_field($_POST['phone']) : '';
        $address = isset($_POST['address']) ? sanitize_textarea_field($_POST['address']) : '';
        
        // Validate required fields
        if (empty($email)) {
            wp_send_json_error(array('message' => __('Email is required', 'ai-auto-tool')));
        }
        
        // Get website information
        $site_name = get_bloginfo('name');
        $site_url = get_bloginfo('url');
        $site_description = get_bloginfo('description');
        
        // Prepare context for AI
        $context = $this->prepare_context($site_name, $site_url, $site_description, $email, $phone, $address, $prompt);
        
        // Generate pages
        $results = array();
        $pages_config = $this->get_pages_config();
        
        foreach ($pages_config as $page_key => $page_data) {
            $result = $this->generate_single_page($page_data, $context);
            $results[$page_key] = $result;
            
            if (!$result['success']) {
                wp_send_json_error(array(
                    'message' => sprintf(__('Failed to generate %s', 'ai-auto-tool'), $page_data['title']),
                    'details' => $result
                ));
            }
        }
        
        wp_send_json_success(array(
            'message' => __('All legal pages generated successfully!', 'ai-auto-tool'),
            'pages' => $results
        ));
    }
    
    /**
     * Prepare context for AI generation
     */
    private function prepare_context($site_name, $site_url, $site_description, $email, $phone, $address, $prompt) {
        $context = "Website Information:\n";
        $context .= "- Website Name: {$site_name}\n";
        $context .= "- Website URL: {$site_url}\n";
        
        if (!empty($site_description)) {
            $context .= "- Website Description: {$site_description}\n";
        }
        
        $context .= "\nContact Information:\n";
        $context .= "- Email: {$email}\n";
        
        if (!empty($phone)) {
            $context .= "- Phone: {$phone}\n";
        }
        
        if (!empty($address)) {
            $context .= "- Address: {$address}\n";
        }
        
        if (!empty($prompt)) {
            $context .= "\nAdditional Context:\n{$prompt}\n";
        }
        
        return $context;
    }
    
    /**
     * Get configuration for pages to generate
     */
    private function get_pages_config() {
        return array(
            'about' => array(
                'title' => __('About Us', 'ai-auto-tool'),
                'slug' => 'about-us',
                'prompt_template' => 'Write a professional "About Us" page for the website described below. The content should be engaging, professional, and highlight the mission and values of the organization. Write in English and use HTML formatting for better readability. Include sections about the company background, mission, and team if applicable.'
            ),
            'terms' => array(
                'title' => __('Terms of Service', 'ai-auto-tool'),
                'slug' => 'terms-of-service',
                'prompt_template' => 'Write comprehensive Terms of Service (Terms & Conditions) for the website described below. Cover important legal aspects including: user responsibilities, acceptable use, intellectual property rights, disclaimers, limitation of liability, termination, governing law, and dispute resolution. Write in English, use professional legal language, and format with HTML headings and lists for clarity. This should be legally sound but readable.'
            ),
            'privacy' => array(
                'title' => __('Privacy Policy', 'ai-auto-tool'),
                'slug' => 'privacy-policy',
                'prompt_template' => 'Write a comprehensive Privacy Policy for the website described below. Cover: what personal data is collected, how it is collected, why it is collected, how it is used, how it is stored and protected, user rights (access, deletion, portability), cookies policy, third-party services, data retention, and contact information. Ensure GDPR and privacy regulation compliance. Write in English with HTML formatting for clarity.'
            ),
            'disclaimer' => array(
                'title' => __('Disclaimer', 'ai-auto-tool'),
                'slug' => 'disclaimer',
                'prompt_template' => 'Write a comprehensive Disclaimer page for the website described below. Cover: accuracy of information, professional advice disclaimer, limitation of liability, external links disclaimer, affiliate disclosure (if applicable), errors and omissions, and any industry-specific disclaimers. Write in English with clear, professional legal language formatted with HTML.'
            ),
            'contact' => array(
                'title' => __('Contact Us', 'ai-auto-tool'),
                'slug' => 'contact-us',
                'prompt_template' => 'Write a friendly and professional "Contact Us" page for the website described below. Include an introduction inviting users to get in touch, display the provided contact information (email, phone, address) in a well-formatted way, and mention response time expectations. Add a note about contact form if applicable. Write in English with HTML formatting.'
            )
        );
    }
    
    /**
     * Generate a single page using AI
     */
    private function generate_single_page($page_data, $context) {
        try {
            // Check if AI Agent is available
            if (!class_exists('AIAutotool_AI_Agent')) {
                return array(
                    'success' => false,
                    'message' => __('AI Agent not available', 'ai-auto-tool')
                );
            }
            
            // Prepare AI prompt
            $full_prompt = $page_data['prompt_template'] . "\n\n" . $context;
            
            // Call AI Agent with legal industry context
            $ai_agent = AIAutotool_AI_Agent::get_instance();
            $response = $ai_agent->generate($full_prompt, array(
                'industry' => 'legal',
                'max_tokens' => 2000,
                'temperature' => 0.7
            ));
            
            // Check if AI generation was successful
            if (empty($response) || !isset($response['success']) || !$response['success']) {
                $error_message = isset($response['error']) ? $response['error'] : __('AI failed to generate content', 'ai-auto-tool');
                return array(
                    'success' => false,
                    'message' => $error_message
                );
            }
            
            // Extract content from response
            $content = isset($response['content']) ? $response['content'] : '';
            if (empty($content)) {
                return array(
                    'success' => false,
                    'message' => __('AI returned empty content', 'ai-auto-tool')
                );
            }
            
            // Create WordPress page
            $page_id = wp_insert_post(array(
                'post_title' => $page_data['title'],
                'post_name' => $page_data['slug'],
                'post_content' => $content,
                'post_status' => 'draft',
                'post_type' => 'page',
                'post_author' => get_current_user_id(),
                'comment_status' => 'closed',
                'ping_status' => 'closed'
            ));
            
            if (is_wp_error($page_id)) {
                return array(
                    'success' => false,
                    'message' => $page_id->get_error_message()
                );
            }
            
            return array(
                'success' => true,
                'page_id' => $page_id,
                'edit_url' => admin_url('post.php?post=' . $page_id . '&action=edit'),
                'title' => $page_data['title']
            );
            
        } catch (Exception $e) {
            return array(
                'success' => false,
                'message' => $e->getMessage()
            );
        }
    }
}
