<?php
/**
 * Direct AJAX Test - Run this to see actual error
 */
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h2>Testing Registration AJAX Handler</h2>";

// Simulate the include
define('BASE_PATH', __DIR__);

echo "<h3>1. Loading config...</h3>";
try {
    require_once BASE_PATH . '/app/config/config.php';
    echo "<p style='color:green'>✅ Config loaded</p>";
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Config error: " . $e->getMessage() . "</p>";
    exit;
}

echo "<h3>2. Testing Database...</h3>";
try {
    $test = Database::fetchOne("SELECT 1 as test");
    echo "<p style='color:green'>✅ Database OK</p>";
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Database error: " . $e->getMessage() . "</p>";
    exit;
}

echo "<h3>3. Checking Users Table...</h3>";
try {
    $count = Database::fetchColumn("SELECT COUNT(*) FROM users");
    echo "<p style='color:green'>✅ Users table exists ($count users)</p>";
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Users table error: " . $e->getMessage() . "</p>";
    echo "<p>Run: <code>mysql -u root safa_modest_house < sql/schema.sql</code></p>";
    exit;
}

echo "<h3>4. Testing Session & CSRF...</h3>";
session_name(SESSION_NAME);
session_start();
$token = CSRF::generateToken();
echo "<p style='color:green'>✅ Session & CSRF OK</p>";

echo "<h3>5. Testing Validator Class...</h3>";
try {
    $v = Validator::make(['test' => '']);
    $v->required('test', 'Test');
    echo "<p style='color:green'>✅ Validator OK</p>";
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Validator error: " . $e->getMessage() . "</p>";
}

echo "<h3>6. Testing Response Class...</h3>";
try {
    // Don't actually call Response methods as they exit
    echo "<p style='color:green'>✅ Response class exists</p>";
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Response error: " . $e->getMessage() . "</p>";
}

echo "<h3>7. Testing Insert...</h3>";
$testEmail = 'ajaxtest_' . time() . '@test.com';
$testPhone = '01711' . rand(100000, 999999);
try {
    $id = Database::insert(
        "INSERT INTO users (full_name, email, phone, password_hash, created_at) VALUES (?, ?, ?, ?, NOW())",
        ['Ajax Test', $testEmail, $testPhone, password_hash('test123', PASSWORD_DEFAULT)]
    );
    echo "<p style='color:green'>✅ Insert OK (ID: $id)</p>";
    Database::execute("DELETE FROM users WHERE id = ?", [$id]);
    echo "<p style='color:green'>✅ Cleanup OK</p>";
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Insert error: " . $e->getMessage() . "</p>";
}

echo "<hr><h3>All tests passed! Registration should work.</h3>";
echo "<p><a href='public/?page=register'>Try Registration →</a></p>";
echo "<p style='color:orange'><strong>⚠️ DELETE test_ajax.php after testing!</strong></p>";
