#!/bin/bash

# Load configuration
source wordpress-dev/bin/hvac-plugin-deploy.conf

echo "=== Enhancing Test Data with Revenue and Sales Information ==="

# Execute PHP script directly on server
ssh $REMOTE_USER@$REMOTE_HOST << 'ENDSSH'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# Create and execute the PHP script
cat << 'EOF' > enhance-revenue-data.php
<?php
// Load WordPress
require_once('wp-load.php');

echo "=== Enhancing test data with revenue information ===\n\n";

// Get test trainer
$test_trainer = get_user_by('login', 'test_trainer');
if (!$test_trainer) {
    die("test_trainer user not found.\n");
}
$trainer_id = $test_trainer->ID;

// Get all events created by test_trainer
$events = get_posts([
    'post_type' => 'tribe_events',
    'post_status' => 'publish',
    'author' => $trainer_id,
    'posts_per_page' => -1,
    'orderby' => 'date',
    'order' => 'DESC'
]);

echo "Found " . count($events) . " events to enhance\n\n";

foreach ($events as $event) {
    echo "Enhancing event: {$event->post_title} (ID: {$event->ID})\n";
    
    // Get existing ticket for this event
    $tickets = get_posts([
        'post_type' => 'tribe_tpp_tickets',
        'meta_query' => [
            [
                'key' => '_tribe_tpp_for_event',
                'value' => $event->ID
            ]
        ],
        'posts_per_page' => 1
    ]);
    
    if (!empty($tickets)) {
        $ticket = $tickets[0];
        $ticket_id = $ticket->ID;
        echo "Found existing ticket ID: {$ticket_id}\n";
        
        // Get ticket price
        $price = get_post_meta($ticket_id, '_price', true) ?: 299;
        
        // Count actual attendees
        $attendees = get_posts([
            'post_type' => 'tribe_tpp_attendees',
            'meta_query' => [
                [
                    'key' => '_tribe_tpp_event',
                    'value' => $event->ID
                ]
            ],
            'posts_per_page' => -1
        ]);
        
        $attendee_count = count($attendees);
        $checked_in_count = 0;
        
        // Update attendee payment status and count check-ins
        foreach ($attendees as $attendee) {
            // Ensure payment status is set
            update_post_meta($attendee->ID, '_paid_price', $price);
            update_post_meta($attendee->ID, '_tribe_tickets_order_status', 'completed');
            update_post_meta($attendee->ID, '_tribe_tpp_order_status', 'completed');
            
            // Count checked in
            $is_checked_in = get_post_meta($attendee->ID, '_tribe_tpp_checkin', true);
            if ($is_checked_in) {
                $checked_in_count++;
            }
        }
        
        // Calculate revenue
        $total_revenue = $attendee_count * $price;
        
        // Update ticket meta with accurate sales data
        update_post_meta($ticket_id, '_tribe_tpp_sold', $attendee_count);
        update_post_meta($ticket_id, '_tribe_ticket_sold', $attendee_count);
        update_post_meta($ticket_id, 'total_sales', $attendee_count);
        update_post_meta($ticket_id, '_stock', 50 - $attendee_count); // Assuming capacity of 50
        
        // Update event meta for revenue tracking
        update_post_meta($event->ID, '_tribe_ticket_sold_count', $attendee_count);
        update_post_meta($event->ID, '_EventCost', $price);
        update_post_meta($event->ID, '_tribe_event_revenue', $total_revenue);
        
        // Add provider if not set
        $provider = get_post_meta($event->ID, '_tribe_default_ticket_provider', true);
        if (empty($provider)) {
            update_post_meta($event->ID, '_tribe_default_ticket_provider', 'Tribe__Tickets_Plus__Commerce__PayPal__Main');
        }
        
        echo "- Attendees: {$attendee_count}\n";
        echo "- Checked in: {$checked_in_count}\n";
        echo "- Ticket price: \${$price}\n";
        echo "- Total revenue: \${$total_revenue}\n";
        
        // Ensure we have PayPal order data for each attendee (needed for reports)
        $order_num = 1;
        foreach ($attendees as $attendee) {
            $order_id = get_post_meta($attendee->ID, '_tribe_tpp_order', true);
            if (empty($order_id) || strpos($order_id, 'TEST-') === 0) {
                // Create a more realistic order ID
                $new_order_id = 'PAY-' . strtoupper(substr(md5($event->ID . '-' . $attendee->ID . '-' . time()), 0, 8));
                update_post_meta($attendee->ID, '_tribe_tpp_order', $new_order_id);
                update_post_meta($attendee->ID, '_tribe_paypal_transaction_id', $new_order_id);
            }
            
            // Ensure attendee has all required meta for revenue calculation
            update_post_meta($attendee->ID, '_tribe_tpp_price', $price);
            update_post_meta($attendee->ID, '_paid_price', $price);
            update_post_meta($attendee->ID, '_tribe_tickets_event_id', $event->ID);
            update_post_meta($attendee->ID, '_tribe_tickets_product_id', $ticket_id);
            
            $order_num++;
        }
        
    } else {
        echo "No ticket found for this event - skipping revenue enhancement\n";
    }
    
    echo "----------------------------\n";
}

