<?php
/**
 * Create Test Events, Attendees, and Certificates
 * 
 * This script creates complete test events with attendees and certificates.
 */

// Load WordPress
require_once('wp-load.php');

echo "===== CREATING TEST EVENTS, ATTENDEES, AND CERTIFICATES =====\n\n";

// Check for required plugins
if (!class_exists('Tribe__Events__Main')) {
    die("The Events Calendar plugin is not active.\n");
}

if (!class_exists('HVAC_Certificate_Manager')) {
    die("Certificate Manager class not found. Please ensure the plugin is active.\n");
}

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

// Create certificate 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) {
        die("Failed to create certificate directory at: {$cert_dir}\n");
    }
    echo "Certificate directory created at: {$cert_dir}\n";
}

// Get current user ID for certificate generation
$current_user_id = get_current_user_id();
if (!$current_user_id) {
    $current_user_id = 1; // Default to admin if no user is logged in
}

// Test trainer user for event authorship
$trainer_user = get_user_by('login', 'test_trainer');
$trainer_id = $trainer_user ? $trainer_user->ID : $current_user_id;

// Define test events
$events = [
    [
        'title' => 'HVAC System Design Fundamentals',
        'description' => 'Learn the basics of designing effective HVAC systems for residential and light commercial buildings. This course covers load calculations, equipment selection, and ductwork design.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+1 week')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+1 week +6 hours')),
        'venue' => 'Technical Training Institute',
        'address' => '123 Education Blvd, Boston, MA 02108',
        'attendees' => 25,
        'checked_in' => 20,
    ],
    [
        'title' => 'Advanced Refrigeration Technology',
        'description' => 'Deep dive into commercial refrigeration systems, focusing on the latest technologies, troubleshooting techniques, and energy efficiency improvements.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+2 weeks')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+2 weeks +8 hours')),
        'venue' => 'Refrigeration Excellence Center',
        'address' => '456 Technology Park, Miami, FL 33101',
        'attendees' => 18,
        'checked_in' => 15,
    ],
    [
        'title' => 'Building Automation Systems Workshop',
        'description' => 'Hands-on workshop teaching the fundamentals of modern building automation systems, including programming, troubleshooting, and optimization techniques.',
        'start_date' => date('Y-m-d H:i:s', strtotime('+3 weeks')),
        'end_date' => date('Y-m-d H:i:s', strtotime('+3 weeks +12 hours')),
        'venue' => 'Smart Building Center',
        'address' => '789 Innovation Way, Seattle, WA 98101',
        'attendees' => 15,
        'checked_in' => 12,
    ]
];

// Attendee data generation
$first_names = ['John', 'Jane', 'Michael', 'Sara', 'David', 'Lisa', 'Robert', 'Emily', 
               'William', 'Olivia', 'James', 'Sophia', 'Thomas', 'Emma', 'Daniel', 'Ava'];

$last_names = ['Smith', 'Johnson', 'Williams', 'Jones', 'Brown', 'Davis', 'Miller', 'Wilson',
              'Moore', 'Taylor', 'Anderson', 'Thomas', 'Jackson', 'White', 'Harris', 'Martin'];

$domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'aol.com', 'icloud.com', 
            'protonmail.com', 'hvactraining.com', 'techedu.org', 'contractor.net'];

// Track statistics
$events_created = 0;
$attendees_created = 0;
$attendees_checked_in = 0;
$certificates_created = 0;
$certificates_revoked = 0;
$certificates_emailed = 0;
$created_event_ids = [];

