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

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

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

// Error handling wrapper for the whole template
try {
    // Get certificate manager instance
    if (!class_exists('HVAC_Certificate_Manager')) {
        require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-manager.php';
    }
    $certificate_manager = HVAC_Certificate_Manager::instance();

    // Get certificate security instance
    if (!class_exists('HVAC_Certificate_Security')) {
        require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-security.php';
    }
    $certificate_security = HVAC_Certificate_Security::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;
    }

    // Get filtering parameters
    $filter_event = isset($_GET['filter_event']) ? absint($_GET['filter_event']) : 0;
    $filter_status = isset($_GET['filter_status']) ? sanitize_text_field($_GET['filter_status']) : 'active';
    $page = isset($_GET['certificate_page']) ? absint($_GET['certificate_page']) : 1;
    $per_page = 20;

    // Build filter args
    $filter_args = array(
        'page' => $page,
        'per_page' => $per_page,
        'orderby' => 'date_generated',
        'order' => 'DESC',
    );

    // Add event filter if selected
    if ($filter_event > 0) {
        $filter_args['event_id'] = $filter_event;
    }

    // Add status filter
    if ($filter_status === 'active') {
        $filter_args['revoked'] = 0;
    } elseif ($filter_status === 'revoked') {
        $filter_args['revoked'] = 1;
    }
    // Default 'all' doesn't add a filter

    // Get user's events for filtering 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"
    );
    
    // Check if user has any events
    if (empty($events)) {
        // No certificates to show since user has no events
        $certificates = array();
        $total_certificates = 0;
        $total_pages = 0;
        $certificate_stats = array(
            'total' => 0,
            'active' => 0,
            'revoked' => 0,
            'emailed' => 0
        );
    } else {
        // Get certificates for the current user with filters
        $certificates = $certificate_manager->get_user_certificates($current_user_id, $filter_args);

        // Get total certificate count for pagination
        $total_certificates = $certificate_manager->get_user_certificate_count($current_user_id, $filter_args);
        $total_pages = ceil($total_certificates / $per_page);

        // Get certificate statistics
        $certificate_stats = $certificate_manager->get_user_certificate_stats($current_user_id);
    }

    // Get header and footer
    get_header();
} catch (Exception $e) {
    echo '<div class="hvac-error">Error initializing certificate system: ' . esc_html($e->getMessage()) . '</div>';
    return;
}
?>

