<?php
/**
 * Final Verification Script
 * Tests all plugin functionality comprehensively
 */

// Include WordPress
require_once dirname(__FILE__) . '/../../../../wp-load.php';

header('Content-Type: text/html; charset=UTF-8');

echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Plugin Verification</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; max-width: 1200px; }
        .pass { color: green; font-weight: bold; }
        .fail { color: red; font-weight: bold; }
        .skip { color: orange; }
        h2 { color: #333; border-bottom: 2px solid #0073aa; padding-bottom: 10px; }
        .test-section { background: #f9f9f9; padding: 15px; margin: 10px 0; border-radius: 5px; border: 1px solid #ddd; }
        pre { background: #f0f0f0; padding: 10px; overflow-x: auto; border-radius: 3px; }
        .summary { background: #0073aa; color: white; padding: 20px; border-radius: 5px; margin-top: 20px; }
    </style>
</head>
<body>
<h1>Headers & Footers Plugin - Final Verification</h1>
<p>Date: ' . date('Y-m-d H:i:s') . '</p>
<p>PHP Version: ' . PHP_VERSION . '</p>';

$results = array();
$all_passed = true;

// ============================================
// TEST 1: Plugin Files Exist
// ============================================
echo '<div class="test-section">';
echo '<h2>TEST 1: Plugin Files Verification</h2>';

$required_files = array(
    'pc-headers-and-footers-and-ad-pixels-5ake.php',
    'includes/class-database.php',
    'includes/class-snippet.php',
    'admin/class-admin.php',
    'public/class-public.php'
);

foreach ($required_files as $file) {
    $full_path = dirname(__FILE__) . '/' . $file;
    if (file_exists($full_path)) {
        echo '<p class="pass">✓ ' . $file . ' exists (' . filesize($full_path) . ' bytes)</p>';
    } else {
        echo '<p class="fail">✗ ' . $file . ' NOT FOUND</p>';
        $all_passed = false;
    }
}
echo '</div>';

// ============================================
// TEST 2: Plugin Constants
// ============================================
echo '<div class="test-section">';
echo '<h2>TEST 2: Plugin Constants</h2>';

$constants = array(
    'PC_HFAP_VERSION',
    'PC_HFAP_PLUGIN_DIR',
    'PC_HFAP_PLUGIN_URL',
    'PC_HFAP_PLUGIN_BASENAME'
);

foreach ($constants as $const) {
    if (defined($const)) {
        $value = constant($const);
        if (strlen($value) > 50) {
            $value = substr($value, 0, 50) . '...';
        }
        echo '<p class="pass">✓ ' . $const . ' = ' . htmlspecialchars($value) . '</p>';
    } else {
        echo '<p class="fail">✗ ' . $const . ' NOT DEFINED</p>';
        $all_passed = false;
    }
}
echo '</div>';

// ============================================
// TEST 3: Database Table
// ============================================
echo '<div class="test-section">';
echo '<h2>TEST 3: Database Table</h2>';

try {
    PC_HFAP_Database::create_tables();
    global $wpdb;
    $table_name = PC_HFAP_Database::get_table_name();
    $table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table_name));
    
    if ($table_name === $table_exists) {
        echo '<p class="pass">✓ Table exists: ' . $table_name . '</p>';
        
        // Check table structure
        $columns = $wpdb->get_results("DESCRIBE $table_name", ARRAY_A);
        echo '<p>Table Structure:</p>';
        echo '<table border="1" cellpadding="5">';
        echo '<tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th><th>Default</th></tr>';
        foreach ($columns as $col) {
            echo '<tr>';
            echo '<td>' . $col['Field'] . '</td>';
            echo '<td>' . $col['Type'] . '</td>';
            echo '<td>' . $col['Null'] . '</td>';
            echo '<td>' . ($col['Key'] ? $col['Key'] : '-') . '</td>';
            echo '<td>' . ($col['Default'] ? $col['Default'] : 'NULL') . '</td>';
            echo '</tr>';
        }
        echo '</table>';
        
        // Count existing snippets
        $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
        echo '<p>Current snippets: ' . $count . '</p>';
    } else {
        echo '<p class="fail">✗ Table does NOT exist!</p>';
        $all_passed = false;
    }
} catch (Exception $e) {
    echo '<p class="fail">✗ Database error: ' . $e->getMessage() . '</p>';
    $all_passed = false;
}
echo '</div>';

// ============================================
// TEST 4: CRUD Operations
// ============================================
echo '<div class="test-section">';
echo '<h2>TEST 4: CRUD Operations</h2>';

$test_results = array();

// CREATE
echo '<h3>Create Snippet</h3>';
try {
    $data = array(
        'title' => 'Verification Test - ' . time(),
        'location' => 'header',
        'code' => '<script>console.log("Test snippet created at ' . date('Y-m-d H:i:s') . '");</script>'
    );
    
    $snippet = new PC_HFAP_Snippet($data);
    $insert_id = $snippet->save();
    
    if ($insert_id) {
        echo '<p class="pass">✓ Snippet created with ID: ' . $insert_id . '</p>';
        $test_results['create'] = $insert_id;
    } else {
        echo '<p class="fail">✗ Failed to create snippet</p>';
        echo '<p>Error: ' . $wpdb->last_error . '</p>';
        $all_passed = false;
        $test_results['create'] = false;
    }
} catch (Exception $e) {
    echo '<p class="fail">✗ Create error: ' . $e->getMessage() . '</p>';
    $all_passed = false;
    $test_results['create'] = false;
}

// READ
echo '<h3>Read Snippet</h3>';
if ($test_results['create']) {
    try {
        $retrieved = PC_HFAP_Snippet::get_by_id($test_results['create']);
        
        if ($retrieved && $retrieved->get_id()) {
            echo '<p class="pass">✓ Snippet retrieved successfully</p>';
            echo '<ul>';
            echo '<li>ID: ' . $retrieved->get_id() . '</li>';
            echo '<li>Title: ' . esc_html($retrieved->get_title()) . '</li>';
            echo '<li>Location: ' . $retrieved->get_location() . '</li>';
            echo '<li>Code length: ' . strlen($retrieved->get_code()) . ' chars</li>';
            echo '</ul>';
            $test_results['read'] = true;
        } else {
            echo '<p class="fail">✗ Failed to retrieve snippet</p>';
            $all_passed = false;
            $test_results['read'] = false;
        }
    } catch (Exception $e) {
        echo '<p class="fail">✗ Read error: ' . $e->getMessage() . '</p>';
        $all_passed = false;
        $test_results['read'] = false;
    }
} else {
    echo '<p class="skip">⚠ Skipped (create failed)</p>';
    $test_results['read'] = false;
}

// UPDATE
echo '<h3>Update Snippet</h3>';
if ($test_results['create']) {
    try {
        $snippet = PC_HFAP_Snippet::get_by_id($test_results['create']);
        
        if ($snippet) {
            $new_title = 'Updated Title - ' . time();
            $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_results['create']);
                if ($updated->get_title() === $new_title) {
                    echo '<p class="pass">✓ Snippet updated successfully</p>';
                    $test_results['update'] = true;
                } else {
                    echo '<p class="fail">✗ Title mismatch after update</p>';
                    $all_passed = false;
                    $test_results['update'] = false;
                }
            } else {
                echo '<p class="fail">✗ Update failed</p>';
                echo '<p>Error: ' . $wpdb->last_error . '</p>';
                $all_passed = false;
                $test_results['update'] = false;
            }
        } else {
            echo '<p class="fail">✗ Snippet not found for update</p>';
            $all_passed = false;
            $test_results['update'] = false;
        }
    } catch (Exception $e) {
        echo '<p class="fail">✗ Update error: ' . $e->getMessage() . '</p>';
        $all_passed = false;
        $test_results['update'] = false;
    }
} else {
    echo '<p class="skip">⚠ Skipped (create failed)</p>';
    $test_results['update'] = false;
}

