#!/bin/bash

# Debug and fix certificate attendees script with proper revenue data

source .env

echo "=== Debug and Fix Certificate Attendees + Revenue Data ==="
echo "Target: $UPSKILL_STAGING_IP"
echo "=========================================================="

# Upload and execute PHP script to debug and fix attendee data
sshpass -p "$UPSKILL_STAGING_PASS" scp -o StrictHostKeyChecking=no /dev/stdin $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP:tmp/debug-fix-attendees.php << 'PHPEOF'
<?php
require_once('wp-load.php');

echo "=== Debug and Fix Attendees for Revenue Calculation ===\n";

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

$trainer_id = $test_trainer->ID;
echo "Using trainer ID: {$trainer_id}\n";

// First, let's check existing attendees
echo "\n=== 1. Current Attendees Overview ===\n";
global $wpdb;

$attendees = $wpdb->get_results($wpdb->prepare(
    "SELECT 
        p.ID as attendee_id,
        p.post_parent as event_id,
        p.post_title,
        pm_event.meta_value as linked_event,
        pm_price1.meta_value as tec_commerce_price,
        pm_price2.meta_value as tpp_ticket_price,
        pm_price3.meta_value as tpp_price,
        pm_price4.meta_value as paid_price
    FROM {$wpdb->posts} p
    LEFT JOIN {$wpdb->postmeta} pm_event ON p.ID = pm_event.post_id AND pm_event.meta_key IN ('_tec_tickets_commerce_event', '_tribe_tpp_event')
    LEFT JOIN {$wpdb->postmeta} pm_price1 ON p.ID = pm_price1.post_id AND pm_price1.meta_key = '_tec_tickets_commerce_price_paid'
    LEFT JOIN {$wpdb->postmeta} pm_price2 ON p.ID = pm_price2.post_id AND pm_price2.meta_key = '_tribe_tpp_ticket_price'
    LEFT JOIN {$wpdb->postmeta} pm_price3 ON p.ID = pm_price3.post_id AND pm_price3.meta_key = '_tribe_tpp_price'
    LEFT JOIN {$wpdb->postmeta} pm_price4 ON p.ID = pm_price4.post_id AND pm_price4.meta_key = '_paid_price'
    WHERE p.post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees')
    AND p.post_parent IN (
        SELECT ID FROM {$wpdb->posts} 
        WHERE post_type = 'tribe_events' 
        AND post_author = %d
    )
    ORDER BY p.post_parent, p.ID",
    $trainer_id
));

echo "Found " . count($attendees) . " attendees:\n";
foreach ($attendees as $attendee) {
    echo "  - ID: {$attendee->attendee_id}, Event: {$attendee->event_id}, TEC Price: {$attendee->tec_commerce_price}, TPP Price: {$attendee->tpp_ticket_price}\n";
}

// Now let's add price metadata to existing attendees
echo "\n=== 2. Adding Price Metadata to Attendees ===\n";
$ticket_price = 95.00; // Standard ticket price for HVAC training

foreach ($attendees as $attendee) {
    $attendee_id = $attendee->attendee_id;
    $event_id = $attendee->event_id;
    
    // Force add price metadata regardless of current state (to fix the revenue issue)
    $post = get_post($attendee_id);
    
    if ($post->post_type === 'tribe_tpp_attendees') {
        // For Tribe PayPal attendees, set multiple price fields
        update_post_meta($attendee_id, '_tribe_tpp_ticket_price', $ticket_price);
        update_post_meta($attendee_id, '_tribe_tpp_price', $ticket_price);
        update_post_meta($attendee_id, '_paid_price', $ticket_price);
        echo "  ✓ FORCE ADDED TPP price metadata ($ticket_price) to attendee ID: {$attendee_id}\n";
    } elseif ($post->post_type === 'tec_tc_attendee') {
        // For TEC Commerce attendees
        update_post_meta($attendee_id, '_tec_tickets_commerce_price_paid', $ticket_price);
        echo "  ✓ FORCE ADDED TEC Commerce price metadata ($ticket_price) to attendee ID: {$attendee_id}\n";
    } else {
        echo "  - Unknown post type: {$post->post_type} for attendee ID: {$attendee_id}\n";
    }
}

// Test the revenue calculation
echo "\n=== 3. Testing Revenue Calculation ===\n";
require_once ABSPATH . 'wp-content/plugins/hvac-community-events/includes/class-hvac-dashboard-data.php';
$dashboard_data = new HVAC_Dashboard_Data($trainer_id);

$total_revenue = $dashboard_data->get_total_revenue();
$total_tickets = $dashboard_data->get_total_tickets_sold();

echo "Total Tickets Sold: {$total_tickets}\n";
echo "Total Revenue: $" . number_format($total_revenue, 2) . "\n";

