<?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 using direct database query (bypassing TEC interference)
global $wpdb;

// Build author filter
$author_filter = current_user_can('edit_others_posts') ? '' : 'AND post_author = ' . intval($current_user_id);

// Get events directly from database
$events = $wpdb->get_results(
    "SELECT ID, post_title, post_date 
     FROM {$wpdb->posts} 
     WHERE post_type = 'tribe_events' 
     AND post_status = 'publish' 
     {$author_filter}
     ORDER BY post_date DESC"
);

// Get attendees for the selected event using direct database query
$attendees = array();
if ($event_id > 0) {
    // Use direct database query to get attendees (both TEC and TPP formats)
    $tec_attendees = $wpdb->get_results($wpdb->prepare(
        "SELECT 
            p.ID as attendee_id,
            p.post_parent as event_id,
            COALESCE(tec_full_name.meta_value, tpp_full_name.meta_value, tickets_full_name.meta_value, 'Unknown Attendee') as holder_name,
            COALESCE(tec_email.meta_value, tpp_email.meta_value, tickets_email.meta_value, tpp_attendee_email.meta_value, 'no-email@example.com') as holder_email,
            COALESCE(checked_in.meta_value, '0') as check_in
        FROM {$wpdb->posts} p
        LEFT JOIN {$wpdb->postmeta} tec_full_name ON p.ID = tec_full_name.post_id AND tec_full_name.meta_key = '_tec_tickets_commerce_full_name'
        LEFT JOIN {$wpdb->postmeta} tpp_full_name ON p.ID = tpp_full_name.post_id AND tpp_full_name.meta_key = '_tribe_tpp_full_name'
        LEFT JOIN {$wpdb->postmeta} tickets_full_name ON p.ID = tickets_full_name.post_id AND tickets_full_name.meta_key = '_tribe_tickets_full_name'
        LEFT JOIN {$wpdb->postmeta} tec_email ON p.ID = tec_email.post_id AND tec_email.meta_key = '_tec_tickets_commerce_email'
        LEFT JOIN {$wpdb->postmeta} tpp_email ON p.ID = tpp_email.post_id AND tpp_email.meta_key = '_tribe_tpp_email'
        LEFT JOIN {$wpdb->postmeta} tickets_email ON p.ID = tickets_email.post_id AND tickets_email.meta_key = '_tribe_tickets_email'
        LEFT JOIN {$wpdb->postmeta} tpp_attendee_email ON p.ID = tpp_attendee_email.post_id AND tpp_attendee_email.meta_key = '_tribe_tpp_attendee_email'
        LEFT JOIN {$wpdb->postmeta} checked_in ON p.ID = checked_in.post_id AND checked_in.meta_key = '_tribe_tickets_attendee_checked_in'
        WHERE p.post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees') 
        AND p.post_parent = %d
        ORDER BY p.ID ASC",
        $event_id
    ));
    
    // Convert to format expected by template
    foreach ($tec_attendees as $attendee) {
        $attendees[] = array(
            'attendee_id' => $attendee->attendee_id,
            'event_id' => $attendee->event_id,
            'holder_name' => $attendee->holder_name,
            'holder_email' => $attendee->holder_email,
            'check_in' => intval($attendee->check_in)
        );
    }
}

// Get header and footer
get_header();

// Ensure certificate CSS is loaded
wp_enqueue_style(
    'hvac-certificates-style',
    HVAC_CE_PLUGIN_URL . 'assets/css/hvac-certificates.css',
    ['hvac-common-style'],
    HVAC_CE_VERSION
);

// Ensure dashboard CSS is loaded for proper styling
wp_enqueue_style(
    'hvac-dashboard-style',
    HVAC_CE_PLUGIN_URL . 'assets/css/hvac-dashboard.css',
    ['hvac-common-style'],
    HVAC_CE_VERSION
);
?>

