<?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_CE_PLUGIN_URL . 'assets/css/hvac-help-system.css',
            array('hvac-common-style', 'font-awesome'),
            HVAC_CE_VERSION
        );
        
        wp_enqueue_script(
            'hvac-help-system',
            HVAC_CE_PLUGIN_URL . 'assets/js/hvac-help-system.js',
            array('jquery'),
            HVAC_CE_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>
            
            <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-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. No need to access WordPress admin!</p>
                    <a href="/hvac-dashboard" class="hvac-doc-btn">Go to Dashboard</a>
                </div>
                <div class="hvac-doc-card">
                    <h3>2. Create Your First Event</h3>
                    <p>Click "Create Event" from any page. Fill in the simple form - event title, description, date, and pricing. Your event saves as a draft automatically.</p>
                    <a href="/manage-event" class="hvac-doc-btn">Create Event</a>
                </div>
                <div class="hvac-doc-card">
                    <h3>3. Complete Your Profile</h3>
                    <p>Add your credentials and business info to build trust with trainees. A complete profile helps your events get found and booked faster.</p>
                    <a href="/trainer-profile" class="hvac-doc-btn">Edit Profile</a>
                </div>
            </div>
        </section>
        
        <section id="managing-events" class="hvac-doc-section">
            <h2><i class="fas fa-calendar-alt"></i> Managing Events</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>Creating Events is Simple</h3>
                    <ol>
                        <li><strong>Click "Create Event"</strong> from your dashboard or navigation menu</li>
                        <li><strong>Fill the form:</strong> Title, description, date/time, venue, and pricing</li>
                        <li><strong>Save as Draft:</strong> Review and edit anytime before publishing</li>
                        <li><strong>Publish:</strong> Your event goes live immediately</li>
                    </ol>
                </div>
                <div class="hvac-feature">
                    <h3>What You Can Do</h3>
                    <ul>
                        <li><strong>Edit Events:</strong> Click any event title to modify details</li>
                        <li><strong>Set Capacity:</strong> Control how many can register</li>
                        <li><strong>Track Sales:</strong> See registrations in real-time</li>
                        <li><strong>Quick Actions:</strong> View, edit, or check attendees with one click</li>
                    </ul>
                </div>
                <div class="hvac-feature">
                    <h3>Event Summary Page</h3>
                    <p>Click "View Summary" on any event to see everything at a glance: attendee list, revenue, check-in status, and quick links to email attendees or generate certificates.</p>
                </div>
            </div>
        </section>
        
        <section id="attendee-management" class="hvac-doc-section">
            <h2><i class="fas fa-users"></i> Attendee Management</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>See Who\'s Coming</h3>
                    <p>Your dashboard shows registration counts. Click "View Attendees" on any event to see the full list with names, emails, and check-in status.</p>
                </div>
                <div class="hvac-feature">
                    <h3>Easy Email Communication</h3>
                    <p>Click "Email Attendees" to send updates. Select all attendees or just those who are checked in. Add CC recipients and your message is sent instantly.</p>
                </div>
                <div class="hvac-feature">
                    <h3>Quick Check-In</h3>
                    <p>During your event, use the attendee list to check people in. This helps track completion for certificates and keeps accurate records.</p>
                </div>
            </div>
        </section>
        
        <section id="certificates" class="hvac-doc-section">
            <h2><i class="fas fa-certificate"></i> Professional Certificates - NEW!</h2>
            <div class="hvac-feature-list">
                <div class="hvac-feature">
                    <h3>Beautiful Certificates Automatically</h3>
                    <p>Generate professional certificates with the Upskill HVAC logo, your name as instructor, and attendee details. Each certificate has a unique number and can be verified.</p>
                </div>
                <div class="hvac-feature">
                    <h3>Simple Generation Process</h3>
                    <ul>
                        <li><strong>Go to "Generate Certificates"</strong> from the menu</li>
                        <li><strong>Select your event</strong> from the dropdown</li>
                        <li><strong>Choose attendees</strong> (or select all)</li>
                        <li><strong>Click Generate</strong> - certificates are created instantly!</li>
                        <li><strong>Click "Certificate Issued"</strong> text to view any certificate</li>
                    </ul>
                </div>
                <div class="hvac-feature">
                    <h3>Track Everything</h3>
                    <p>The Certificate Reports page shows all certificates you\'ve issued. Filter by event, search by name, and download certificates anytime.</p>
                </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 at your dashboard! It shows everything you need. Click "Create Event" to add your first training, or "My Events" to see what you\'ve already created.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>How do I edit an event?</h3>
                    <p>From your dashboard, find the event and click its title. You\'ll go straight to the edit page. Make changes and click "Update Event" to save.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>How do certificates work?</h3>
                    <p>After your event, go to "Generate Certificates" and select your event. Choose which attendees get certificates (usually those who were checked in). Click generate and they\'re ready! Each certificate shows your name, the attendee\'s name, and has the Upskill HVAC logo.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>Can attendees view their certificates?</h3>
                    <p>Yes! On the Generate Certificates page, you\'ll see "Certificate Issued" under each attendee who has one. Click this text to open their certificate - you can share this link with them.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>What\'s the revenue target on my dashboard?</h3>
                    <p>This is your annual goal to maintain your trainer status. The progress bar shows how close you are. Keep creating quality events and you\'ll reach it!</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>How do I email my attendees?</h3>
                    <p>Click "Email Attendees" from the menu or from any event summary. Select who to email, write your message, and send. You can CC yourself or others too.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>Do I need to use WordPress admin?</h3>
                    <p>No! Everything you need is in your trainer dashboard and the connected pages. The system is designed so you never need to access the WordPress backend.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>How do payments work?</h3>
                    <p>Attendees pay through Stripe when they register. You receive 100% of ticket sales (minus Stripe\'s standard 2.9% + 30¢ fee) directly to your connected account.</p>
                </div>
                <div class="hvac-faq-item">
                    <h3>Need more help?</h3>
                    <p>Look for the (?) tooltips throughout the site - hover over them for quick help. This documentation is always available from the Help link. For urgent issues, contact support.</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();