<?php
/**
 * Simplified template for the Certificate Reports page
 * This is a fallback version with minimal functionality to fix 500 errors
 *
 * @package HVAC_Community_Events
 * @subpackage Templates/Certificates
 */

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

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Get header
get_header();

// Current user ID
$current_user_id = get_current_user_id();

// Simple error handler
try {
    global $wpdb;
    
    // Check if certificate table exists
    $table_name = $wpdb->prefix . 'hvac_certificates';
    $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
    
    if (!$table_exists) {
        throw new Exception("Certificate database tables are not properly set up.");
    }
    
    // Basic empty stats
    $certificate_stats = array(
        'total' => 0,
        'active' => 0,
        'revoked' => 0,
        'emailed' => 0
    );
    
    // Get user's events for filtering
    $events = get_posts(array(
        'post_type' => 'tribe_events',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'author' => $current_user_id
    ));
    
    // Get basic stats without using the certificate manager class
    $event_ids = array();
    foreach ($events as $event) {
        $event_ids[] = $event->ID;
    }
    
    if (!empty($event_ids)) {
        $event_ids_string = implode(',', array_map('intval', $event_ids));
        
        // Only run query if we have events
        if (!empty($event_ids_string)) {
            $stats_query = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN revoked = 0 THEN 1 ELSE 0 END) as active,
                SUM(CASE WHEN revoked = 1 THEN 1 ELSE 0 END) as revoked,
                SUM(CASE WHEN email_sent = 1 THEN 1 ELSE 0 END) as emailed
            FROM {$wpdb->prefix}hvac_certificates 
            WHERE event_id IN ($event_ids_string)";
            
            $result = $wpdb->get_row($stats_query);
            
            if ($result) {
                $certificate_stats = array(
                    'total' => intval($result->total),
                    'active' => intval($result->active),
                    'revoked' => intval($result->revoked),
                    'emailed' => intval($result->emailed)
                );
            }
        }
    }
    
    // Empty certificates array to start with
    $certificates = array();
    $total_certificates = 0;
    $total_pages = 0;
    $page = isset($_GET['certificate_page']) ? absint($_GET['certificate_page']) : 1;
    $per_page = 20;
    
} catch (Exception $e) {
    echo '<div class="hvac-error">Error: ' . esc_html($e->getMessage()) . '</div>';
}
?>

<div class="hvac-container">
    <div class="hvac-content-wrapper">
        <div class="hvac-page-header">
            <h1>Certificate Reports</h1>
            <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(isset($_GET['filter_event']) ? absint($_GET['filter_event']) : 0, $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(isset($_GET['filter_status']) ? $_GET['filter_status'] : 'active', 'all'); ?>>All Certificates</option>
                        <option value="active" <?php selected(isset($_GET['filter_status']) ? $_GET['filter_status'] : 'active', 'active'); ?>>Active Only</option>
                        <option value="revoked" <?php selected(isset($_GET['filter_status']) ? $_GET['filter_status'] : 'active', '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 (isset($_GET['filter_event']) && $_GET['filter_event'] > 0 || (isset($_GET['filter_status']) && $_GET['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>
                                    </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 endif; ?>
        </div>
        
        <!-- Certificate viewer modal placeholder -->
        <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_PLUGIN_URL . 'assets/css/hvac-certificates.css', array(), HVAC_PLUGIN_VERSION);
wp_enqueue_script('hvac-certificate-actions-js', HVAC_PLUGIN_URL . 'assets/js/hvac-certificate-actions.js', array('jquery'), HVAC_PLUGIN_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')
));

// Footer
get_footer();
?>