<?php
/**
 * FORM SUBMISSION SIMULATION TEST
 * This simulates EXACTLY what happens when you submit the Add New form
 */

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

echo '<!DOCTYPE html>
<html>
<head>
    <title>Form Submission Test</title>
    <style>
        body { font-family: sans-serif; padding: 20px; max-width: 700px; margin: 0 auto; background: #f0f0f0; }
        h1 { background: #0073aa; color: white; padding: 15px; margin: -20px -20px 20px; }
        .step { background: white; padding: 15px; margin: 10px 0; border-radius: 5px; }
        .ok { color: #28a745; font-weight: bold; }
        .fail { color: #dc3545; font-weight: bold; }
        .warn { color: #ffc107; font-weight: bold; }
        pre { background: #f5f5f5; padding: 10px; overflow-x: auto; }
    </style>
</head>
<body>
<h1>Form Submission Simulation</h1>
<p>This test simulates clicking "Save Snippet" on the Add New page.</p>';

$success = true;

// Simulate form data
$form_data = array(
    'pc_hfap_title' => 'Simulated Form Test ' . date('H:i:s'),
    'pc_hfap_location' => 'header',
    'pc_hfap_code' => '<script>console.log("Form test ' . date('Y-m-d H:i:s') . '");</script>',
    'pc_hfap_nonce' => wp_create_nonce('pc_hfap_save_snippet'),
    'submit_snippet' => '1'
);

echo '<div class="step">';
echo '<h3>Simulated Form Data:</h3>';
echo '<ul>';
echo '<li>Title: ' . htmlspecialchars($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 '<li>Nonce: ' . substr($form_data['pc_hfap_nonce'], 0, 20) . '...</li>';
echo '</ul>';
echo '</div>';

// Step 1: Verify nonce
echo '<div class="step">';
echo '<h3>Step 1: Verify Nonce</h3>';

if (wp_verify_nonce($form_data['pc_hfap_nonce'], 'pc_hfap_save_snippet')) {
    echo '<p class="ok">✓ Nonce is VALID</p>';
} else {
    echo '<p class="fail">✗ Nonce verification FAILED</p>';
    $success = false;
}
echo '</div>';

// Step 2: Check permissions
echo '<div class="step">';
echo '<h3>Step 2: Check Permissions</h3>';

if (current_user_can('manage_options')) {
    echo '<p class="ok">✓ User has manage_options capability</p>';
} else {
    echo '<p class="warn">⚠ User may not have admin permissions (normal if not logged in as admin)</p>';
}
echo '</div>';

// Step 3: Validate fields
echo '<div class="step">';
echo '<h3>Step 3: Validate Fields</h3>';

$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']);

echo '<p>Sanitized title: ' . htmlspecialchars($title) . '</p>';
echo '<p>Validated location: ' . $location . '</p>';
echo '<p>Unslashed code: ' . htmlspecialchars($code) . '</p>';

if (!empty($title) && !empty($location) && !empty($code)) {
    echo '<p class="ok">✓ All fields valid</p>';
} else {
    echo '<p class="fail">✗ Some fields are empty</p>';
    $success = false;
}
echo '</div>';

// Step 4: Save to database
echo '<div class="step">';
echo '<h3>Step 4: Save to Database</h3>';

$data = array(
    'title' => $title,
    'location' => $location,
    'code' => $code
);

$snippet = new PC_HFAP_Snippet($data);
$result = $snippet->save();

if ($result) {
    echo '<p class="ok">✓ SUCCESS! Snippet saved with ID: ' . $result . '</p>';
} else {
    echo '<p class="fail">✗ FAILED to save snippet</p>';
    global $wpdb;
    echo '<p>WordPress error: ' . $wpdb->last_error . '</p>';
    $success = false;
}
echo '</div>';

// Step 5: Verify in database
echo '<div class="step">';
echo '<h3>Step 5: Verify in Database</h3>';

if ($result) {
    $retrieved = PC_HFAP_Snippet::get_by_id($result);
    
    if ($retrieved) {
        echo '<p class="ok">✓ Retrieved from database:</p>';
        echo '<pre>';
        echo 'ID: ' . $retrieved->get_id() . "\n";
        echo 'Title: ' . $retrieved->get_title() . "\n";
        echo 'Location: ' . $retrieved->get_location() . "\n";
        echo 'Code: ' . $retrieved->get_code() . "\n";
        echo '</pre>';
        
        // Step 6: Delete test snippet
        echo '<div class="step">';
        echo '<h3>Step 6: Clean Up - Delete Test Snippet</h3>';
        
        $delete_result = $retrieved->delete();
        
        if ($delete_result) {
            echo '<p class="ok">✓ Test snippet deleted successfully</p>';
        } else {
            echo '<p class="fail">✗ Failed to delete test snippet</p>';
        }
        echo '</div>';
    } else {
        echo '<p class="fail">✗ Could not retrieve saved snippet</p>';
        $success = false;
    }
}
echo '</div>';

// Final result
echo '<hr>';
echo '<div class="step" style="background: #23282d; color: white; text-align: center;">';
echo '<h2>FINAL RESULT</h2>';

if ($success) {
    echo '<p style="color: #28a745; font-size: 20px;">✓ FORM SUBMISSION WOULD WORK!</p>';
    echo '<p>The form submission process is working correctly.</p>';
} else {
    echo '<p style="color: #dc3545; font-size: 20px;">✗ ISSUES DETECTED</p>';
    echo '<p>Check the errors above.</p>';
}

echo '</div>';

// Test the actual admin form
echo '<h3>Test the Actual Form</h3>';
echo '<p>Now try the actual admin form:</p>';
echo '<ul>';
echo '<li><a href="' . admin_url('admin.php?page=pc-hfap-add-snippet') . '">Headers & Footers → Add New</a></li>';
echo '<li>Fill in the form</li>';
echo '<li>Click "Save Snippet"</li>';
echo '<li>You should be redirected to the snippets list</li>';
echo '</ul>';

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