// Now let's add some additional attendees to events that need more data
echo "\nAdding additional attendees to events with low attendance...\n\n";

foreach ($events as $event) {
    // Get ticket
    $tickets = get_posts([
        'post_type' => 'tribe_tpp_tickets',
        'meta_query' => [
            [
                'key' => '_tribe_tpp_for_event',
                'value' => $event->ID
            ]
        ],
        'posts_per_page' => 1
    ]);
    
    if (empty($tickets)) {
        continue;
    }
    
    $ticket = $tickets[0];
    $ticket_id = $ticket->ID;
    $price = get_post_meta($ticket_id, '_price', true) ?: 299;
    
    // Count current attendees
    $current_attendees = get_posts([
        'post_type' => 'tribe_tpp_attendees',
        'meta_query' => [
            [
                'key' => '_tribe_tpp_event',
                'value' => $event->ID
            ]
        ],
        'posts_per_page' => -1
    ]);
    
    $current_count = count($current_attendees);
    
    // If less than 15 attendees, add more
    if ($current_count < 15) {
        $to_add = 15 - $current_count;
        echo "Event '{$event->post_title}' has {$current_count} attendees. Adding {$to_add} more...\n";
        
        $names = [
            ['Alex', 'Thompson', 'alex.thompson'],
            ['Jessica', 'Martinez', 'jessica.martinez'],
            ['Ryan', 'Chen', 'ryan.chen'],
            ['Ashley', 'Kumar', 'ashley.kumar'],
            ['Brandon', 'White', 'brandon.white'],
            ['Nicole', 'Lee', 'nicole.lee'],
            ['Justin', 'Harris', 'justin.harris'],
            ['Amanda', 'Clark', 'amanda.clark'],
            ['Kevin', 'Lewis', 'kevin.lewis'],
            ['Rachel', 'Walker', 'rachel.walker'],
            ['Timothy', 'Hall', 'timothy.hall'],
            ['Laura', 'Allen', 'laura.allen'],
            ['Jason', 'Young', 'jason.young'],
            ['Michelle', 'King', 'michelle.king'],
            ['Eric', 'Wright', 'eric.wright']
        ];
        
        for ($i = 0; $i < $to_add && $i < count($names); $i++) {
            list($first_name, $last_name, $email_prefix) = $names[$i];
            $full_name = "{$first_name} {$last_name}";
            $email = $email_prefix . rand(100, 999) . '@hvacpro.com';
            
            // Create attendee
            $attendee_args = [
                'post_title' => $full_name,
                'post_content' => '',
                'post_status' => 'publish',
                'post_type' => 'tribe_tpp_attendees',
                'post_author' => $trainer_id
            ];
            
            $attendee_id = wp_insert_post($attendee_args);
            
            if (!is_wp_error($attendee_id)) {
                // Create realistic order ID
                $order_id = 'PAY-' . strtoupper(substr(md5($event->ID . '-' . $attendee_id . '-' . time()), 0, 8));
                
                // Set all attendee meta
                $attendee_meta = [
                    '_tribe_tpp_event' => $event->ID,
                    '_tribe_tpp_product' => $ticket_id,
                    '_tribe_tpp_order' => $order_id,
                    '_tribe_paypal_transaction_id' => $order_id,
                    '_tribe_tickets_full_name' => $full_name,
                    '_tribe_tickets_email' => $email,
                    '_tribe_tpp_full_name' => $full_name,
                    '_tribe_tpp_email' => $email,
                    '_tribe_tpp_security_code' => substr(md5($order_id), 0, 10),
                    '_paid_price' => $price,
                    '_tribe_tpp_price' => $price,
                    '_tribe_tickets_order_status' => 'completed',
                    '_tribe_tpp_order_status' => 'completed',
                    '_tribe_tickets_event_id' => $event->ID,
                    '_tribe_tickets_product_id' => $ticket_id
                ];
                
                foreach ($attendee_meta as $key => $value) {
                    update_post_meta($attendee_id, $key, $value);
                }
                
                // Check in 85% of new attendees
                if ($i < ($to_add * 0.85)) {
                    update_post_meta($attendee_id, '_tribe_tpp_checkin', 1);
                    update_post_meta($attendee_id, 'check_in', 1);
                }
            }
        }
        
        // Update ticket sales count
        $new_total = $current_count + $to_add;
        update_post_meta($ticket_id, '_tribe_tpp_sold', $new_total);
        update_post_meta($ticket_id, '_tribe_ticket_sold', $new_total);
        update_post_meta($ticket_id, 'total_sales', $new_total);
        update_post_meta($ticket_id, '_stock', 50 - $new_total);
        
        // Update event revenue
        $new_revenue = $new_total * $price;
        update_post_meta($event->ID, '_tribe_ticket_sold_count', $new_total);
        update_post_meta($event->ID, '_tribe_event_revenue', $new_revenue);
        
        echo "Added {$to_add} attendees. New total: {$new_total}, Revenue: \${$new_revenue}\n";
    }
}

