<?php
/**
 * Test Certificate Generator Script
 * 
 * This script generates test certificates for attendees who are marked as checked-in.
 * Upload to the server and run via wp-cli or directly via PHP.
 *
 * Usage: php generate-test-certificates.php
 */

// Load WordPress with full admin capabilities
define('WP_USE_THEMES', false);
require_once('wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

// Set execution time limit to allow for certificate generation
set_time_limit(300);

echo "===== HVAC TEST CERTIFICATE GENERATOR =====\n\n";

// Make sure certificate classes exist
if (!class_exists('HVAC_Certificate_Manager')) {
    echo "Error: HVAC_Certificate_Manager class not found.\n";
    echo "Please ensure the HVAC Community Events plugin is properly installed and activated.\n";
    exit(1);
}

// Initialize certificate manager
$certificate_manager = HVAC_Certificate_Manager::instance();

// Check if certificate table exists
global $wpdb;
$table_name = $wpdb->prefix . 'hvac_certificates';
$table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;

if (!$table_exists) {
    echo "Certificate table does not exist. Creating it now...\n";
    
    // Try to create the table using the installer
    if (class_exists('HVAC_Certificate_Installer')) {
        $installer = HVAC_Certificate_Installer::instance();
        $installer->create_tables();
        
        // Check if table creation was successful
        $table_exists = $wpdb->get_var("SHOW TABLES LIKE '$table_name'") === $table_name;
        if (!$table_exists) {
            echo "Failed to create certificate table. Exiting.\n";
            exit(1);
        }
        
        echo "Certificate table created successfully.\n";
    } else {
        echo "Error: HVAC_Certificate_Installer class not found. Exiting.\n";
        exit(1);
    }
}

// Create certificate storage directory if it doesn't exist
$upload_dir = wp_upload_dir();
$cert_dir = $upload_dir['basedir'] . '/' . get_option('hvac_certificate_storage_path', 'hvac-certificates');

if (!file_exists($cert_dir)) {
    echo "Certificate directory does not exist. Creating it now...\n";
    $result = wp_mkdir_p($cert_dir);
    if (!$result) {
        echo "Failed to create certificate directory at: {$cert_dir}\n";
        exit(1);
    }
    echo "Certificate directory created at: {$cert_dir}\n";
}

// Get the events to generate certificates for
$event_ids = [5484, 5485, 5486]; // HVAC Installation, Commercial HVAC, HVAC Energy Efficiency 

// Variables to track generation stats
$total_certificates = 0;
$total_revoked = 0;
$total_emailed = 0;
$failed_generations = 0;

echo "Generating certificates for " . count($event_ids) . " events...\n\n";

foreach ($event_ids as $event_id) {
    $event = get_post($event_id);
    if (!$event) {
        echo "Event ID {$event_id} does not exist. Skipping.\n";
        continue;
    }
    
    echo "Processing event: {$event->post_title} (ID: {$event_id})\n";
    
    // Get checked-in attendees for this event
    $attendees = get_posts([
        'post_type' => 'tribe_tpp_attendees',
        'meta_query' => [
            'relation' => 'AND',
            [
                'key' => '_tribe_tpp_event',
                'value' => $event_id,
            ],
            [
                'key' => '_tribe_tpp_checkin',
                'value' => 1,
            ]
        ],
        'posts_per_page' => -1
    ]);
    
    echo "Found " . count($attendees) . " checked-in attendees for event {$event_id}\n";
    
    // Get a random user ID for the certificate generation (by default the current user)
    $user_query = new WP_User_Query([
        'role' => 'administrator',
        'number' => 1
    ]);
    
    $admin_users = $user_query->get_results();
    $generated_by = !empty($admin_users) ? $admin_users[0]->ID : get_current_user_id();
    
    // Find the trainer user if available
    $trainer_user = get_user_by('login', 'test_trainer');
    $trainer_id = $trainer_user ? $trainer_user->ID : $generated_by;
    
    // Generate certificates for each attendee
    $certificates_created = 0;
    $certificates_revoked = 0;
    $certificates_emailed = 0;
    
    foreach ($attendees as $attendee) {
        $attendee_id = $attendee->ID;
        $attendee_name = get_post_meta($attendee_id, '_tribe_tickets_full_name', true);
        $attendee_email = get_post_meta($attendee_id, '_tribe_tickets_email', true);
        
        // Skip if a certificate already exists
        if ($certificate_manager->certificate_exists($event_id, $attendee_id)) {
            echo " - Certificate already exists for attendee {$attendee_name} ({$attendee_id}). Skipping.\n";
            continue;
        }
        
        // Create a sample certificate file path
        $year = date('Y');
        $month = date('m');
        $certificate_filename = "certificate-{$event_id}-{$attendee_id}-" . time() . ".pdf";
        $certificate_relative_path = "hvac-certificates/{$year}/{$month}/{$certificate_filename}";
        
        // Create the certificate record
        $certificate_id = $certificate_manager->create_certificate(
            $event_id,
            $attendee_id,
            0, // user_id (not associated with a user)
            $certificate_relative_path,
            $trainer_id // generated by (trainer)
        );
        
        if ($certificate_id) {
            $certificates_created++;
            
            // Create year/month directory structure if needed
            $year_month_dir = $cert_dir . "/{$year}/{$month}";
            if (!file_exists($year_month_dir)) {
                wp_mkdir_p($year_month_dir);
            }
            
            // Example - Create a dummy PDF file (in real scenario, you'd generate a real PDF)
            // For testing purposes, we'll create an empty file
            $certificate_full_path = $upload_dir['basedir'] . '/' . $certificate_relative_path;
            file_put_contents($certificate_full_path, "Placeholder for certificate PDF (Generated for testing)");
            
            echo " - Generated certificate for {$attendee_name} ({$attendee_email}) - ID: {$certificate_id}\n";
            
            // For testing, randomly mark some certificates as revoked or emailed
            $random = mt_rand(1, 10);
            
            // Revoke about 10% of certificates
            if ($random == 1) {
                $revoke_result = $certificate_manager->revoke_certificate(
                    $certificate_id,
                    $generated_by,
                    "Test revocation for certificate testing"
                );
                
                if ($revoke_result) {
                    $certificates_revoked++;
                    echo "   - Revoked certificate ID: {$certificate_id}\n";
                }
            }
            
            // Mark about 60% as emailed
            if ($random <= 6) {
                $email_result = $certificate_manager->mark_certificate_emailed($certificate_id);
                
                if ($email_result) {
                    $certificates_emailed++;
                    echo "   - Marked certificate ID: {$certificate_id} as emailed\n";
                }
            }
        } else {
            echo " - Failed to generate certificate for attendee {$attendee_name} ({$attendee_id})\n";
            $failed_generations++;
        }
    }
    
    // Update statistics
    $total_certificates += $certificates_created;
    $total_revoked += $certificates_revoked;
    $total_emailed += $certificates_emailed;
    
    echo "Created {$certificates_created} certificates for event {$event_id}\n";
    echo "Revoked {$certificates_revoked} certificates for event {$event_id}\n";
    echo "Marked {$certificates_emailed} certificates as emailed for event {$event_id}\n";
    echo "----------------------------\n";
}

echo "\n===== CERTIFICATE GENERATION SUMMARY =====\n";
echo "Total certificates created: {$total_certificates}\n";
echo "Total certificates revoked: {$total_revoked}\n";
echo "Total certificates marked as emailed: {$total_emailed}\n";
echo "Failed certificate generations: {$failed_generations}\n";

// Fetch some certificate statistics for verification
if (class_exists('HVAC_Certificate_Manager')) {
    echo "\n===== CERTIFICATE DATABASE VERIFICATION =====\n";
    $stats = $certificate_manager->get_certificate_stats();
    
    echo "Certificate count in database: {$stats['total_certificates']}\n";
    echo "Event count with certificates: {$stats['total_events']}\n";
    echo "Trainee count with certificates: {$stats['total_trainees']}\n";
    echo "Total revoked certificates: {$stats['total_revoked']}\n";
    echo "Total emailed certificates: {$stats['total_emailed']}\n";
}

// Print instructions on how to view certificates
echo "\n===== INSTRUCTIONS =====\n";
echo "1. Certificates have been generated for checked-in attendees\n";
echo "2. View certificates at: " . home_url('/certificate-reports/') . "\n";
echo "3. Filter certificates by event, attendee name, or revocation status\n";
echo "4. Download certificate PDFs from the certificate reports page\n";

echo "\n===== CERTIFICATE GENERATION COMPLETED =====\n";