<div class="hvac-container">
    <div class="hvac-content-wrapper">
        <!-- Navigation Header -->
        <div class="hvac-dashboard-header">
            <h1 class="entry-title">Certificate Reports</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( '/generate-certificates/' ) ); ?>" class="ast-button ast-button-secondary">Generate Certificates</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">View and manage all certificates you've generated for event attendees.</p>
        </div>
        
        <!-- Certificate Statistics -->
        <div class="hvac-section hvac-stats-section">
            <h2>Certificate Statistics</h2>
            
            <div class="hvac-certificate-stats">
                <div class="hvac-stat-card">
                    <h3>Total Certificates</h3>
                    <div class="hvac-stat-value"><?php echo esc_html($certificate_stats['total']); ?></div>
                </div>
                
                <div class="hvac-stat-card">
                    <h3>Active Certificates</h3>
                    <div class="hvac-stat-value"><?php echo esc_html($certificate_stats['active']); ?></div>
                </div>
                
                <div class="hvac-stat-card">
                    <h3>Revoked Certificates</h3>
                    <div class="hvac-stat-value"><?php echo esc_html($certificate_stats['revoked']); ?></div>
                </div>
                
                <div class="hvac-stat-card">
                    <h3>Emailed Certificates</h3>
                    <div class="hvac-stat-value"><?php echo esc_html($certificate_stats['emailed']); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Certificate Filters -->
        <div class="hvac-section hvac-filters-section">
            <h2>Certificate Filters</h2>
            
            <form method="get" class="hvac-certificate-filters">
                <div class="hvac-filter-group">
                    <label for="filter_event">Event:</label>
                    <select name="filter_event" id="filter_event">
                        <option value="0">All Events</option>
                        <?php foreach ($events as $event) : ?>
                            <option value="<?php echo esc_attr($event->ID); ?>" <?php selected($filter_event, $event->ID); ?>>
                                <?php echo esc_html($event->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="hvac-filter-group">
                    <label for="filter_status">Status:</label>
                    <select name="filter_status" id="filter_status">
                        <option value="all" <?php selected($filter_status, 'all'); ?>>All Certificates</option>
                        <option value="active" <?php selected($filter_status, 'active'); ?>>Active Only</option>
                        <option value="revoked" <?php selected($filter_status, 'revoked'); ?>>Revoked Only</option>
                    </select>
                </div>
                
                <div class="hvac-filter-group hvac-filter-submit">
                    <button type="submit" class="hvac-button hvac-primary">Apply Filters</button>
                </div>
            </form>
        </div>
        
        <!-- Certificate Listing -->
        <div class="hvac-section hvac-certificates-section">
            <h2>Certificate Listing</h2>
            
            <?php if (empty($certificates)) : ?>
                <div class="hvac-no-certificates">
                    <p>No certificates found matching your filters.</p>
                    
                    <?php if ($filter_event > 0 || $filter_status !== 'active') : ?>
                        <p><a href="<?php echo esc_url(remove_query_arg(array('filter_event', 'filter_status'))); ?>">Clear filters</a> to see all your certificates.</p>
                    <?php else : ?>
                        <p>Generate certificates for your event attendees on the <a href="<?php echo esc_url(get_permalink(get_page_by_path('generate-certificates'))); ?>">Generate Certificates</a> page.</p>
                    <?php endif; ?>
                </div>
            <?php else : ?>
                <div class="hvac-certificate-table-wrapper">
                    <table class="hvac-certificate-table">
                        <thead>
                            <tr>
                                <th>Certificate #</th>
                                <th>Event</th>
                                <th>Attendee</th>
                                <th>Date Generated</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($certificates as $certificate) : 
                                // Get certificate data
                                $certificate_number = $certificate->certificate_number;
                                $event_id = $certificate->event_id;
                                $attendee_id = $certificate->attendee_id;
                                $generated_date = date_i18n(get_option('date_format'), strtotime($certificate->date_generated));
                                $is_revoked = (bool) $certificate->revoked;
                                $is_emailed = (bool) $certificate->email_sent;
                                
                                // Get event and attendee information
                                $event_title = get_the_title($event_id);
                                $attendee_name = get_post_meta($attendee_id, '_tribe_tickets_full_name', true);
                                if (empty($attendee_name)) {
                                    $attendee_name = 'Attendee #' . $attendee_id;
                                }
                                
                                // Status text and class
                                $status_text = $is_revoked ? 'Revoked' : 'Active';
                                $status_class = $is_revoked ? 'hvac-status-revoked' : 'hvac-status-active';
                            ?>
                                <tr class="<?php echo $is_revoked ? 'hvac-certificate-revoked' : ''; ?>">
                                    <td><?php echo esc_html($certificate_number); ?></td>
                                    <td>
                                        <a href="<?php echo esc_url(get_permalink($event_id)); ?>" target="_blank">
                                            <?php echo esc_html($event_title); ?>
                                        </a>
                                    </td>
                                    <td><?php echo esc_html($attendee_name); ?></td>
                                    <td><?php echo esc_html($generated_date); ?></td>
                                    <td>
                                        <span class="<?php echo esc_attr($status_class); ?>">
                                            <?php echo esc_html($status_text); ?>
                                        </span>
                                        <?php if ($is_revoked && !empty($certificate->revoked_date)) : ?>
                                            <div class="hvac-certificate-revocation-info">
                                                <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($certificate->revoked_date))); ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="hvac-certificate-actions">
                                        <?php if (!$is_revoked) : ?>
                                            <button class="hvac-view-certificate" data-certificate-id="<?php echo esc_attr($certificate->certificate_id); ?>">View</button>
                                            <button class="hvac-email-certificate" data-certificate-id="<?php echo esc_attr($certificate->certificate_id); ?>"><?php echo $is_emailed ? 'Re-email' : 'Email'; ?></button>
                                            <button class="hvac-revoke-certificate" data-certificate-id="<?php echo esc_attr($certificate->certificate_id); ?>">Revoke</button>
                                        <?php else : ?>
                                            <span class="hvac-certificate-revoked-message">Certificate has been revoked</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if ($total_pages > 1) : ?>
                    <div class="hvac-pagination">
                        <?php
                        // Previous page link
                        if ($page > 1) {
                            $prev_url = add_query_arg('certificate_page', $page - 1);
                            echo '<a href="' . esc_url($prev_url) . '" class="hvac-button hvac-pagination-prev">&laquo; Previous</a>';
                        }
                        
                        // Page numbers
                        for ($i = 1; $i <= $total_pages; $i++) {
                            $page_url = add_query_arg('certificate_page', $i);
                            $class = $i === $page ? 'hvac-button hvac-pagination-current' : 'hvac-button';
                            echo '<a href="' . esc_url($page_url) . '" class="' . esc_attr($class) . '">' . $i . '</a>';
                        }
                        
                        // Next page link
                        if ($page < $total_pages) {
                            $next_url = add_query_arg('certificate_page', $page + 1);
                            echo '<a href="' . esc_url($next_url) . '" class="hvac-button hvac-pagination-next">Next &raquo;</a>';
                        }
                        ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
        
        <!-- Certificate Viewer Modal -->
        <div class="hvac-modal-overlay"></div>
        <div id="hvac-certificate-modal" class="hvac-certificate-modal">
            <span class="hvac-modal-close">&times;</span>
            <h2 class="hvac-modal-title">Certificate Preview</h2>
            <iframe id="hvac-certificate-preview" class="hvac-certificate-preview" src="" frameborder="0"></iframe>
        </div>
    </div>
</div>

<?php
// Enqueue the scripts and styles
wp_enqueue_style('hvac-certificates-css', HVAC_CE_PLUGIN_URL . 'assets/css/hvac-certificates.css', array(), HVAC_CE_VERSION);
wp_enqueue_script('hvac-certificate-actions-js', HVAC_CE_PLUGIN_URL . 'assets/js/hvac-certificate-actions.js', array('jquery'), HVAC_CE_VERSION, true);

// Localize script with AJAX data
wp_localize_script('hvac-certificate-actions-js', 'hvacCertificateData', array(
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'viewNonce' => wp_create_nonce('hvac_view_certificate'),
    'emailNonce' => wp_create_nonce('hvac_email_certificate'),
    'revokeNonce' => wp_create_nonce('hvac_revoke_certificate')
));

// Close the try block
get_footer();
?>
