<?php
/**
 * FINAL PLUGIN TEST - Tests everything from scratch
 * This file tests all core functionality step by step
 */

// Bootstrap WordPress
$wp_load_path = dirname(__FILE__) . '/../../../../wp-load.php';

if (!file_exists($wp_load_path)) {
    die('ERROR: WordPress not found. Please run this from a WordPress site.');
}

require_once $wp_load_path;

// Prevent caching
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Type: text/html; charset=' . get_option('blog_charset'));

?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Final Plugin Test</title>
<style>
* { box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; 
       max-width: 900px; margin: 0 auto; padding: 20px; background: #f1f1f1; }
h1 { background: #23282d; color: white; padding: 20px; margin: -20px -20px 20px; border-radius: 0; }
h2 { color: #23282d; border-bottom: 2px solid #0073aa; padding-bottom: 10px; }
.test-section { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.pass { background: #d4edda; color: #155724; padding: 10px; border-radius: 4px; margin: 5px 0; border-left: 4px solid #28a745; }
.fail { background: #f8d7da; color: #721c24; padding: 10px; border-radius: 4px; margin: 5px 0; border-left: 4px solid #dc3545; }
.info { background: #cce5ff; color: #004085; padding: 10px; border-radius: 4px; margin: 5px 0; border-left: 4px solid #0073aa; }
pre { background: #f8f9fa; padding: 10px; overflow-x: auto; border-radius: 4px; font-size: 12px; }
.summary { background: #23282d; color: white; padding: 30px; margin: 30px -20px -20px; text-align: center; border-radius: 0 0 5px 5px; }
.summary h2 { color: white; border: none; }
.pass-all { color: #28a745; font-size: 24px; }
.fail-any { color: #dc3545; font-size: 24px; }
table { width: 100%; border-collapse: collapse; margin: 10px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background: #f5f5f5; }
</style>
</head>
<body <?php body_class(); ?>>
<h1>Headers & Footers Plugin - Complete Test</h1>

<?php
$results = array();
$all_pass = true;
$test_start = microtime(true);

// ==========================================
// STEP 1: Check if WordPress loaded
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 1: WordPress Environment</h2>';

$wp_version = get_bloginfo('version');
$php_version = PHP_VERSION;
$wp_url = get_bloginfo('url');
$wp_admin_url = admin_url();

echo '<table>';
echo '<tr><th>Component</th><th>Status</th></tr>';
echo '<tr><td>WordPress Version</td><td>' . $wp_version . '</td></tr>';
echo '<tr><td>PHP Version</td><td>' . $php_version . '</td></tr>';
echo '<tr><td>Site URL</td><td>' . $wp_url . '</td></tr>';
echo '</table>';

if (defined('ABSPATH')) {
    echo '<p class="pass">ABSPATH defined: ' . ABSPATH . '</p>';
} else {
    echo '<p class="fail">ABSPATH not defined!</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 2: Check plugin files
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 2: Plugin Files</h2>';

$plugin_file = plugin_dir_path(__FILE__) . 'pc-headers-and-footers-and-ad-pixels-5ake.php';
$admin_file = dirname(__FILE__) . '/admin/class-admin.php';
$database_file = dirname(__FILE__) . '/includes/class-database.php';
$snippet_file = dirname(__FILE__) . '/includes/class-snippet.php';
$public_file = dirname(__FILE__) . '/public/class-public.php';

$files = array(
    'Main plugin' => $plugin_file,
    'Admin class' => $admin_file,
    'Database class' => $database_file,
    'Snippet class' => $snippet_file,
    'Public class' => $public_file,
);

foreach ($files as $name => $path) {
    if (file_exists($path)) {
        $size = filesize($path);
        echo "<p class='pass'>✓ $name ($size bytes)</p>";
    } else {
        echo "<p class='fail'>✗ $name NOT FOUND</p>";
        $all_pass = false;
    }
}

echo '</div>';

// ==========================================
// STEP 3: Include and test classes
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 3: Load Plugin Classes</h2>';

// Include classes
try {
    require_once $database_file;
    echo '<p class="info">Including class-database.php...</p>';
    
    require_once $snippet_file;
    echo '<p class="info">Including class-snippet.php...</p>';
    
    echo '<p class="pass">✓ All classes included successfully</p>';
} catch (Exception $e) {
    echo '<p class="fail">✗ Include error: ' . $e->getMessage() . '</p>';
    $all_pass = false;
}

// Check classes exist
if (class_exists('PC_HFAP_Database')) {
    echo '<p class="pass">✓ PC_HFAP_Database class exists</p>';
} else {
    echo '<p class="fail">✗ PC_HFAP_Database class not found</p>';
    $all_pass = false;
}

if (class_exists('PC_HFAP_Snippet')) {
    echo '<p class="pass">✓ PC_HFAP_Snippet class exists</p>';
} else {
    echo '<p class="fail">✗ PC_HFAP_Snippet class not found</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 4: Test database table
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 4: Database Table</h2>';

global $wpdb;

try {
    // Create tables
    PC_HFAP_Database::create_tables();
    
    // Get table name
    $table_name = PC_HFAP_Database::get_table_name();
    
    echo '<p class="info">Table name: ' . $table_name . '</p>';
    
    // Check if table exists
    $table_check = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));
    
    if ($table_name === $table_check) {
        echo '<p class="pass">✓ Table exists: ' . $table_name . '</p>';
        
        // Get table structure
        $columns = $wpdb->get_results("DESCRIBE $table_name", ARRAY_A);
        echo '<p>Table structure:</p>';
        echo '<table><tr><th>Column</th><th>Type</th></tr>';
        foreach ($columns as $col) {
            echo '<tr><td>' . $col['Field'] . '</td><td>' . $col['Type'] . '</td></tr>';
        }
        echo '</table>';
        
        // Count existing
        $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
        echo '<p class="info">Current snippets: ' . $count . '</p>';
        
    } else {
        echo '<p class="fail">✗ Table does NOT exist!</p>';
        $all_pass = false;
    }
} catch (Exception $e) {
    echo '<p class="fail">✗ Database error: ' . $e->getMessage() . '</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 5: Test CREATE operation
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 5: Create Snippet</h2>';

$test_snippet_id = 0;
$test_title = 'Test Snippet ' . date('Y-m-d H:i:s');

try {
    $data = array(
        'title' => $test_title,
        'location' => 'header',
        'code' => '<!-- Test header code -->'
    );
    
    $snippet = new PC_HFAP_Snippet($data);
    $result = $snippet->save();
    
    if ($result) {
        $test_snippet_id = $result;
        echo '<p class="pass">✓ Snippet created with ID: ' . $result . '</p>';
        echo '<p>Title: ' . htmlspecialchars($test_title) . '</p>';
    } else {
        echo '<p class="fail">✗ Failed to create snippet</p>';
        echo '<p>Error: ' . $wpdb->last_error . '</p>';
        $all_pass = false;
    }
} catch (Exception $e) {
    echo '<p class="fail">✗ Create error: ' . $e->getMessage() . '</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 6: Test READ operation
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 6: Read Snippet</h2>';

if ($test_snippet_id > 0) {
    try {
        $snippet = PC_HFAP_Snippet::get_by_id($test_snippet_id);
        
        if ($snippet) {
            echo '<p class="pass">✓ Snippet retrieved successfully</p>';
            echo '<table>';
            echo '<tr><td>ID</td><td>' . $snippet->get_id() . '</td></tr>';
            echo '<tr><td>Title</td><td>' . htmlspecialchars($snippet->get_title()) . '</td></tr>';
            echo '<tr><td>Location</td><td>' . $snippet->get_location() . '</td></tr>';
            echo '<tr><td>Code</td><td><code>' . htmlspecialchars($snippet->get_code()) . '</code></td></tr>';
            echo '</table>';
        } else {
            echo '<p class="fail">✗ Snippet not found!</p>';
            $all_pass = false;
        }
    } catch (Exception $e) {
        echo '<p class="fail">✗ Read error: ' . $e->getMessage() . '</p>';
        $all_pass = false;
    }
} else {
    echo '<p class="fail">✗ Skipped (no test snippet)</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 7: Test UPDATE operation
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 7: Update Snippet</h2>';

if ($test_snippet_id > 0) {
    try {
        $snippet = PC_HFAP_Snippet::get_by_id($test_snippet_id);
        
        if ($snippet) {
            $new_title = 'Updated ' . date('Y-m-d H:i:s');
            $new_code = '<style>/* Updated CSS */</style>';
            
            $snippet->set_title($new_title);
            $snippet->set_code($new_code);
            $update_result = $snippet->save();
            
            if ($update_result !== false) {
                // Verify update
                $updated = PC_HFAP_Snippet::get_by_id($test_snippet_id);
                
                if ($updated->get_title() === $new_title) {
                    echo '<p class="pass">✓ Title updated successfully</p>';
                } else {
                    echo '<p class="fail">✗ Title not updated</p>';
                    $all_pass = false;
                }
                
                if ($updated->get_code() === $new_code) {
                    echo '<p class="pass">✓ Code updated successfully</p>';
                } else {
                    echo '<p class="fail">✗ Code not updated</p>';
                    $all_pass = false;
                }
            } else {
                echo '<p class="fail">✗ Update failed</p>';
                echo '<p>Error: ' . $wpdb->last_error . '</p>';
                $all_pass = false;
            }
        } else {
            echo '<p class="fail">✗ Snippet not found for update</p>';
            $all_pass = false;
        }
    } catch (Exception $e) {
        echo '<p class="fail">✗ Update error: ' . $e->getMessage() . '</p>';
        $all_pass = false;
    }
} else {
    echo '<p class="fail">✗ Skipped (no test snippet)</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 8: Test get_all()
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 8: Get All Snippets</h2>';

try {
    $snippets = PC_HFAP_Snippet::get_all();
    
    echo '<p class="pass">✓ get_all() returned ' . count($snippets) . ' snippet(s)</p>';
    
    if (!empty($snippets)) {
        echo '<table><tr><th>ID</th><th>Title</th><th>Location</th></tr>';
        foreach ($snippets as $s) {
            echo '<tr>';
            echo '<td>' . $s->get_id() . '</td>';
            echo '<td>' . htmlspecialchars($s->get_title()) . '</td>';
            echo '<td>' . $s->get_location() . '</td>';
            echo '</tr>';
        }
        echo '</table>';
    }
} catch (Exception $e) {
    echo '<p class="fail">✗ get_all() error: ' . $e->getMessage() . '</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 9: Test location methods
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 9: Location Methods</h2>';

try {
    $headers = PC_HFAP_Snippet::get_headers();
    $bodies = PC_HFAP_Snippet::get_bodies();
    $footers = PC_HFAP_Snippet::get_footers();
    
    echo '<p class="pass">✓ get_headers(): ' . count($headers) . ' snippets</p>';
    echo '<p class="pass">✓ get_bodies(): ' . count($bodies) . ' snippets</p>';
    echo '<p class="pass">✓ get_footers(): ' . count($footers) . ' snippets</p>';
} catch (Exception $e) {
    echo '<p class="fail">✗ Location error: ' . $e->getMessage() . '</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// STEP 10: Test DELETE operation
// ==========================================
echo '<div class="test-section">';
echo '<h2>Step 10: Delete Snippet</h2>';

if ($test_snippet_id > 0) {
    try {
        $snippet = PC_HFAP_Snippet::get_by_id($test_snippet_id);
        
        if ($snippet) {
            $delete_result = $snippet->delete();
            
            if ($delete_result) {
                // Verify deletion
                $deleted = PC_HFAP_Snippet::get_by_id($test_snippet_id);
                
                if (!$deleted) {
                    echo '<p class="pass">✓ Snippet deleted successfully</p>';
                } else {
                    echo '<p class="fail">✗ Snippet still exists after delete</p>';
                    $all_pass = false;
                }
            } else {
                echo '<p class="fail">✗ Delete operation returned false</p>';
                echo '<p>Error: ' . $wpdb->last_error . '</p>';
                $all_pass = false;
            }
        } else {
            echo '<p class="fail">✗ Snippet not found for delete</p>';
            $all_pass = false;
        }
    } catch (Exception $e) {
        echo '<p class="fail">✗ Delete error: ' . $e->getMessage() . '</p>';
        $all_pass = false;
    }
} else {
    echo '<p class="fail">✗ Skipped (no test snippet)</p>';
    $all_pass = false;
}

echo '</div>';

// ==========================================
// FINAL SUMMARY
// ==========================================
$test_end = microtime(true);
$duration = round(($test_end - $test_start) * 1000, 2);

echo '<div class="summary">';
echo '<h2>FINAL RESULT</h2>';
echo '<p>Test completed in ' . $duration . 'ms</p>';

if ($all_pass) {
    echo '<p class="pass-all">✓ ALL TESTS PASSED!</p>';
    echo '<p>The plugin is working correctly.</p>';
} else {
    echo '<p class="fail-any">✗ SOME TESTS FAILED</p>';
    echo '<p>Please review the errors above.</p>';
}

echo '</div>';

// ==========================================
// NEXT STEPS
// ==========================================
echo '<div class="test-section">';
echo '<h2>Next Steps</h2>';
echo '<ul>';
echo '<li><a href="' . admin_url('admin.php?page=pc-hfap-snippets') . '">Go to Snippets Admin Page</a></li>';
echo '<li><a href="' . admin_url('admin.php?page=pc-hfap-add-snippet') . '">Add New Snippet</a></li>';
echo '<li><a href="' . home_url() . '">View Your Site</a></li>';
echo '</ul>';

echo '<h3>Troubleshooting</h3>';
echo '<ul>';
echo '<li>If tests failed, check WordPress debug log</li>';
echo '<li>Ensure plugin is properly uploaded</li>';
echo '<li>Try deactivating and reactivating the plugin</li>';
echo '</ul>';
echo '</div>';

echo '</body></html>';
