<?php
require_once 'config/config.php';

echo "<h2>Registration Debug</h2>\n";

try {
    $database = new Database();
    $db = $database->getConnection();
    
    echo "<p>✓ Database connection successful</p>\n";
    
    // Check if required columns exist in candidates table
    echo "<h3>Checking candidates table structure:</h3>\n";
    $stmt = $db->query("DESCRIBE candidates");
    $columns = $stmt->fetchAll();
    
    $required_columns = ['candidate_type', 'employee_code', 'company_id', 'hr_approval_status'];
    $existing_columns = array_column($columns, 'Field');
    
    echo "<table border='1' style='border-collapse: collapse; margin: 10px 0;'>\n";
    echo "<tr><th>Column</th><th>Type</th><th>Null</th><th>Default</th></tr>\n";
    foreach ($columns as $column) {
        $color = in_array($column['Field'], $required_columns) ? 'background-color: #d4edda;' : '';
        echo "<tr style='$color'><td>{$column['Field']}</td><td>{$column['Type']}</td><td>{$column['Null']}</td><td>{$column['Default']}</td></tr>\n";
    }
    echo "</table>\n";
    
    echo "<h3>Required columns status:</h3>\n";
    foreach ($required_columns as $col) {
        if (in_array($col, $existing_columns)) {
            echo "<div style='color: green;'>✓ $col - EXISTS</div>\n";
        } else {
            echo "<div style='color: red;'>✗ $col - MISSING</div>\n";
        }
    }
    
    // Test the exact SQL query that would be used in registration
    echo "<h3>Testing registration SQL query:</h3>\n";
    
    $test_data = [
        'first_name' => 'Test',
        'last_name' => 'User',
        'email' => 'test_' . time() . '@example.com',
        'password' => password_hash('TestPassword123!', PASSWORD_DEFAULT),
        'phone' => '1234567890',
        'candidate_type' => 'internal',
        'employee_code' => 'EMP001',
        'company_id' => 1,
        'hr_approval_status' => 'pending'
    ];
    
    try {
        $stmt = $db->prepare("
            INSERT INTO candidates (first_name, last_name, email, password, phone, candidate_type, employee_code, company_id, hr_approval_status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        echo "<p><strong>SQL Query:</strong> INSERT INTO candidates (first_name, last_name, email, password, phone, candidate_type, employee_code, company_id, hr_approval_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)</p>\n";
        echo "<p><strong>Test Data:</strong></p>\n";
        echo "<ul>\n";
        foreach ($test_data as $key => $value) {
            $display_value = ($key === 'password') ? '[HASHED_PASSWORD]' : $value;
            echo "<li>$key: $display_value</li>\n";
        }
        echo "</ul>\n";
        
        $result = $stmt->execute(array_values($test_data));
        
        if ($result) {
            echo "<div style='color: green; padding: 10px; background: #d4edda; border: 1px solid #c3e6cb;'>✓ Test registration SQL executed successfully!</div>\n";
            
            // Clean up test data
            $stmt = $db->prepare("DELETE FROM candidates WHERE email = ?");
            $stmt->execute([$test_data['email']]);
            echo "<p><em>Test data cleaned up.</em></p>\n";
        } else {
            echo "<div style='color: red; padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb;'>✗ Test registration SQL failed!</div>\n";
        }
        
    } catch (PDOException $e) {
        echo "<div style='color: red; padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb;'>\n";
        echo "<strong>SQL Error:</strong> " . $e->getMessage() . "<br>\n";
        echo "<strong>Error Code:</strong> " . $e->getCode() . "\n";
        echo "</div>\n";
        
        // Suggest fixes based on common errors
        if (strpos($e->getMessage(), "Unknown column") !== false) {
            echo "<h3>🔧 Fix Required:</h3>\n";
            echo "<p>Some columns are missing from the candidates table. Run the migration script:</p>\n";
            echo "<p><a href='run_company_approval_fixed_migration.php' style='background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px;'>Run Migration Script</a></p>\n";
        }
    }
    
    // Check if companies exist for internal registration
    echo "<h3>Checking companies for internal registration:</h3>\n";
    $stmt = $db->query("SELECT id, name, status FROM companies ORDER BY name");
    $companies = $stmt->fetchAll();
    
    if (empty($companies)) {
        echo "<div style='color: orange; padding: 10px; background: #fff3cd; border: 1px solid #ffeaa7;'>⚠ No companies found. Internal candidate registration will not work without companies.</div>\n";
    } else {
        echo "<table border='1' style='border-collapse: collapse; margin: 10px 0;'>\n";
        echo "<tr><th>ID</th><th>Company Name</th><th>Status</th></tr>\n";
        foreach ($companies as $company) {
            $color = ($company['status'] === 'approved') ? 'background-color: #d4edda;' : 'background-color: #fff3cd;';
            echo "<tr style='$color'><td>{$company['id']}</td><td>{$company['name']}</td><td>{$company['status']}</td></tr>\n";
        }
        echo "</table>\n";
        
        $approved_count = count(array_filter($companies, function($c) { return $c['status'] === 'approved'; }));
        echo "<p><strong>$approved_count approved companies available for internal registration.</strong></p>\n";
    }
    
} catch (Exception $e) {
    echo "<div style='color: red; padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb;'>\n";
    echo "<strong>Database Error:</strong> " . $e->getMessage() . "\n";
    echo "</div>\n";
}

echo "<hr>\n";
echo "<h3>Next Steps:</h3>\n";
echo "<ol>\n";
echo "<li>If columns are missing, run the <a href='run_company_approval_fixed_migration.php'>migration script</a></li>\n";
echo "<li>Make sure you have approved companies in the database</li>\n";
echo "<li>Try registration again at <a href='auth/register.php'>register.php</a></li>\n";
echo "</ol>\n";
?>