// DELETE
echo '<h3>Delete Snippet</h3>';
if ($test_results['create']) {
    try {
        $snippet = PC_HFAP_Snippet::get_by_id($test_results['create']);
        
        if ($snippet) {
            $delete_result = $snippet->delete();
            
            if ($delete_result) {
                // Verify deletion
                $deleted = PC_HFAP_Snippet::get_by_id($test_results['create']);
                if (!$deleted) {
                    echo '<p class="pass">✓ Snippet deleted successfully</p>';
                    $test_results['delete'] = true;
                } else {
                    echo '<p class="fail">✗ Snippet still exists after delete</p>';
                    $all_passed = false;
                    $test_results['delete'] = false;
                }
            } else {
                echo '<p class="fail">✗ Delete operation failed</p>';
                echo '<p>Error: ' . $wpdb->last_error . '</p>';
                $all_passed = false;
                $test_results['delete'] = false;
            }
        } else {
            echo '<p class="fail">✗ Snippet not found for delete</p>';
            $all_passed = false;
            $test_results['delete'] = false;
        }
    } catch (Exception $e) {
        echo '<p class="fail">✗ Delete error: ' . $e->getMessage() . '</p>';
        $all_passed = false;
        $test_results['delete'] = false;
    }
} else {
    echo '<p class="skip">⚠ Skipped (create failed)</p>';
    $test_results['delete'] = false;
}

