<?php
/**
 * Debug Certificate Reports
 * 
 * This script helps debug issues with the certificate reports page.
 * It simulates loading the template and running the queries with debug output.
 */

// Load WordPress
if (file_exists('../wordpress/wp-load.php')) {
    require_once '../wordpress/wp-load.php';
} elseif (file_exists('./wordpress/wp-load.php')) {
    require_once './wordpress/wp-load.php';
} else {
    echo "Could not find wp-load.php\n";
    exit(1);
}

// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Output header
echo "=== Certificate Reports Debug ===\n\n";

// Check if HVAC_CE_PLUGIN_DIR is defined
if (!defined('HVAC_CE_PLUGIN_DIR')) {
    echo "Error: HVAC_CE_PLUGIN_DIR is not defined. Plugin files may not be loaded correctly.\n";
    echo "Attempting to define it...\n";
    
    // Try to determine the plugin directory
    $plugin_dir = WP_PLUGIN_DIR . '/hvac-community-events/';
    if (is_dir($plugin_dir)) {
        define('HVAC_CE_PLUGIN_DIR', $plugin_dir);
        echo "Defined HVAC_CE_PLUGIN_DIR as: $plugin_dir\n";
    } else {
        echo "Error: Could not find the hvac-community-events plugin directory.\n";
        exit(1);
    }
}

// Check if HVAC_CE_PLUGIN_URL is defined
if (!defined('HVAC_CE_PLUGIN_URL')) {
    echo "Warning: HVAC_CE_PLUGIN_URL is not defined.\n";
    echo "Attempting to define it...\n";
    
    $plugin_url = plugins_url() . '/hvac-community-events/';
    define('HVAC_CE_PLUGIN_URL', $plugin_url);
    echo "Defined HVAC_CE_PLUGIN_URL as: $plugin_url\n";
}

// Check if required classes are loaded
echo "\nChecking required classes:\n";

// Certificate Manager
$manager_file = HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-manager.php';
if (file_exists($manager_file)) {
    require_once $manager_file;
    echo "✓ Certificate Manager class loaded\n";
} else {
    echo "✗ Certificate Manager class not found at: $manager_file\n";
    exit(1);
}

// Certificate Security
$security_file = HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-security.php';
if (file_exists($security_file)) {
    require_once $security_file;
    echo "✓ Certificate Security class loaded\n";
} else {
    echo "✗ Certificate Security class not found at: $security_file\n";
    exit(1);
}

// Certificate Installer
$installer_file = HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-installer.php';
if (file_exists($installer_file)) {
    require_once $installer_file;
    echo "✓ Certificate Installer class loaded\n";
} else {
    echo "✗ Certificate Installer class not found at: $installer_file\n";
    exit(1);
}

// Check database table
echo "\nChecking certificate database table:\n";
$installer = HVAC_Certificate_Installer::instance();
$table_exists = $installer->check_tables();

if ($table_exists) {
    echo "✓ Certificate table exists and has correct structure\n";
} else {
    echo "! Certificate table did not exist or was outdated. It has been created/updated.\n";
}

// Get current user ID
$current_user_id = get_current_user_id();
echo "\nCurrent user ID: $current_user_id\n";

// Get certificate manager instance
$certificate_manager = HVAC_Certificate_Manager::instance();
echo "Certificate Manager instance created\n";

// Get certificate security instance
$certificate_security = HVAC_Certificate_Security::instance();
echo "Certificate Security instance created\n";

// Get filtering parameters (simulating GET request)
$filter_event = 0;
$filter_status = 'active';
$page = 1;
$per_page = 20;

echo "\nFilter parameters:\n";
echo "- Event ID: $filter_event\n";
echo "- Status: $filter_status\n";
echo "- Page: $page\n";
echo "- Per Page: $per_page\n";

// Build filter args
$filter_args = array(
    'page' => $page,
    'per_page' => $per_page,
    'orderby' => 'date_generated',
    'order' => 'DESC',
);

