<?php
/**
 * Registration Test Script
 * Run this to debug registration issues, then DELETE!
 */

define('BASE_PATH', __DIR__);
require_once BASE_PATH . '/app/config/config.php';

echo "<h2>Registration Debug Test</h2>";

// Test 1: Database connection
echo "<h3>1. Database Connection</h3>";
try {
    $pdo = Database::getInstance();
    echo "<p style='color:green'>✅ Database connected successfully</p>";
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Database error: " . $e->getMessage() . "</p>";
    exit;
}

// Test 2: Users table exists
echo "<h3>2. Users Table</h3>";
try {
    $result = Database::fetchAll("SHOW TABLES LIKE 'users'");
    if (count($result) > 0) {
        echo "<p style='color:green'>✅ Users table exists</p>";
        
        // Show table structure
        $columns = Database::fetchAll("DESCRIBE users");
        echo "<pre>";
        foreach ($columns as $col) {
            echo $col['Field'] . " - " . $col['Type'] . "\n";
        }
        echo "</pre>";
    } else {
        echo "<p style='color:red'>❌ Users table does NOT exist! Import schema.sql first.</p>";
        exit;
    }
} catch (Exception $e) {
    echo "<p style='color:red'>❌ Error: " . $e->getMessage() . "</p>";
}

// Test 3: CSRF Token
echo "<h3>3. CSRF Token</h3>";
session_name(SESSION_NAME);
session_start();
$token = CSRF::generateToken();
echo "<p>Token generated: " . substr($token, 0, 20) . "...</p>";
echo "<p style='color:green'>✅ CSRF working</p>";

// Test 4: Try inserting a test user
echo "<h3>4. Test User Insert</h3>";
$testEmail = 'test_' . time() . '@test.com';
$testPhone = '01700' . rand(100000, 999999);

try {
    $userId = Database::insert(
        "INSERT INTO users (full_name, email, phone, password_hash, created_at) VALUES (?, ?, ?, ?, NOW())",
        ['Test User', $testEmail, $testPhone, password_hash('test123', PASSWORD_DEFAULT)]
    );
    echo "<p style='color:green'>✅ Test user created with ID: $userId</p>";
    
    // Clean up - delete test user
    Database::execute("DELETE FROM users WHERE id = ?", [$userId]);
    echo "<p style='color:green'>✅ Test user cleaned up</p>";
    
} catch (PDOException $e) {
    echo "<p style='color:red'>❌ Insert failed: " . $e->getMessage() . "</p>";
    echo "<p>Error code: " . $e->getCode() . "</p>";
}

// Test 5: Check existing users
echo "<h3>5. Existing Users</h3>";
$users = Database::fetchAll("SELECT id, email, phone FROM users LIMIT 5");
if (count($users) > 0) {
    echo "<p>Found " . count($users) . " user(s):</p>";
    echo "<ul>";
    foreach ($users as $u) {
        echo "<li>" . htmlspecialchars($u['email']) . " - " . htmlspecialchars($u['phone']) . "</li>";
    }
    echo "</ul>";
} else {
    echo "<p>No users in database yet.</p>";
}

echo "<hr>";
echo "<p style='color:orange'><strong>⚠️ DELETE THIS FILE (test_register.php) after testing!</strong></p>";
echo "<p><a href='public/?page=register'>Go to Registration Page →</a></p>";
