<?php
// test_form.php
ob_start(); // Start output buffering

if (isset($_GET['debug'])) {
    header('Content-Type: text/plain');
    
    // Test JSON response
    echo json_encode(['test' => true, 'message' => 'Debug test']);
    exit;
}

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

echo "<h1>Form Test Script</h1>";

// Test session
$_SESSION['csrf_token'] = 'test_token_' . time();
echo "<p>Session started. CSRF token: " . $_SESSION['csrf_token'] . "</p>";

// Test database connection
try {
    require_once 'database.php';
    echo "<p style='color: green;'>✓ Database connected successfully</p>";
    
    // Test fraud_reports table
    $result = $database->get_connection()->query("SELECT COUNT(*) as count FROM fraud_reports");
    if ($result) {
        $row = $result->fetch_assoc();
        echo "<p>fraud_reports table has " . $row['count'] . " records</p>";
    } else {
        echo "<p style='color: orange;'>Could not query fraud_reports table: " . $database->get_connection()->error . "</p>";
    }
    
} catch (Exception $e) {
    echo "<p style='color: red;'>✗ Database error: " . $e->getMessage() . "</p>";
}

// Test POST handling
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "<h2>POST Received</h2>";
    echo "<p>POST data: " . htmlspecialchars(json_encode($_POST)) . "</p>";
    echo "<p>FILES data: " . htmlspecialchars(json_encode($_FILES)) . "</p>";
    
    // Simulate your form processing
    $response = [
        'success' => true,
        'message' => 'Test successful! This would be your success message.',
        'errors' => [],
        'case_number' => 'TEST-' . time()
    ];
    
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Show test form
?>
<h2>Test Form</h2>
<form id="testForm" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    <input type="text" name="website" style="display:none;">
    
    <div>
        <label>Name: <input type="text" name="reporterName" value="Test User"></label>
    </div>
    <div>
        <label>Email: <input type="email" name="reporterEmail" value="test@example.com"></label>
    </div>
    <div>
        <label>Phone: <input type="text" name="reporterPhone" value="1234567890"></label>
    </div>
    <div>
        <label>Fraud Type: 
            <select name="fraudType">
                <option value="general">General</option>
            </select>
        </label>
    </div>
    <div>
        <label>First Noticed: <input type="datetime-local" name="firstNoticed" value="<?php echo date('Y-m-d\TH:i'); ?>"></label>
    </div>
    <div>
        <label>Description: <textarea name="fraudDescription">Test description with more than 50 characters for validation testing purposes.</textarea></label>
    </div>
    <div>
        <label>Ongoing: 
            <input type="radio" name="ongoing" value="no" checked> No
        </label>
    </div>
    <div>
        <label>Contact Preference: 
            <select name="contactPreference">
                <option value="email" selected>Email</option>
            </select>
        </label>
    </div>
    <div>
        <label>
            <input type="checkbox" name="confirmTruthful" checked> Confirm truthful
        </label>
    </div>
    <div>
        <label>
            <input type="checkbox" name="confirmConsent" checked> Confirm consent
        </label>
    </div>
    <div>
        <label>
            <input type="checkbox" name="confirmPrivacy" checked> Confirm privacy
        </label>
    </div>
    <div>
        <label>Test File (optional): <input type="file" name="evidenceFiles[]"></label>
    </div>
    <div>
        <button type="submit">Submit Test</button>
    </div>
</form>

<script>
document.getElementById('testForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    console.log('Submitting test form...');
    
    const formData = new FormData(this);
    
    try {
        const response = await fetch('', {
            method: 'POST',
            body: formData
        });
        
        console.log('Response status:', response.status);
        console.log('Response ok:', response.ok);
        
        if (response.ok) {
            const data = await response.json();
            console.log('Response data:', data);
            alert('Success: ' + data.message);
        } else {
            const text = await response.text();
            console.error('Response text:', text);
            alert('Error: Status ' + response.status);
        }
    } catch (error) {
        console.error('Fetch error:', error);
        console.error('Error name:', error.name);
        console.error('Error message:', error.message);
        alert('Network error: ' + error.message);
    }
});
</script>