#!/bin/bash

# Test event queries on staging

# Get absolute path to this script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Navigate to wordpress-dev directory
cd "$(dirname "$SCRIPT_DIR")" || exit 1

# Load environment variables
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at: $ENV_FILE"
    exit 1
fi

source "$ENV_FILE"

echo "=== Testing Event Queries ==="
echo "Remote host: $UPSKILL_STAGING_IP"
echo "==============================="

# Test query
sshpass -p "${UPSKILL_STAGING_PASS}" ssh -o StrictHostKeyChecking=no "${UPSKILL_STAGING_SSH_USER}@${UPSKILL_STAGING_IP}" <<'EOF'
cd /home/974670.cloudwaysapps.com/uberrxmprk/public_html

# Create PHP test script
cat > test-query.php << 'PHP'
<?php
require_once 'wp-load.php';

// Check post type constant
echo "Post type constant: " . Tribe__Events__Main::POSTTYPE . "\n";

// Test 1: Direct query with WP_Query
echo "\nTest 1: WP_Query with author=17\n";
$args = array(
    'post_type' => Tribe__Events__Main::POSTTYPE,
    'author' => 17,
    'post_status' => 'any',
    'posts_per_page' => -1,
    'fields' => 'ids'
);
$query = new WP_Query($args);
echo "Found posts: " . $query->found_posts . "\n";
var_dump($query->posts);

// Test 2: get_posts
echo "\nTest 2: get_posts with author=17\n";
$events = get_posts($args);
echo "Found events: " . count($events) . "\n";

// Test 3: Direct DB query
echo "\nTest 3: Direct DB query\n";
global $wpdb;
$results = $wpdb->get_results("SELECT ID, post_title, post_author FROM {$wpdb->posts} WHERE post_type='tribe_events' AND post_author=17");
echo "Found in DB: " . count($results) . "\n";
foreach ($results as $r) {
    echo "ID: {$r->ID}, Title: {$r->post_title}\n";
}

// Test 4: Check plugin active
echo "\nTest 4: Plugin status\n";
echo "TEC Active: " . (class_exists('Tribe__Events__Main') ? 'Yes' : 'No') . "\n";
echo "Post type registered: " . (post_type_exists('tribe_events') ? 'Yes' : 'No') . "\n";

// Test 5: Clear cache and try again
echo "\nTest 5: Clearing cache\n";
wp_cache_flush();
$query2 = new WP_Query($args);
echo "After cache clear - Found posts: " . $query2->found_posts . "\n";
PHP

php test-query.php
rm test-query.php
EOF

echo "Test completed!"