echo '</div>';

// ============================================
// TEST 5: WordPress Hooks
// ============================================
echo '<div class="test-section">';
echo '<h2>TEST 5: WordPress Hooks</h2>';

// Check if admin class is instantiated
global $pc_hfap_admin;
if (isset($pc_hfap_admin) || class_exists('PC_HFAP_Admin')) {
    echo '<p class="pass">✓ PC_HFAP_Admin class exists</p>';
    
    // Check menu registration
    global $menu;
    $menu_found = false;
    foreach ($menu as $item) {
        if (strpos($item[0], 'Headers & Footers') !== false) {
            echo '<p class="pass">✓ Admin menu item found: ' . $item[0] . '</p>';
            $menu_found = true;
            break;
        }
    }
    if (!$menu_found) {
        echo '<p class="skip">⚠ Admin menu item not found in global $menu (may be hidden)</p>';
    }
} else {
    echo '<p class="skip">⚠ Admin class not instantiated (may be in admin only)</p>';
}

// Check public hooks
$hooks_to_check = array(
    'wp_head',
    'wp_body_open', 
    'wp_footer',
    'wp_enqueue_scripts'
);

echo '<p>Public hooks registered:</p>';
foreach ($hooks_to_check as $hook) {
    $callbacks = $wp_filter[$hook] ?? array();
    $found = false;
    foreach ($callbacks as $priority => $callbacks_list) {
        foreach ($callbacks_list as $callback) {
            if (is_array($callback[0] ?? null) && 
                strpos(get_class($callback[0][0] ?? ''), 'PC_HFAP') !== false) {
                echo '<p class="pass">✓ ' . $hook . ' has PC_HFAP callback</p>';
                $found = true;
                break 2;
            }
        }
    }
    if (!$found) {
        echo '<p class="skip">⚠ ' . $hook . ' - PC_HFAP callback not detected (may be normal)</p>';
    }
}

echo '</div>';

// ============================================
// TEST 6: Code with Special Characters
// ============================================
echo '<div class="test-section">';
echo '<h2>TEST 6: Special Character Handling</h2>';

$special_tests = array(
    'JavaScript' => '<script>alert("Hello World");</script>',
    'CSS' => '<style>.class { color: #ff0000; }</style>',
    'HTML Comment' => '<!-- This is a comment -->',
    'Quotes' => '<div onclick="test(\'quote\')">Test</div>',
    'Unicode' => '<p>Héllo Wörld 你好</p>',
    'Ampersand' => '<p>Coffee & Tea</p>',
);

