#!/bin/bash

# Script to regenerate certificate test data on staging server
# This script should be run on the staging server

echo "=== Certificate Test Data Regeneration Script ==="
echo ""

# Check if wp-cli is available
if ! command -v wp &> /dev/null; then
    echo "Error: wp-cli is not installed or not in PATH"
    exit 1
fi

# Navigate to WordPress directory
cd /home/uberrxmprk/cloudwaysapps.com/rfymqitokx/public_html

# Get test_trainer user ID
TEST_USER_ID=$(wp user get test_trainer --field=ID 2>/dev/null)

if [ -z "$TEST_USER_ID" ]; then
    echo "Error: test_trainer user not found"
    echo "Please run ./bin/create-test-users.sh first"
    exit 1
fi

echo "Found test_trainer user (ID: $TEST_USER_ID)"
echo ""

# Get recent events
echo "Fetching recent events..."
EVENTS=$(wp db query "
    SELECT p.ID, p.post_title, 
           DATE_FORMAT(m.meta_value, '%Y-%m-%d') as event_date
    FROM wp_posts p
    JOIN wp_postmeta m ON p.ID = m.post_id AND m.meta_key = '_EventStartDate'
    WHERE p.post_type = 'tribe_events' 
    AND p.post_status = 'publish'
    ORDER BY m.meta_value DESC
    LIMIT 5
" --skip-column-names)

if [ -z "$EVENTS" ]; then
    echo "No events found. Please create some test events first."
    exit 1
fi

echo "Recent events:"
echo "$EVENTS" | nl
echo ""

read -p "Enter the event number to use for test certificates (1-5): " EVENT_NUM

EVENT_ID=$(echo "$EVENTS" | sed -n "${EVENT_NUM}p" | awk '{print $1}')
EVENT_TITLE=$(echo "$EVENTS" | sed -n "${EVENT_NUM}p" | cut -f2- -d$'\t' | cut -f1 -d$'\t')

if [ -z "$EVENT_ID" ]; then
    echo "Invalid selection"
    exit 1
fi

echo ""
echo "Selected event: $EVENT_TITLE (ID: $EVENT_ID)"
echo ""

# Get attendees for this event
echo "Fetching attendees for this event..."
ATTENDEE_COUNT=$(wp db query "
    SELECT COUNT(*) 
    FROM wp_posts 
    WHERE post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees', 'tribe_rsvp_attendees')
    AND post_parent = $EVENT_ID
" --skip-column-names)

echo "Found $ATTENDEE_COUNT attendees"

if [ "$ATTENDEE_COUNT" -eq 0 ]; then
    echo ""
    echo "No attendees found. Would you like to create test attendees?"
    read -p "Create test attendees? (y/n): " CREATE_ATTENDEES
    
    if [ "$CREATE_ATTENDEES" = "y" ]; then
        echo ""
        read -p "How many test attendees to create? (1-10): " NUM_ATTENDEES
        
        if [ "$NUM_ATTENDEES" -gt 0 ] && [ "$NUM_ATTENDEES" -le 10 ]; then
            echo "Creating $NUM_ATTENDEES test attendees..."
            
            # This is a simplified version - in reality, creating attendees is complex
            # and depends on the ticket system being used
            echo "Note: Automatic attendee creation requires the ticket system to be properly configured."
            echo "For now, please create attendees manually through the WordPress admin."
            exit 0
        fi
    fi
    exit 0
fi

echo ""
echo "Ready to generate test certificates"
echo ""
echo "Options:"
echo "1) Generate certificates for ALL attendees"
echo "2) Generate certificates for first 5 attendees only"
echo "3) Generate certificates for checked-in attendees only"
echo "4) Exit without generating"
echo ""
read -p "Enter your choice (1-4): " GEN_CHOICE

case $GEN_CHOICE in
    1)
        ATTENDEE_IDS=$(wp db query "
            SELECT ID 
            FROM wp_posts 
            WHERE post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees', 'tribe_rsvp_attendees')
            AND post_parent = $EVENT_ID
        " --skip-column-names)
        ;;
    2)
        ATTENDEE_IDS=$(wp db query "
            SELECT ID 
            FROM wp_posts 
            WHERE post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees', 'tribe_rsvp_attendees')
            AND post_parent = $EVENT_ID
            LIMIT 5
        " --skip-column-names)
        ;;
    3)
        ATTENDEE_IDS=$(wp db query "
            SELECT p.ID 
            FROM wp_posts p
            JOIN wp_postmeta m ON p.ID = m.post_id 
            WHERE p.post_type IN ('tec_tc_attendee', 'tribe_tpp_attendees', 'tribe_rsvp_attendees')
            AND p.post_parent = $EVENT_ID
            AND m.meta_key = '_tribe_tickets_attendee_checked_in'
            AND m.meta_value = '1'
        " --skip-column-names)
        ;;
    4)
        echo "Exiting without generating certificates."
        exit 0
        ;;
    *)
        echo "Invalid choice"
        exit 1
        ;;
esac

if [ -z "$ATTENDEE_IDS" ]; then
    echo "No attendees found matching criteria"
    exit 0
fi

ATTENDEE_COUNT=$(echo "$ATTENDEE_IDS" | wc -l)
echo ""
echo "Generating certificates for $ATTENDEE_COUNT attendees..."
echo ""

# Generate certificates using WP-CLI eval-file
cat > /tmp/generate_certs.php << 'EOF'
<?php
// Load certificate generator
require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-generator.php';
$generator = HVAC_Certificate_Generator::instance();

$event_id = $args[0];
$attendee_ids = explode("\n", trim($args[1]));
$generated_by = $args[2];

$success = 0;
$failed = 0;

foreach ($attendee_ids as $attendee_id) {
    if (empty($attendee_id)) continue;
    
    $result = $generator->generate_certificate($event_id, $attendee_id, array(), $generated_by);
    
    if ($result) {
        $success++;
        echo "✓ Generated certificate for attendee $attendee_id\n";
    } else {
        $failed++;
        echo "✗ Failed to generate certificate for attendee $attendee_id\n";
    }
}

echo "\nSummary:\n";
echo "Successful: $success\n";
echo "Failed: $failed\n";
EOF

wp eval-file /tmp/generate_certs.php "$EVENT_ID" "$ATTENDEE_IDS" "$TEST_USER_ID"

rm -f /tmp/generate_certs.php

echo ""
echo "=== Certificate Generation Complete ==="
echo ""
echo "To view the generated certificates:"
echo "1. Log in as test_trainer"
echo "2. Navigate to Certificate Reports page"
echo "3. Or check the uploads directory at:"
echo "   /wp-content/uploads/hvac-certificates/"