<?php
/**
 * Mark Existing Attendees as Checked In and Generate Certificates
 * 
 * This script marks existing attendees as checked in and generates certificates for them.
 */

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

echo "===== MARKING ATTENDEES AS CHECKED IN & GENERATING CERTIFICATES =====\n\n";

// Check for certificate manager
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();

// Get all attendees
$attendees = get_posts([
    'post_type' => 'tribe_tpp_attendees',
    'posts_per_page' => 100,
]);

// Get attendees from RSVP as well
$rsvp_attendees = get_posts([
    'post_type' => 'tribe_rsvp_attendees',
    'posts_per_page' => 100,
]);

// Combine attendees
$all_attendees = array_merge($attendees, $rsvp_attendees);

echo "Found " . count($all_attendees) . " total attendees\n";

// 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";
}

// Track stats
$checked_in = 0;
$certificates_created = 0;
$certificates_revoked = 0;
$certificates_emailed = 0;

// Process attendees
foreach ($all_attendees as $attendee) {
    $attendee_id = $attendee->ID;
    
    // Get attendee details
    $attendee_name = get_post_meta($attendee_id, '_tribe_tickets_full_name', true);
    if (empty($attendee_name)) {
        $attendee_name = get_post_meta($attendee_id, '_tribe_rsvp_full_name', true);
    }
    
    $attendee_email = get_post_meta($attendee_id, '_tribe_tickets_email', true);
    if (empty($attendee_email)) {
        $attendee_email = get_post_meta($attendee_id, '_tribe_rsvp_email', true);
    }
    
    // Get event ID
    $event_id = get_post_meta($attendee_id, '_tribe_tpp_event', true);
    if (empty($event_id)) {
        $event_id = get_post_meta($attendee_id, '_tribe_rsvp_event', true);
    }
    
    if (!$event_id) {
        echo "No event ID found for attendee {$attendee_id}. Skipping.\n";
        continue;
    }
    
    // Check if already checked in
    $is_checked_in = false;
    
    $checkin_status1 = get_post_meta($attendee_id, '_tribe_tpp_checkin', true);
    $checkin_status2 = get_post_meta($attendee_id, '_tribe_rsvp_checkin', true);
    $checkin_status3 = get_post_meta($attendee_id, '_tribe_tickets_checkin_status', true);
    
    if (!empty($checkin_status1) || !empty($checkin_status2) || !empty($checkin_status3)) {
        $is_checked_in = true;
    }
    
    // Mark as checked in randomly (if not already)
    if (!$is_checked_in && mt_rand(1, 3) == 1) {
        // Update the various check-in fields used by different ticket providers
        update_post_meta($attendee_id, '_tribe_tpp_checkin', 1);
        update_post_meta($attendee_id, '_tribe_rsvp_checkin', 1);
        update_post_meta($attendee_id, '_tribe_tickets_checkin_status', 1);
        update_post_meta($attendee_id, 'check_in', 1);
        
        $is_checked_in = true;
        $checked_in++;
        
        echo "Marked attendee {$attendee_name} (ID: {$attendee_id}) as checked in\n";
    }
    
    // Generate certificate for checked-in attendees
    if ($is_checked_in) {
        // Skip if already has a certificate
        if ($certificate_manager->certificate_exists($event_id, $attendee_id)) {
            echo "Certificate already exists for attendee {$attendee_name} (ID: {$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 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,
            get_current_user_id() // generated by current user
        );
        
        if ($certificate_id) {
            $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 (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,
                    get_current_user_id(),
                    "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} (ID: {$attendee_id})\n";
        }
    }
}

echo "\n===== RESULTS =====\n";
echo "Marked {$checked_in} attendees as checked in\n";
echo "Generated {$certificates_created} certificates\n";
echo "Revoked {$certificates_revoked} certificates\n";
echo "Marked {$certificates_emailed} certificates as emailed\n";

// Get certificate statistics
if (class_exists('HVAC_Certificate_Manager')) {
    $stats = $certificate_manager->get_certificate_stats();
    
    echo "\n===== CERTIFICATE 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 "\n===== COMPLETE =====\n";