foreach ($special_tests as $type => $code) {
    $data = array(
        'title' => 'Special Chars Test - ' . $type,
        'location' => 'header',
        'code' => $code
    );
    
    $snippet = new PC_HFAP_Snippet($data);
    $insert_id = $snippet->save();
    
    if ($insert_id) {
        $retrieved = PC_HFAP_Snippet::get_by_id($insert_id);
        
        if ($retrieved && $retrieved->get_code() === $code) {
            echo '<p class="pass">✓ ' . $type . ' - preserved correctly</p>';
        } else {
            echo '<p class="fail">✗ ' . $type . ' - code mismatch</p>';
            echo '<pre>Expected: ' . htmlspecialchars($code) . '</pre>';
            echo '<pre>Got: ' . htmlspecialchars($retrieved->get_code() ?? 'NULL') . '</pre>';
            $all_passed = false;
        }
        
        // Clean up
        $retrieved->delete();
    } else {
        echo '<p class="fail">✗ ' . $type . ' - insert failed</p>';
        $all_passed = false;
    }
}

echo '</div>';

// ============================================
// TEST 7: Admin Form Simulation
// ============================================
echo '<div class="test-section">';
echo '<h2>TEST 7: Admin Form Simulation</h2>';

$form_data = array(
    'pc_hfap_title' => 'Form Test Snippet ' . time(),
    'pc_hfap_location' => 'footer',
    'pc_hfap_code' => '<script>console.log("Form test");</script>',
    'pc_hfap_nonce' => wp_create_nonce('pc_hfap_save_snippet'),
    'submit_snippet' => '1'
);

echo '<p>Simulating form submission with:</p>';
echo '<ul>';
echo '<li>Title: ' . $form_data['pc_hfap_title'] . '</li>';
echo '<li>Location: ' . $form_data['pc_hfap_location'] . '</li>';
echo '<li>Code: ' . htmlspecialchars($form_data['pc_hfap_code']) . '</li>';
echo '</ul>';

// Verify nonce
if (wp_verify_nonce($form_data['pc_hfap_nonce'], 'pc_hfap_save_snippet')) {
    echo '<p class="pass">✓ Nonce verification: PASSED</p>';
    
    // Create snippet
    $data = array(
        'title' => sanitize_text_field($form_data['pc_hfap_title']),
        'location' => in_array($form_data['pc_hfap_location'], array('header', 'footer', 'body')) 
            ? $form_data['pc_hfap_location'] 
            : 'header',
        'code' => wp_unslash($form_data['pc_hfap_code'])
    );
    
    $snippet = new PC_HFAP_Snippet($data);
    $result = $snippet->save();
    
    if ($result) {
        echo '<p class="pass">✓ Form simulation: Snippet saved (ID: ' . $result . ')</p>';
        
        // Clean up
        $snippet->delete();
    } else {
        echo '<p class="fail">✗ Form simulation: Save failed</p>';
        $all_passed = false;
    }
} else {
    echo '<p class="fail">✗ Nonce verification: FAILED</p>';
    $all_passed = false;
}

echo '</div>';

// ============================================
// FINAL SUMMARY
// ============================================
echo '<div class="summary">';
echo '<h2>FINAL SUMMARY</h2>';

echo '<p>Test Results:</p>';
echo '<ul>';
echo '<li>Files: ✓</li>';
echo '<li>Constants: ✓</li>';
echo '<li>Database: ' . ($table_exists === $table_name ? '✓' : '✗') . '</li>';
echo '<li>Create: ' . ($test_results['create'] ? '✓' : '✗') . '</li>';
echo '<li>Read: ' . ($test_results['read'] ? '✓' : '✗') . '</li>';
echo '<li>Update: ' . ($test_results['update'] ? '✓' : '✗') . '</li>';
echo '<li>Delete: ' . ($test_results['delete'] ? '✓' : '✗') . '</li>';
echo '</ul>';

if ($all_passed) {
    echo '<h1 class="pass">✓ ALL TESTS PASSED - PLUGIN IS WORKING CORRECTLY</h1>';
} else {
    echo '<h1 class="fail">✗ SOME TESTS FAILED - REVIEW RESULTS ABOVE</h1>';
}

echo '</div>';

echo '<h3>Quick Links</h3>';
echo '<ul>';
echo '<li><a href="' . admin_url('admin.php?page=pc-hfap-snippets') . '">Manage Snippets</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 Site</a></li>';
echo '</ul>';

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