<div class="hvac-container">
    <div class="hvac-content-wrapper">
        <!-- Navigation Header -->
        <div class="hvac-dashboard-header">
            <h1 class="entry-title">Generate Certificates</h1>
            <div class="hvac-dashboard-nav">
                <a href="<?php echo esc_url( home_url( '/hvac-dashboard/' ) ); ?>" class="ast-button ast-button-secondary">Dashboard</a>
                <a href="<?php echo esc_url( home_url( '/certificate-reports/' ) ); ?>" class="ast-button ast-button-secondary">Certificate Reports</a>
                <a href="<?php echo esc_url( home_url( '/manage-event/' ) ); ?>" class="ast-button ast-button-primary">Create Event</a>
            </div>
        </div>
        
        <div class="hvac-page-header">
            <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 : ?>
                <div 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(date('M j, Y', strtotime($event->post_date))); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Step 2: Select Attendees (AJAX loaded) -->
        <div class="hvac-section hvac-step-section" id="step-select-attendees" <?php echo $event_id > 0 ? '' : 'style="display: none;"'; ?>>
            <h2>Step 2: Select Attendees</h2>
            
            <!-- Loading indicator -->
            <div id="attendees-loading" style="display: none;">
                <p>Loading attendees...</p>
            </div>
            
            <!-- Attendees content -->
            <div id="attendees-content">
                <form id="generate-certificates-form" class="hvac-form" method="post">
                    <?php wp_nonce_field('hvac_generate_certificates', 'hvac_certificate_nonce'); ?>
                    <input type="hidden" name="event_id" id="selected_event_id" value="<?php echo esc_attr($event_id); ?>">
                    <input type="hidden" name="generate_certificates" value="1">
                    
                    <div class="hvac-form-group">
                        <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>
                        
                        <!-- Attendees table will be loaded here via AJAX -->
                        <div id="attendees-table-container">
                            <?php if ($event_id > 0 && !empty($attendees)) : ?>
                                <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-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) : 
                                                $checked_in_class = $attendee['check_in'] ? 'hvac-checked-in' : '';
                                                $status_class = $attendee['check_in'] ? 'hvac-status-checked-in' : 'hvac-status-not-checked-in';
                                                $status_text = $attendee['check_in'] ? 'Checked In' : 'Not Checked In';
                                                
                                                // Check if certificate already exists
                                                $has_certificate = $certificate_manager->certificate_exists($event_id, $attendee['attendee_id']);
                                                $certificate_status = $has_certificate ? 'Certificate Issued' : 'No Certificate';
                                                $has_cert_class = $has_certificate ? 'hvac-has-certificate' : '';
                                            ?>
                                                <tr class="<?php echo esc_attr($has_cert_class . ' ' . $checked_in_class); ?>">
                                                    <td>
                                                        <?php if (!$has_certificate) : ?>
                                                            <input type="checkbox" name="attendee_ids[]" value="<?php echo esc_attr($attendee['attendee_id']); ?>" class="attendee-checkbox" <?php echo $attendee['check_in'] ? 'checked' : ''; ?>>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo esc_html($attendee['holder_name']); ?></td>
                                                    <td><?php echo esc_html($attendee['holder_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>
                            <?php elseif ($event_id > 0 && empty($attendees)) : ?>
                                <p class="hvac-empty-state">This event has no attendees.</p>
                            <?php endif; ?>
                        </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>
                            <p class="hvac-certificate-preview-note">A professional certificate will be generated based on the default template.</p>
                        </div>
                    </div>
                    
                    <div class="hvac-form-actions">
                        <button type="submit" name="generate_certificates" class="hvac-button hvac-primary">Generate Certificates</button>
                    </div>
                </form>
            </div>
        </div>

        <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>
jQuery(document).ready(function($) {
    // Handle event selection change
    $('#event_id').on('change', function() {
        var eventId = $(this).val();
        var $step2 = $('#step-select-attendees');
        var $loading = $('#attendees-loading');
        var $content = $('#attendees-content');
        var $container = $('#attendees-table-container');
        
        if (!eventId) {
            $step2.hide();
            return;
        }
        
        // Show step 2 and loading
        $step2.show();
        $loading.show();
        $content.hide();
        
        // Get attendees for selected event
        <?php 
        // Get existing attendees if event is already selected
        if ($event_id > 0 && !empty($attendees)) {
            echo "// Event already selected, use existing attendees\n";
            echo "var attendees = " . json_encode($attendees) . ";\n";
            echo "renderAttendees(attendees);\n";
            echo "$loading.hide();\n";
            echo "$content.show();\n";
        } else {
            echo "// No pre-selected event, clear container\n";
            echo "\$container.html('<p>Loading attendees...</p>');\n";
        }
        ?>
        
        // Update hidden field
        $('#selected_event_id').val(eventId);
        
        // Reload page with selected event
        if (eventId && eventId !== '<?php echo $event_id; ?>') {
            window.location.href = window.location.pathname + '?event_id=' + eventId;
        }
    });
    
    function renderAttendees(attendees) {
        var $container = $('#attendees-table-container');
        
        if (attendees.length === 0) {
            $container.html('<p class="hvac-empty-state">This event has no attendees.</p>');
            return;
        }
        
        var tableHtml = '<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-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>';
        
        attendees.forEach(function(attendee) {
            var checkedInClass = attendee.check_in ? 'hvac-checked-in' : '';
            var statusClass = attendee.check_in ? 'hvac-status-checked-in' : 'hvac-status-not-checked-in';
            var statusText = attendee.check_in ? 'Checked In' : 'Not Checked In';
            var hasCert = false; // TODO: Check if certificate exists
            var certStatus = hasCert ? 'Certificate Issued' : 'No Certificate';
            
            tableHtml += '<tr class="' + checkedInClass + '">' +
                '<td>' + 
                (!hasCert ? '<input type="checkbox" name="attendee_ids[]" value="' + attendee.attendee_id + '" class="attendee-checkbox">' : '') +
                '</td>' +
                '<td>' + attendee.holder_name + '</td>' +
                '<td>' + attendee.holder_email + '</td>' +
                '<td><span class="' + statusClass + '">' + statusText + '</span></td>' +
                '<td>' + certStatus + '</td>' +
                '</tr>';
        });
        
        tableHtml += '</tbody></table></div></div>';
        $container.html(tableHtml);
    }
    
    // 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 
// Ensure the AJAX handler script is loaded with proper localization
wp_enqueue_script('hvac-certificate-actions-js');

get_footer();

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