if ($total_revenue > 0) {
    echo "✅ SUCCESS: Revenue calculation is working!\n";
} else {
    echo "❌ ISSUE: Revenue is still $0.00\n";
    
    // Let's debug the revenue query
    echo "\n=== Revenue Debug Query ===\n";
    
    // TEC Commerce revenue
    $tec_commerce_revenue = $wpdb->get_var($wpdb->prepare(
        "SELECT SUM(CAST(pm_price.meta_value AS DECIMAL(10,2))) 
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm_event ON p.ID = pm_event.post_id AND pm_event.meta_key = '_tec_tickets_commerce_event'
        INNER JOIN {$wpdb->postmeta} pm_price ON p.ID = pm_price.post_id AND pm_price.meta_key = '_tec_tickets_commerce_price_paid'
        WHERE p.post_type = %s 
        AND pm_event.meta_value IN (
            SELECT ID FROM {$wpdb->posts} 
            WHERE post_type = %s 
            AND post_author = %d 
            AND post_status IN ('publish', 'private')
        )",
        'tec_tc_attendee',
        'tribe_events',
        $trainer_id
    ));
    
    // Legacy Tribe PayPal revenue
    $tribe_tpp_revenue = $wpdb->get_var($wpdb->prepare(
        "SELECT SUM(
            CASE 
                WHEN pm_price1.meta_value IS NOT NULL THEN CAST(pm_price1.meta_value AS DECIMAL(10,2))
                WHEN pm_price2.meta_value IS NOT NULL THEN CAST(pm_price2.meta_value AS DECIMAL(10,2))
                WHEN pm_price3.meta_value IS NOT NULL THEN CAST(pm_price3.meta_value AS DECIMAL(10,2))
                ELSE 0
            END
        ) 
        FROM {$wpdb->posts} p
        INNER JOIN {$wpdb->postmeta} pm_event ON p.ID = pm_event.post_id AND pm_event.meta_key = '_tribe_tpp_event'
        LEFT JOIN {$wpdb->postmeta} pm_price1 ON p.ID = pm_price1.post_id AND pm_price1.meta_key = '_tribe_tpp_ticket_price'
        LEFT JOIN {$wpdb->postmeta} pm_price2 ON p.ID = pm_price2.post_id AND pm_price2.meta_key = '_paid_price'
        LEFT JOIN {$wpdb->postmeta} pm_price3 ON p.ID = pm_price3.post_id AND pm_price3.meta_key = '_tribe_tpp_price'
        WHERE p.post_type = %s 
        AND pm_event.meta_value IN (
            SELECT ID FROM {$wpdb->posts} 
            WHERE post_type = %s 
            AND post_author = %d 
            AND post_status IN ('publish', 'private')
        )",
        'tribe_tpp_attendees',
        'tribe_events',
        $trainer_id
    ));
    
    echo "TEC Commerce Revenue: $" . number_format(($tec_commerce_revenue ?: 0), 2) . "\n";
    echo "Tribe TPP Revenue: $" . number_format(($tribe_tpp_revenue ?: 0), 2) . "\n";
}

echo "\n=== Final Verification ===\n";
// Re-check attendees after adding price data
$updated_attendees = $wpdb->get_results($wpdb->prepare(
    "SELECT 
        p.ID as attendee_id,
        p.post_parent as event_id,
        pm_price1.meta_value as tec_commerce_price,
        pm_price2.meta_value as tpp_ticket_price,
        pm_price3.meta_value as tpp_price,
        pm_price4.meta_value as paid_price
    FROM {$wpdb->posts} p
    LEFT JOIN {$wpdb->postmeta} pm_price1 ON p.ID = pm_price1.post_id AND pm_price1.meta_key = '_tec_tickets_commerce_price_paid'
    LEFT JOIN {$wpdb->postmeta} pm_price2 ON p.ID = pm_price2.post_id AND pm_price2.meta_key = '_tribe_tpp_ticket_price'
    LEFT JOIN {$wpdb->postmeta} pm_price3 ON p.ID = pm_price3.post_id AND pm_price3.meta_key = '_tribe_tpp_price'
    LEFT JOIN {$wpdb->postmeta} pm_price4 ON p.ID = pm_price4.post_id AND pm_price4.meta_key = '_paid_price'
    WHERE p.post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees')
    AND p.post_parent IN (
        SELECT ID FROM {$wpdb->posts} 
        WHERE post_type = 'tribe_events' 
        AND post_author = %d
    )
    ORDER BY p.post_parent, p.ID",
    $trainer_id
));

echo "Attendees with price data:\n";
foreach ($updated_attendees as $attendee) {
    $has_price = !empty($attendee->tec_commerce_price) || !empty($attendee->tpp_ticket_price) || !empty($attendee->tpp_price) || !empty($attendee->paid_price);
    $price_display = $attendee->tec_commerce_price ?: ($attendee->tpp_ticket_price ?: ($attendee->tpp_price ?: ($attendee->paid_price ?: 'NO PRICE')));
    echo "  - Attendee ID: {$attendee->attendee_id}, Event: {$attendee->event_id}, Price: {$price_display}\n";
}

echo "\n✅ Debug and fix completed!\n";
?>
PHPEOF

# Execute the script on the server
echo "Executing debug and fix script..."
sshpass -p "$UPSKILL_STAGING_PASS" ssh -o StrictHostKeyChecking=no $UPSKILL_STAGING_SSH_USER@$UPSKILL_STAGING_IP "cd $UPSKILL_STAGING_PATH && php ../tmp/debug-fix-attendees.php && rm ../tmp/debug-fix-attendees.php"

echo ""
echo "✅ Debug and fix completed!"
echo ""
echo "Next steps:"
echo "1. Check dashboard - revenue should now show correct amount"
echo "2. Dashboard key metrics should display in a row instead of column"
echo "3. All formatting issues should be resolved"