<?php
/**
 * HVAC Help System
 * 
 * Manages welcome guide, tooltips, and documentation for the HVAC Community Events plugin
 */

class HVAC_Help_System {
    
    private static $instance = null;
    
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_help_assets'));
        add_action('wp_footer', array($this, 'render_welcome_guide'));
        add_shortcode('hvac_documentation', array($this, 'render_documentation_page'));
        add_action('wp_ajax_hvac_dismiss_welcome', array($this, 'handle_welcome_dismissal'));
        add_action('wp_ajax_nopriv_hvac_dismiss_welcome', array($this, 'handle_welcome_dismissal'));
    }
    
    /**
     * Enqueue help system assets
     */
    public function enqueue_help_assets() {
        // Only load on HVAC pages for authenticated trainers
        if (!$this->is_hvac_page() || !$this->is_trainer_logged_in()) {
            return;
        }
        
        // Enqueue Font Awesome for icons
        wp_enqueue_style(
            'font-awesome',
            'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css',
            array(),
            '6.0.0'
        );
        
        wp_enqueue_style(
            'hvac-help-system',
            HVAC_PLUGIN_URL . 'assets/css/hvac-help-system.css',
            array('hvac-common-style', 'font-awesome'),
            HVAC_PLUGIN_VERSION
        );
        
        wp_enqueue_script(
            'hvac-help-system',
            HVAC_PLUGIN_URL . 'assets/js/hvac-help-system.js',
            array('jquery'),
            HVAC_PLUGIN_VERSION,
            true
        );
        
        wp_localize_script('hvac-help-system', 'hvacHelp', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('hvac_help_nonce'),
            'showWelcome' => $this->should_show_welcome_guide()
        ));
    }
    
    /**
     * Check if current page is an HVAC custom page
     */
    private function is_hvac_page() {
        $hvac_pages = array(
            'hvac-dashboard', 'trainer-registration', 'community-login',
            'trainer-profile', 'event-summary', 'email-attendees',
            'certificate-reports', 'generate-certificates', 'hvac-documentation'
        );
        
        foreach ($hvac_pages as $page) {
            if (is_page($page)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Check if current user is a logged-in trainer
     */
    private function is_trainer_logged_in() {
        return is_user_logged_in() && (current_user_can('hvac_trainer') || current_user_can('administrator'));
    }
    
    /**
     * Check if welcome guide should be shown
     */
    private function should_show_welcome_guide() {
        if (!$this->is_trainer_logged_in()) {
            return false;
        }
        
        // Check cookie for dismissal
        if (isset($_COOKIE['hvac_welcome_dismissed'])) {
            return false;
        }
        
        // Only show on dashboard page
        return is_page('hvac-dashboard');
    }
    
    /**
     * Render welcome guide modal
     */
    public function render_welcome_guide() {
        if (!$this->should_show_welcome_guide()) {
            return;
        }
        
        $cards = $this->get_welcome_cards();
        ?>
        <div id="hvac-welcome-modal" class="hvac-modal-overlay">
            <div class="hvac-modal-content">
                <div class="hvac-modal-header">
                    <h2>Welcome to Upskill HVAC Training Network!</h2>
                    <button class="hvac-modal-close" aria-label="Close welcome guide">&times;</button>
                </div>
                
                <div class="hvac-welcome-cards">
                    <?php foreach ($cards as $index => $card): ?>
                        <div class="hvac-welcome-card <?php echo $index === 0 ? 'active' : 'hidden'; ?>" data-card="<?php echo $index; ?>">
                            <div class="hvac-card-icon">
                                <i class="<?php echo esc_attr($card['icon']); ?>"></i>
                            </div>
                            <div class="hvac-card-content">
                                <h3><?php echo esc_html($card['title']); ?></h3>
                                <p><?php echo esc_html($card['description']); ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="hvac-modal-navigation">
                    <button id="hvac-prev-card" class="hvac-nav-btn" disabled>Previous</button>
                    <div class="hvac-card-indicators">
                        <?php for ($i = 0; $i < count($cards); $i++): ?>
                            <span class="hvac-indicator <?php echo $i === 0 ? 'active' : ''; ?>" data-card="<?php echo $i; ?>"></span>
                        <?php endfor; ?>
                    </div>
                    <button id="hvac-next-card" class="hvac-nav-btn">Next</button>
                </div>
                
                <div class="hvac-modal-footer">
                    <label class="hvac-dismiss-checkbox">
                        <input type="checkbox" id="hvac-dont-show-again"> Don't show this again
                    </label>
                    <button id="hvac-get-started" class="hvac-primary-btn">Get Started</button>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Get welcome guide cards data
     */
    private function get_welcome_cards() {
        return array(
            array(
                'icon' => 'fas fa-chalkboard-teacher',
                'title' => 'Welcome to Your Training Hub',
                'description' => 'As a verified HVAC trainer, you have access to powerful tools for managing your training business. Your dashboard shows real-time stats, upcoming events, and revenue tracking.'
            ),
            array(
                'icon' => 'fas fa-calendar-plus',
                'title' => 'Create Events in Minutes',
                'description' => 'Click "Create Event" to set up new trainings. Add details, set pricing, and manage capacity. Your events appear immediately in your dashboard - no WordPress admin needed!'
            ),
            array(
                'icon' => 'fas fa-certificate',
                'title' => 'Professional Certificates Made Easy',
                'description' => 'After your event, generate beautiful certificates with your name, attendee details, and the Upskill HVAC logo. Click "Certificate Issued" to view any certificate instantly.'
            ),
            array(
                'icon' => 'fas fa-users',
                'title' => 'Manage Everything in One Place',
                'description' => 'Email attendees, track registrations, generate reports, and monitor your progress. Use the navigation menu to access all features - tooltips guide you every step of the way.'
            )
        );
    }
    
    /**
     * Handle AJAX request to dismiss welcome guide
     */
    public function handle_welcome_dismissal() {
        if (!wp_verify_nonce($_POST['nonce'], 'hvac_help_nonce')) {
            wp_die('Invalid nonce');
        }
        
        if (!$this->is_trainer_logged_in()) {
            wp_die('Unauthorized');
        }
        
        // Set cookie to expire in 30 days
        setcookie('hvac_welcome_dismissed', '1', time() + (30 * 24 * 60 * 60), COOKIEPATH, COOKIE_DOMAIN);
        
        wp_send_json_success();
    }
    
    /**
     * Render documentation page content
     */
    public function render_documentation_page($atts) {
        if (!$this->is_trainer_logged_in()) {
            return '<p>Please log in to access the documentation.</p>';
        }
        
        ob_start();
        ?>
        <div class="hvac-documentation">
            <div class="hvac-doc-header">
                <h1>Trainer Documentation</h1>
                <p class="hvac-doc-subtitle">Everything you need to know about managing your training events</p>
            </div>
            
            <!-- Navigation removed - now handled by page template -->
            <!-- <div class="hvac-doc-navigation">
                <ul class="hvac-doc-nav">
                    <li><a href="#getting-started" class="hvac-doc-link">Getting Started</a></li>
                    <li><a href="#managing-events" class="hvac-doc-link">Managing Events</a></li>
                    <li><a href="#attendee-management" class="hvac-doc-link">Attendee Management</a></li>
                    <li><a href="#certificates" class="hvac-doc-link">Certificates</a></li>
                    <li><a href="#faq" class="hvac-doc-link">FAQ</a></li>
                </ul>
            </div> -->
            
            <div class="hvac-doc-content">
                <?php echo $this->get_documentation_content(); ?>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Get main documentation content
     */
    private function get_documentation_content() {
        return '
        <section id="getting-started" class="hvac-doc-section">
            <h2><i class="fas fa-play-circle"></i> Getting Started</h2>
            <div class="hvac-doc-intro">
                <p class="hvac-welcome-message">Welcome to Upskill HVAC! You\'re part of our comprehensive training platform designed to help HVAC trainers get discovered, share training events, build professional reputation, and connect with the HVAC community.</p>
            </div>
            <div class="hvac-doc-grid">
                <div class="hvac-doc-card">
                    <h3>1. Your Dashboard is Home Base</h3>
                    <p>Everything starts at your dashboard. See your total events, upcoming trainings, revenue progress, and quick links to all features. Track your performance metrics and manage everything from one place.</p>
                    <a href="' . home_url('/trainer/dashboard/') . '" class="hvac-doc-btn">Go to Dashboard</a>
                </div>
                <div class="hvac-doc-card">
                    <h3>2. Update Your Profile First</h3>
                    <p>Your trainer profile is your professional showcase in our directory. Complete your profile to appear in "Find A Trainer" searches and generate more training leads.</p>
                    <a href="' . home_url('/trainer/profile/') . '" class="hvac-doc-btn">Edit Profile</a>
                </div>
                <div class="hvac-doc-card">
                    <h3>3. Create Your First Event</h3>
                    <p>Ready to host training? Create events with pricing, capacity limits, and venue information. Your events integrate with The Events Calendar for seamless management.</p>
                    <a href="' . home_url('/tribe/events/add/') . '" class="hvac-doc-btn">Create Event</a>
                </div>
            </div>
        </section>
        
        <section id="managing-events" class="hvac-doc-section">
            <h2><i class="fas fa-calendar-alt"></i> Managing Events & Training</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>Integrated Event System</h3>
                    <p>Our platform integrates with The Events Calendar to provide comprehensive event management:</p>
                    <ul>
                        <li><strong>Training Events:</strong> Sessions with pricing, capacity, and location</li>
                        <li><strong>Venues:</strong> Physical or virtual training locations</li>
                        <li><strong>Organizers:</strong> Business entities with logos and contact info</li>
                        <li><strong>Revenue Tracking:</strong> Monitor training income and attendance</li>
                    </ul>
                </div>
                <div class="hvac-feature">
                    <h3>Quick Event Management</h3>
                    <ol>
                        <li><strong>Dashboard Overview:</strong> See all your events at a glance</li>
                        <li><strong>New Event:</strong> Click to create from navigation menu</li>
                        <li><strong>Event Management:</strong> Access manage page for detailed controls</li>
                        <li><strong>Analytics:</strong> View performance metrics and revenue data</li>
                    </ol>
                </div>
                <div class="hvac-feature">
                    <h3>Venues & Organizers</h3>
                    <p>Manage your training infrastructure:</p>
                    <ul>
                        <li><strong>Training Venues:</strong> Add locations where you conduct training</li>
                        <li><strong>Training Organizers:</strong> Set up business entities with branding</li>
                        <li><strong>Auto-Creation:</strong> We\'ve tried to auto-create these for you!</li>
                    </ul>
                </div>
            </div>
        </section>
        
        <section id="profile-directory" class="hvac-doc-section">
            <h2><i class="fas fa-user-circle"></i> Your Professional Profile</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>Directory Listing</h3>
                    <p>Your profile appears in our "Find A Trainer" directory where potential students can discover you:</p>
                    <ul>
                        <li><strong>Map Integration:</strong> Shows your location and service areas</li>
                        <li><strong>Contact Form:</strong> Students can reach out directly</li>
                        <li><strong>QR Code Sharing:</strong> Easy sharing at events and conferences</li>
                        <li><strong>Professional Showcase:</strong> Display credentials and experience</li>
                    </ul>
                </div>
                <div class="hvac-feature">
                    <h3>Training Leads</h3>
                    <p>When potential students find you in the directory, they can submit contact requests that appear in your Training Leads page:</p>
                    <ul>
                        <li><strong>Lead Management:</strong> Track contact requests from potential clients</li>
                        <li><strong>Status Tracking:</strong> Mark leads as read, replied, or archived</li>
                        <li><strong>Direct Contact:</strong> Email and phone information included</li>
                        <li><strong>Message History:</strong> View full inquiry details</li>
                    </ul>
                    <a href="' . home_url('/trainer/profile/training-leads/') . '" class="hvac-doc-btn">View Training Leads</a>
                </div>
                <div class="hvac-feature">
                    <h3>Pro Tip: Share Your Profile</h3>
                    <p>The more you share your profile, the more training leads you can generate! Use social media, business cards, or the built-in QR code feature.</p>
                </div>
            </div>
        </section>
        
        <section id="certificates" class="hvac-doc-section">
            <h2><i class="fas fa-certificate"></i> Certificate Generation</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>Professional Certificates</h3>
                    <p>Generate beautiful completion certificates with the Upskill HVAC logo, your name as instructor, and attendee details. Each certificate has a unique number and can be verified.</p>
                    <ul>
                        <li><strong>Automated Generation:</strong> Create certificates for event attendees</li>
                        <li><strong>Professional Design:</strong> Branded with Upskill HVAC styling</li>
                        <li><strong>Unique Verification:</strong> Each certificate has a verification number</li>
                        <li><strong>Easy Distribution:</strong> Download and share with attendees</li>
                    </ul>
                </div>
                <div class="hvac-feature">
                    <h3>Certificate Workflow</h3>
                    <ol>
                        <li><strong>Navigate to Certificates:</strong> Use the navigation menu</li>
                        <li><strong>Generate New Certificates:</strong> Select event and attendees</li>
                        <li><strong>View Certificate Reports:</strong> Track all issued certificates</li>
                        <li><strong>Download & Share:</strong> Distribute to your trainees</li>
                    </ol>
                    <div class="hvac-feature-links">
                        <a href="' . home_url('/trainer/generate-certificates/') . '" class="hvac-doc-btn">Generate Certificates</a>
                        <a href="' . home_url('/trainer/certificate-reports/') . '" class="hvac-doc-btn hvac-doc-btn-secondary">View Reports</a>
                    </div>
                </div>
            </div>
        </section>
        
        <section id="navigation" class="hvac-doc-section">
            <h2><i class="fas fa-compass"></i> Navigation Guide</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>Updated Navigation Menu</h3>
                    <p>Our streamlined navigation makes it easy to access all platform features:</p>
                    <ul>
                        <li><strong>Events:</strong> Dashboard and create new events</li>
                        <li><strong>Certificates:</strong> Generate and view certificate reports</li>
                        <li><strong>Profile:</strong> Your professional profile, training leads, venues, and organizers</li>
                        <li><strong>Help (?):</strong> Access this documentation anytime</li>
                    </ul>
                </div>
                <div class="hvac-feature">
                    <h3>Quick Access Features</h3>
                    <ul>
                        <li><strong>Dashboard:</strong> Your training business overview</li>
                        <li><strong>Training Leads:</strong> Manage contact requests from potential clients</li>
                        <li><strong>Profile Management:</strong> Update your professional information</li>
                        <li><strong>Venue & Organizer Setup:</strong> Configure your training infrastructure</li>
                    </ul>
                </div>
            </div>
        </section>
        
        <section id="faq" class="hvac-doc-section">
            <h2><i class="fas fa-question-circle"></i> Frequently Asked Questions</h2>
            <div class="hvac-faq-list">
                <div class="hvac-faq-item">
                    <h3>Where do I start?</h3>
                    <p>Start by updating your trainer profile to appear in our directory, then create your first training event. Your dashboard provides an overview of everything.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>How do I get more training leads?</h3>
                    <p>Complete your profile and share it! The more visible you are in our "Find A Trainer" directory, the more potential students will contact you through the Training Leads system.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>What\'s the difference between venues and organizers?</h3>
                    <p>Venues are physical or virtual locations where you conduct training. Organizers are business entities (like your company) that host the training and can have logos and branding.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>How do certificates work?</h3>
                    <p>After your training event, you can generate professional certificates for attendees. Each certificate is uniquely numbered and includes your name as the instructor and the Upskill HVAC branding.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>Can I track my training revenue?</h3>
                    <p>Yes! Your dashboard shows revenue tracking and analytics for all your training events. You can monitor your training business performance over time.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>What if I need help?</h3>
                    <p>Click the "?" icon in the navigation menu to return to this documentation anytime. You can also reach out to our support team for additional assistance.</p>
                </div>
            </div>
        </section>
        
        <section id="getting-help" class="hvac-doc-section">
            <h2><i class="fas fa-life-ring"></i> Getting Support</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>Quick Start Checklist</h3>
                    <ol>
                        <li><strong>✓ Update Your Profile</strong> - Make sure your information is complete</li>
                        <li><strong>✓ Add Training Venues</strong> - Set up your training locations</li>
                        <li><strong>✓ Create Training Organizer</strong> - Add your business entity</li>
                        <li><strong>✓ Create First Event</strong> - Host your first training session</li>
                        <li><strong>✓ Share Your Profile</strong> - Start generating training leads</li>
                    </ol>
                </div>
                <div class="hvac-feature">
                    <h3>Remember</h3>
                    <p>We\'ve tried to auto-create venues and organizers for you based on your profile information, but you may need to make corrections or updates to ensure everything is accurate.</p>
                    <p><strong>Pro tip:</strong> The more complete your profile, the more professional you appear to potential students and the more training leads you\'ll generate!</p>
                </div>
            </div>
        </section>';
    }
    
    /**
     * Add tooltip data attribute to elements
     */
    public static function add_tooltip($content, $tooltip_text, $position = 'top') {
        return sprintf(
            '<span class="hvac-tooltip-wrapper" data-tooltip="%s" data-position="%s">%s</span>',
            esc_attr($tooltip_text),
            esc_attr($position),
            $content
        );
    }
    
    /**
     * Get common tooltip texts for consistent help messaging
     */
    public static function get_tooltip_text($key) {
        $tooltips = array(
            // Dashboard tooltips
            'total_events' => 'All events you\'ve created, including past and future trainings',
            'upcoming_events' => 'Events scheduled for the future that attendees can register for',
            'total_revenue' => 'Your total earnings from all ticket sales (after Stripe fees)',
            'revenue_target' => 'Annual revenue goal to maintain your trainer status',
            
            // Event management tooltips
            'create_event' => 'Start here to add a new training event',
            'event_status' => 'Draft = not published yet, Published = live for registration',
            'edit_event' => 'Click to modify event details like date, price, or description',
            'view_attendees' => 'See who registered and their check-in status',
            
            // Certificate tooltips
            'generate_certificates' => 'Create professional completion certificates for your attendees',
            'certificate_issued' => 'Click to view or download the certificate PDF',
            'select_attendees' => 'Choose who receives certificates - typically checked-in attendees',
            'bulk_generate' => 'Generate multiple certificates at once to save time',
            
            // Profile tooltips
            'trainer_profile' => 'Your public profile that attendees see when browsing events',
            'credentials' => 'Add certifications and experience to build trust',
            'business_info' => 'Company name and contact details for professional appearance',
            
            // Email tooltips
            'email_attendees' => 'Send updates or reminders to your event registrants',
            'cc_recipients' => 'Add email addresses separated by commas to receive copies',
            'email_preview' => 'Preview how your email will look before sending'
        );
        
        return isset($tooltips[$key]) ? $tooltips[$key] : '';
    }
}

// Initialize the help system
HVAC_Help_System::instance();