<?php
/**
 * Template for the Generate Certificates page
 *
 * @package HVAC_Community_Events
 * @subpackage Templates/Certificates
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Enable error reporting for debugging
if (WP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
}

// Get current user ID
$current_user_id = get_current_user_id();

// Error handling wrapper for the whole template
try {
    // Get event ID from URL if available
    $event_id = isset($_GET['event_id']) ? absint($_GET['event_id']) : 0;

    // Check if certificate classes are loaded
    if (!class_exists('HVAC_Certificate_Manager')) {
        require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-manager.php';
    }
    
    if (!class_exists('HVAC_Certificate_Generator')) {
        require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-generator.php';
    }
    
    if (!class_exists('HVAC_Certificate_Template')) {
        require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-template.php';
    }
    
    // Get certificate manager instance
    $certificate_manager = HVAC_Certificate_Manager::instance();

    // Get certificate generator instance
    $certificate_generator = HVAC_Certificate_Generator::instance();

    // Get certificate template instance
    $certificate_template = HVAC_Certificate_Template::instance();
    
    // Check if certificate tables exist
    if (!class_exists('HVAC_Certificate_Installer')) {
        require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-installer.php';
    }
    $installer = HVAC_Certificate_Installer::instance();
    $tables_exist = $installer->check_tables();
    
    if (!$tables_exist) {
        echo '<div class="hvac-error">Certificate database tables are not properly set up. Please contact the administrator.</div>';
        return;
    }

// Handle certificate generation form submission
$generation_results = null;
$errors = array();
$success_message = '';

if (isset($_POST['generate_certificates']) && isset($_POST['event_id'])) {
    // Verify nonce
    if (!isset($_POST['hvac_certificate_nonce']) || !wp_verify_nonce($_POST['hvac_certificate_nonce'], 'hvac_generate_certificates')) {
        $errors[] = 'Security verification failed. Please try again.';
    } else {
        $submitted_event_id = absint($_POST['event_id']);
        $selected_attendees = isset($_POST['attendee_ids']) && is_array($_POST['attendee_ids']) ? array_map('absint', $_POST['attendee_ids']) : array();
        $checked_in_only = isset($_POST['checked_in_only']) && $_POST['checked_in_only'] === 'yes';
        
        // Check if any attendees were selected
        if (empty($selected_attendees)) {
            $errors[] = 'Please select at least one attendee to generate certificates for.';
        } else {
            // Generate certificates in batch
            $generation_results = $certificate_generator->generate_certificates_batch(
                $submitted_event_id,
                $selected_attendees,
                array(), // Custom data (none for now)
                $current_user_id, // Generated by current user
                $checked_in_only // Only for checked-in attendees if selected
            );
            
            // Set success message if at least one certificate was generated
            if ($generation_results['success'] > 0) {
                $message_parts = array(
                    sprintf('Successfully generated %d certificate(s).', $generation_results['success'])
                );
                
                if ($generation_results['duplicate'] > 0) {
                    $message_parts[] = sprintf('%d duplicate(s) skipped.', $generation_results['duplicate']);
                }
                
                if ($generation_results['not_checked_in'] > 0) {
                    $message_parts[] = sprintf('%d attendee(s) not checked in.', $generation_results['not_checked_in']);
                }
                
                if ($generation_results['error'] > 0) {
                    $message_parts[] = sprintf('%d error(s).', $generation_results['error']);
                }
                
                $success_message = implode(' ', $message_parts);
            } elseif ($generation_results['duplicate'] > 0 && $generation_results['error'] === 0 && $generation_results['not_checked_in'] === 0) {
                $success_message = sprintf(
                    'No new certificates generated. %d certificate(s) already exist for the selected attendees.',
                    $generation_results['duplicate']
                );
            } elseif ($generation_results['not_checked_in'] > 0 && $checked_in_only) {
                $success_message = sprintf(
                    'No new certificates generated. %d selected attendee(s) have not been checked in.',
                    $generation_results['not_checked_in']
                );
            } else {
                $errors[] = 'Failed to generate certificates. Please try again.';
            }
        }
    }
}

// Get user's events for the event selection step
$args = array(
    'post_type' => Tribe__Events__Main::POSTTYPE,
    'posts_per_page' => -1,
    'post_status' => 'publish',
    'author' => $current_user_id,
    'orderby' => 'meta_value',
    'meta_key' => '_EventStartDate',
    'order' => 'DESC',
);

// Allow admins to see all events
if (current_user_can('edit_others_posts')) {
    unset($args['author']);
}

$events = get_posts($args);

// Get attendees for the selected event
$attendees = array();
if ($event_id > 0) {
    // Get all attendees for the event
    $attendees = tribe_tickets_get_attendees($event_id);
}

// Get header and footer
get_header();
?>

<div class="hvac-container">
    <div class="hvac-content-wrapper">
        <div class="hvac-page-header">
            <h1>Generate Certificates</h1>
            <p class="hvac-page-description">Create and manage certificates for your event attendees.</p>
        </div>

        <?php if (!empty($errors)) : ?>
            <div class="hvac-errors">
                <?php foreach ($errors as $error) : ?>
                    <p class="hvac-error"><?php echo esc_html($error); ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($success_message)) : ?>
            <div class="hvac-success-message">
                <p><?php echo esc_html($success_message); ?></p>
                <p><a href="<?php echo esc_url(get_permalink(get_page_by_path('certificate-reports'))); ?>" class="hvac-button hvac-primary">View All Certificates</a></p>
            </div>
        <?php endif; ?>

        <!-- Step 1: Select Event -->
        <div class="hvac-section hvac-step-section" id="step-select-event">
            <h2>Step 1: Select Event</h2>
            
            <?php if (empty($events)) : ?>
                <p class="hvac-empty-state">You don't have any events. <a href="<?php echo esc_url(get_permalink(get_page_by_path('manage-event'))); ?>">Create an event</a> first.</p>
            <?php else : ?>
                <form method="get" class="hvac-form">
                    <div class="hvac-form-group">
                        <label for="event_id">Select an event:</label>
                        <select name="event_id" id="event_id" class="hvac-select" required>
                            <option value="">-- Select Event --</option>
                            <?php foreach ($events as $event) : ?>
                                <option value="<?php echo esc_attr($event->ID); ?>" <?php selected($event_id, $event->ID); ?>>
                                    <?php echo esc_html($event->post_title); ?> - 
                                    <?php echo esc_html(tribe_get_start_date($event->ID, false, get_option('date_format'))); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="hvac-form-group">
                        <button type="submit" class="hvac-button hvac-primary">Select Event</button>
                    </div>
                </form>
            <?php endif; ?>
        </div>

        <?php if ($event_id > 0) : ?>
            <!-- Step 2: Select Attendees -->
            <div class="hvac-section hvac-step-section" id="step-select-attendees">
                <h2>Step 2: Select Attendees</h2>
                
                <?php if (empty($attendees)) : ?>
                    <p class="hvac-empty-state">This event has no attendees. Sell tickets or add attendees to your event first.</p>
                <?php else : ?>
                    <form method="post" class="hvac-form">
                        <?php wp_nonce_field('hvac_generate_certificates', 'hvac_certificate_nonce'); ?>
                        <input type="hidden" name="event_id" value="<?php echo esc_attr($event_id); ?>">
                        
                        <div class="hvac-form-group">
                            <div class="hvac-table-actions">
                                <button type="button" class="hvac-button hvac-secondary" id="select-all-attendees">Select All</button>
                                <button type="button" class="hvac-button hvac-secondary" id="select-checked-in">Select Checked-In Only</button>
                                <button type="button" class="hvac-button hvac-secondary" id="deselect-all-attendees">Deselect All</button>
                            </div>
                            
                            <div class="hvac-form-options">
                                <label class="hvac-checkbox-label">
                                    <input type="checkbox" name="checked_in_only" value="yes" id="checked-in-only-checkbox">
                                    Generate certificates only for checked-in attendees
                                </label>
                                <p class="hvac-form-help">Check this option to only generate certificates for attendees who have been marked as checked in to the event.</p>
                            </div>

                            <div class="hvac-attendees-table-wrapper">
                                <table class="hvac-attendees-table">
                                    <thead>
                                        <tr>
                                            <th class="hvac-checkbox-column">
                                                <input type="checkbox" id="select-all-checkbox">
                                            </th>
                                            <th>Attendee</th>
                                            <th>Email</th>
                                            <th>Status</th>
                                            <th>Certificate</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($attendees as $attendee) : 
                                            // Get attendee info
                                            $attendee_id = $attendee['attendee_id'];
                                            $attendee_name = isset($attendee['holder_name']) ? $attendee['holder_name'] : '';
                                            $attendee_email = isset($attendee['holder_email']) ? $attendee['holder_email'] : '';
                                            $checked_in = isset($attendee['check_in']) && $attendee['check_in'] === 1;
                                            
                                            // Check if certificate already exists
                                            $has_certificate = $certificate_manager->certificate_exists($event_id, $attendee_id);
                                            $certificate_status = $has_certificate ? 'Certificate Issued' : 'No Certificate';
                                            
                                            // Status class
                                            $status_class = $checked_in ? 'hvac-status-checked-in' : 'hvac-status-not-checked-in';
                                            $status_text = $checked_in ? 'Checked In' : 'Not Checked In';
                                        ?>
                                            <tr class="<?php echo $has_certificate ? 'hvac-has-certificate' : ''; ?> <?php echo $checked_in ? 'hvac-checked-in' : ''; ?>">
                                                <td>
                                                    <?php if (!$has_certificate) : ?>
                                                        <input type="checkbox" name="attendee_ids[]" value="<?php echo esc_attr($attendee_id); ?>" class="attendee-checkbox" <?php checked($checked_in); ?>>
                                                    <?php endif; ?>
                                                </td>
                                                <td><?php echo esc_html($attendee_name); ?></td>
                                                <td><?php echo esc_html($attendee_email); ?></td>
                                                <td><span class="<?php echo esc_attr($status_class); ?>"><?php echo esc_html($status_text); ?></span></td>
                                                <td><?php echo esc_html($certificate_status); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <div class="hvac-form-group">
                            <div class="hvac-certificate-preview">
                                <h3>Certificate Preview</h3>
                                <p>Certificates will be generated based on your template settings.</p>
                                
                                <?php
                                // Get template info for preview
                                $templates = $certificate_template->get_templates();
                                $default_template = 'default';
                                
                                if (!empty($templates)) {
                                    echo '<p>Template: ' . esc_html(ucfirst($default_template)) . '</p>';
                                    echo '<p class="hvac-certificate-preview-note">A professional certificate will be generated based on the default template.</p>';
                                } else {
                                    echo '<p>Preview not available</p>';
                                }
                                ?>
                                
                            </div>
                        </div>
                        
                        <div class="hvac-form-actions">
                            <a href="<?php echo esc_url(remove_query_arg('event_id')); ?>" class="hvac-button hvac-secondary">Back to Event Selection</a>
                            <button type="submit" name="generate_certificates" class="hvac-button hvac-primary">Generate Certificates</button>
                        </div>
                    </form>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <div class="hvac-section hvac-info-section">
            <h2>Certificate Management Tools</h2>
            <p>After generating certificates, you can:</p>
            <ul>
                <li>View all certificates on the <a href="<?php echo esc_url(get_permalink(get_page_by_path('certificate-reports'))); ?>">Certificate Reports</a> page</li>
                <li>Email certificates to attendees directly from the reports page</li>
                <li>Revoke certificates that were issued incorrectly</li>
                <li>Download certificates in PDF format for printing or distribution</li>
            </ul>
        </div>
    </div>
</div>

<script>
    // Client-side JavaScript for the Generate Certificates page
    document.addEventListener('DOMContentLoaded', function() {
        // Select all checkbox functionality
        var selectAllCheckbox = document.getElementById('select-all-checkbox');
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', function() {
                var checkboxes = document.querySelectorAll('.attendee-checkbox');
                checkboxes.forEach(function(checkbox) {
                    checkbox.checked = selectAllCheckbox.checked;
                });
            });
        }
        
        // Select All button
        var selectAllButton = document.getElementById('select-all-attendees');
        if (selectAllButton) {
            selectAllButton.addEventListener('click', function(e) {
                e.preventDefault();
                var checkboxes = document.querySelectorAll('.attendee-checkbox');
                checkboxes.forEach(function(checkbox) {
                    checkbox.checked = true;
                });
                if (selectAllCheckbox) selectAllCheckbox.checked = true;
            });
        }
        
        // Deselect All button
        var deselectAllButton = document.getElementById('deselect-all-attendees');
        if (deselectAllButton) {
            deselectAllButton.addEventListener('click', function(e) {
                e.preventDefault();
                var checkboxes = document.querySelectorAll('.attendee-checkbox');
                checkboxes.forEach(function(checkbox) {
                    checkbox.checked = false;
                });
                if (selectAllCheckbox) selectAllCheckbox.checked = false;
            });
        }
        
        // Select Checked-In Only button
        var selectCheckedInButton = document.getElementById('select-checked-in');
        if (selectCheckedInButton) {
            selectCheckedInButton.addEventListener('click', function(e) {
                e.preventDefault();
                var checkboxes = document.querySelectorAll('.attendee-checkbox');
                checkboxes.forEach(function(checkbox) {
                    var row = checkbox.closest('tr');
                    checkbox.checked = row.classList.contains('hvac-checked-in');
                });
                if (selectAllCheckbox) selectAllCheckbox.checked = false;
            });
        }
        
        // Checked-in only checkbox affects Select All behavior
        var checkedInOnlyCheckbox = document.getElementById('checked-in-only-checkbox');
        if (checkedInOnlyCheckbox) {
            // Update existing behavior when this checkbox changes
            checkedInOnlyCheckbox.addEventListener('change', function() {
                // If checked, select all checked-in attendees
                if (checkedInOnlyCheckbox.checked) {
                    // Automatically select checked-in attendees
                    document.getElementById('select-checked-in').click();
                }
            });
            
            // Warn user when trying to select non-checked-in attendees
            document.querySelectorAll('.attendee-checkbox').forEach(function(checkbox) {
                checkbox.addEventListener('change', function() {
                    if (checkedInOnlyCheckbox.checked && this.checked) {
                        var row = this.closest('tr');
                        if (!row.classList.contains('hvac-checked-in')) {
                            alert('Warning: This attendee is not checked in. With "Generate certificates only for checked-in attendees" enabled, a certificate will not be generated for this attendee.');
                        }
                    }
                });
            });
        }
    });
</script>

<?php 
get_footer();

// End try-catch block
} catch (Exception $e) {
    echo '<div class="hvac-error">Error in certificate generation: ' . esc_html($e->getMessage()) . '</div>';
}
?>