// Create events and associated data
foreach ($events as $event_data) {
    echo "Creating event: {$event_data['title']}\n";
    
    // Create event
    $event_args = [
        'post_title' => $event_data['title'],
        'post_content' => $event_data['description'],
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Main::POSTTYPE,
        'post_author' => $trainer_id
    ];
    
    $event_id = wp_insert_post($event_args);
    
    if (is_wp_error($event_id)) {
        echo "Failed to create event: " . $event_id->get_error_message() . "\n";
        continue;
    }
    
    // Add event meta
    update_post_meta($event_id, '_EventStartDate', $event_data['start_date']);
    update_post_meta($event_id, '_EventEndDate', $event_data['end_date']);
    
    // Create venue
    $venue_args = [
        'post_title' => $event_data['venue'],
        'post_status' => 'publish',
        'post_type' => Tribe__Events__Venue::POSTTYPE,
        'post_author' => $trainer_id
    ];
    
    $venue_id = wp_insert_post($venue_args);
    
    if (!is_wp_error($venue_id)) {
        // Parse address
        $address_parts = explode(', ', $event_data['address']);
        $street = isset($address_parts[0]) ? $address_parts[0] : '';
        $city = isset($address_parts[1]) ? $address_parts[1] : '';
        $state_zip = isset($address_parts[2]) ? explode(' ', $address_parts[2]) : ['', ''];
        
        // Add venue meta
        update_post_meta($venue_id, '_VenueAddress', $street);
        update_post_meta($venue_id, '_VenueCity', $city);
        update_post_meta($venue_id, '_VenueStateProvince', $state_zip[0]);
        update_post_meta($venue_id, '_VenueZip', isset($state_zip[1]) ? $state_zip[1] : '');
        
        // Link venue to event
        update_post_meta($event_id, '_EventVenueID', $venue_id);
    }
    
    $events_created++;
    $created_event_ids[] = $event_id;
    
    echo "Event created successfully (ID: {$event_id})\n";
    
    // Create attendees directly (without tickets, for simplicity)
    $local_attendees_created = 0;
    $local_attendees_checked_in = 0;
    $local_certificates_created = 0;
    
    for ($i = 1; $i <= $event_data['attendees']; $i++) {
        // Generate attendee data
        $first_name = ($i === 1) ? 'Ben' : $first_names[array_rand($first_names)];
        $last_name = ($i === 1) ? 'Tester' : $last_names[array_rand($last_names)];
        $email = ($i === 1) ? 'ben@tealmaker.com' : 
            strtolower($first_name . '.' . $last_name . '.' . rand(100, 999) . '@' . $domains[array_rand($domains)]);
        
        $full_name = $first_name . ' ' . $last_name;
        
        // Create attendee post
        $attendee_args = [
            'post_title' => $full_name,
            'post_content' => '',
            'post_status' => 'publish',
            'post_type' => 'tribe_tpp_attendees', // Use PayPal attendees for this test
        ];
        
        $attendee_id = wp_insert_post($attendee_args);
        
        if (is_wp_error($attendee_id)) {
            echo "Failed to create attendee {$full_name}: " . $attendee_id->get_error_message() . "\n";
            continue;
        }
        
        // Generate a unique order ID
        $order_id = 'TEST-ORDER-' . $event_id . '-' . $i . '-' . uniqid();
        
        // Add attendee meta
        update_post_meta($attendee_id, '_tribe_tickets_full_name', $full_name);
        update_post_meta($attendee_id, '_tribe_tickets_email', $email);
        update_post_meta($attendee_id, '_tribe_tpp_full_name', $full_name); 
        update_post_meta($attendee_id, '_tribe_tpp_email', $email);
        update_post_meta($attendee_id, '_tribe_tpp_event', $event_id);
        update_post_meta($attendee_id, '_tribe_tpp_order', $order_id);
        update_post_meta($attendee_id, '_tribe_tpp_security_code', wp_generate_password(10, false));
        update_post_meta($attendee_id, '_tribe_tickets_order_status', 'completed');
        
        $local_attendees_created++;
        $attendees_created++;
        
        // Check in some attendees
        if ($i <= $event_data['checked_in']) {
            update_post_meta($attendee_id, '_tribe_tpp_checkin', 1);
            update_post_meta($attendee_id, '_tribe_tpp_checked_in', 1);
            update_post_meta($attendee_id, '_tribe_tickets_checkin_status', 1);
            update_post_meta($attendee_id, 'check_in', 1);
            
            $local_attendees_checked_in++;
            $attendees_checked_in++;
            
            // Generate certificate for checked-in attendee
            $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 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);
            }
            
            // 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) {
                $local_certificates_created++;
                $certificates_created++;
                
                // Create dummy certificate file
                $certificate_full_path = $upload_dir['basedir'] . '/' . $certificate_relative_path;
                file_put_contents($certificate_full_path, "Placeholder for certificate PDF - {$event_data['title']} - {$full_name}");
                
                // Randomly mark some certificates as revoked or emailed for testing
                $random = mt_rand(1, 10);
                
                // Revoke about 10% of certificates
                if ($random == 1) {
                    $certificate_manager->revoke_certificate(
                        $certificate_id,
                        $trainer_id,
                        "Test revocation for certificate testing"
                    );
                    $certificates_revoked++;
                }
                
                // Mark about 70% as emailed
                if ($random <= 7) {
                    $certificate_manager->mark_certificate_emailed($certificate_id);
                    $certificates_emailed++;
                }
            }
        }
    }
    
    echo "Created {$local_attendees_created} attendees\n";
    echo "Checked in {$local_attendees_checked_in} attendees\n";
    echo "Generated {$local_certificates_created} certificates\n";
    echo "----------------------------\n";
}

// Print summary
echo "\n===== TEST DATA CREATION SUMMARY =====\n";
echo "Events created: {$events_created}\n";
echo "Attendees created: {$attendees_created}\n";
echo "Attendees checked in: {$attendees_checked_in}\n";
echo "Certificates created: {$certificates_created}\n";
echo "Certificates revoked: {$certificates_revoked}\n";
echo "Certificates marked as emailed: {$certificates_emailed}\n";

// Get certificate statistics
$stats = $certificate_manager->get_certificate_stats();
    
echo "\n===== CERTIFICATE DATABASE STATISTICS =====\n";
echo "Total certificates in database: {$stats['total_certificates']}\n";
echo "Total events with certificates: {$stats['total_events']}\n";
echo "Total trainees with certificates: {$stats['total_trainees']}\n";
echo "Total revoked certificates: {$stats['total_revoked']}\n";
echo "Total emailed certificates: {$stats['total_emailed']}\n";
echo "Average certificates per attendee: {$stats['avg_per_attendee']}\n";

echo "\n===== EVENT IDS FOR REFERENCE =====\n";
foreach ($created_event_ids as $id) {
    $title = get_the_title($id);
    echo "Event ID {$id}: {$title}\n";
}

echo "\n===== TEST DATA CREATION COMPLETE =====\n";
echo "You can now test the certificate system with the created data.\n";
echo "View certificates at: " . home_url('/certificate-reports/') . "\n";