// Generate certificates for all checked-in attendees
if (class_exists('HVAC_Certificate_Manager')) {
    echo "\n=== Generating certificates for checked-in attendees ===\n";
    
    $certificate_manager = HVAC_Certificate_Manager::instance();
    $total_certificates = 0;
    
    foreach ($events as $event) {
        echo "\nProcessing certificates for: {$event->post_title}\n";
        
        // Get all checked-in attendees
        $checked_in_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
        ]);
        
        $event_certificates = 0;
        
        foreach ($checked_in_attendees as $attendee) {
            // Check if certificate already exists
            if (!$certificate_manager->certificate_exists($event->ID, $attendee->ID)) {
                // Generate certificate
                $cert_filename = 'certificate-' . $event->ID . '-' . $attendee->ID . '-' . time() . '.pdf';
                $cert_path = 'hvac-certificates/' . date('Y/m/') . $cert_filename;
                
                $cert_id = $certificate_manager->create_certificate(
                    $event->ID,
                    $attendee->ID,
                    0, // user_id
                    $cert_path,
                    $trainer_id
                );
                
                if ($cert_id) {
                    $event_certificates++;
                    $total_certificates++;
                    
                    // Create dummy PDF file
                    $upload_dir = wp_upload_dir();
                    $full_path = $upload_dir['basedir'] . '/' . $cert_path;
                    $dir = dirname($full_path);
                    if (!file_exists($dir)) {
                        wp_mkdir_p($dir);
                    }
                    
                    // Create a simple PDF-like content
                    $attendee_name = get_post_meta($attendee->ID, '_tribe_tickets_full_name', true);
                    $pdf_content = "%PDF-1.4\nTest Certificate for {$attendee_name}\nEvent: {$event->post_title}\nGenerated for testing purposes.";
                    file_put_contents($full_path, $pdf_content);
                }
            }
        }
        
        if ($event_certificates > 0) {
            echo "Generated {$event_certificates} certificates for this event\n";
        } else {
            echo "All attendees already have certificates\n";
        }
    }
    
    echo "\nTotal new certificates generated: {$total_certificates}\n";
}

// Summary of all events with revenue
echo "\n=== Final Event Summary ===\n";
$total_revenue = 0;
$total_attendees = 0;
$total_checked_in = 0;

foreach ($events as $event) {
    $attendees = get_posts([
        'post_type' => 'tribe_tpp_attendees',
        'meta_query' => [
            [
                'key' => '_tribe_tpp_event',
                'value' => $event->ID
            ]
        ],
        'posts_per_page' => -1
    ]);
    
    $attendee_count = count($attendees);
    $checked_in = 0;
    $event_revenue = 0;
    
    foreach ($attendees as $attendee) {
        if (get_post_meta($attendee->ID, '_tribe_tpp_checkin', true)) {
            $checked_in++;
        }
        $paid = get_post_meta($attendee->ID, '_paid_price', true) ?: 0;
        $event_revenue += $paid;
    }
    
    $total_revenue += $event_revenue;
    $total_attendees += $attendee_count;
    $total_checked_in += $checked_in;
    
    echo "\n{$event->post_title}:\n";
    echo "- Attendees: {$attendee_count}\n";
    echo "- Checked in: {$checked_in}\n";
    echo "- Revenue: \${$event_revenue}\n";
}

echo "\n=== TOTAL SUMMARY ===\n";
echo "Total Events: " . count($events) . "\n";
echo "Total Attendees: {$total_attendees}\n";
echo "Total Checked In: {$total_checked_in}\n";
echo "Total Revenue: \${$total_revenue}\n";

echo "\nRevenue data enhancement completed!\n";
?>
EOF

# Execute the PHP script
php enhance-revenue-data.php

# Clean up
rm enhance-revenue-data.php
ENDSSH

echo ""
echo "[0;32mRevenue data enhancement completed![0m"
echo ""
echo "You can now test:"
echo "1. Dashboard with revenue numbers: https://upskill-staging.measurequick.com/hvac-dashboard/"
echo "2. Generate Certificates: https://upskill-staging.measurequick.com/generate-certificates/"
echo "3. Certificate Reports: https://upskill-staging.measurequick.com/certificate-reports/"
echo ""
echo "The dashboard should now show:"
echo "- Total revenue from ticket sales"
echo "- Number of tickets sold per event"
echo "- Attendee counts and check-in rates"
echo ""
echo "Certificates can be generated for all checked-in attendees."