// Add status filter
if ($filter_status === 'active') {
    $filter_args['revoked'] = 0;
} elseif ($filter_status === 'revoked') {
    $filter_args['revoked'] = 1;
}

// Generate the SQL for the query (debugging only)
global $wpdb;
$table_name = $wpdb->prefix . 'hvac_certificates';

// Check the SQL query
echo "\nQueries that will be executed:\n";

// Get events query (for filtering)
$events_query = new WP_Query(array(
    'post_type' => Tribe__Events__Main::POSTTYPE,
    'posts_per_page' => -1,
    'post_status' => 'publish',
    'author' => $current_user_id,
    'orderby' => 'meta_value',
    'meta_key' => '_EventStartDate',
    'order' => 'DESC',
    'fields' => 'ids'
));

$event_ids = $events_query->posts;

echo "1. WP_Query for user events (SQL):\n";
echo $events_query->request . "\n";
echo "Found " . count($event_ids) . " events for the current user\n";

// If there are no events, user can't have certificates
if (empty($event_ids)) {
    echo "\nNo events found for the current user, therefore no certificates.\n";
    exit(0);
}

// Get certificates query
echo "\n2. Certificate query:\n";
$event_ids_string = implode(',', array_map('intval', $event_ids));
echo "Event IDs: $event_ids_string\n";

// Only include revoked filter if relevant
$where_clause = "WHERE event_id IN ($event_ids_string)";
if (isset($filter_args['revoked'])) {
    $where_clause .= " AND revoked = " . intval($filter_args['revoked']);
}

$order_by = sanitize_sql_orderby('date_generated DESC');
$offset = ($filter_args['page'] - 1) * $filter_args['per_page'];
$limit_clause = "LIMIT $offset, " . $filter_args['per_page'];

$certificates_query = "SELECT * FROM $table_name $where_clause ORDER BY $order_by $limit_clause";
echo $certificates_query . "\n";

// Execute and get certificates
try {
    echo "\nExecuting certificate query...\n";
    $certificates = $wpdb->get_results($certificates_query);
    echo "Found " . count($certificates) . " certificates matching the query\n";
    
    // Get the count for pagination
    $count_query = "SELECT COUNT(*) FROM $table_name $where_clause";
    echo "\n3. Count query for pagination:\n";
    echo $count_query . "\n";
    
    try {
        $total_certificates = $wpdb->get_var($count_query);
        echo "Total certificates matching the filter: $total_certificates\n";
        $total_pages = ceil($total_certificates / $per_page);
        echo "Total pages: $total_pages\n";
    } catch (Exception $e) {
        echo "Error executing count query: " . $e->getMessage() . "\n";
    }
    
    // Get certificate statistics
    echo "\n4. Certificate statistics query:\n";
    $stats_query = "SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN revoked = 0 THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN revoked = 1 THEN 1 ELSE 0 END) as revoked,
        SUM(CASE WHEN email_sent = 1 THEN 1 ELSE 0 END) as emailed
    FROM $table_name 
    WHERE event_id IN ($event_ids_string)";
    echo $stats_query . "\n";
    
    try {
        $result = $wpdb->get_row($stats_query);
        echo "\nCertificate Statistics:\n";
        echo "- Total: " . intval($result->total) . "\n";
        echo "- Active: " . intval($result->active) . "\n";
        echo "- Revoked: " . intval($result->revoked) . "\n";
        echo "- Emailed: " . intval($result->emailed) . "\n";
    } catch (Exception $e) {
        echo "Error executing stats query: " . $e->getMessage() . "\n";
    }
    
    // Check the template file
    $template_file = HVAC_CE_PLUGIN_DIR . 'templates/certificates/template-certificate-reports.php';
    if (file_exists($template_file)) {
        echo "\n✓ Certificate reports template file exists\n";
    } else {
        echo "\n✗ Certificate reports template file not found at: $template_file\n";
    }
    
    echo "\nDebugging complete\n";
    
} catch (Exception $e) {
    echo "Error executing certificate query: " . $e->getMessage() . "\n";
}