<?php
/**
 * Test HR Admin Creation - Debug Page
 * Check prerequisites before creating HR Admin
 */

require_once __DIR__ . '/../includes/init.php';
requireLogin();

if (!isSuperAdmin()) {
    die('Access denied. Super Admin only.');
}

$db = getDB();

echo "<!DOCTYPE html>";
echo "<html><head><title>Test HR Creation</title>";
echo "<style>
    body { font-family: Arial; padding: 20px; }
    table { border-collapse: collapse; width: 100%; margin: 20px 0; }
    th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
    th { background: #4CAF50; color: white; }
    .success { color: green; font-weight: bold; }
    .error { color: red; font-weight: bold; }
    .warning { color: orange; font-weight: bold; }
    .info { background: #e3f2fd; padding: 15px; border-left: 4px solid #2196F3; margin: 20px 0; }
</style>";
echo "</head><body>";

echo "<h1>🔍 HR Admin Creation - Pre-Check</h1>";

$allGood = true;

// Test 1: Check HR Admin role
echo "<h2>Test 1: HR Admin Role</h2>";
try {
    $stmt = $db->query("SELECT role_id, role_code, role_name FROM roles WHERE LOWER(role_code) = 'hr_admin' OR role_code = 'HR_ADMIN'");
    $roles = $stmt->fetchAll();
    
    if (count($roles) == 0) {
        echo "<p class='error'>❌ HR Admin role NOT found!</p>";
        echo "<div class='info'><strong>Fix:</strong> Run this SQL:<br>";
        echo "<code>INSERT INTO roles (role_code, role_name, is_system_role) VALUES ('HR_ADMIN', 'HR Administrator', 1);</code></div>";
        $allGood = false;
    } else {
        echo "<p class='success'>✅ HR Admin role found:</p>";
        echo "<table>";
        echo "<tr><th>Role ID</th><th>Role Code</th><th>Role Name</th></tr>";
        foreach ($roles as $role) {
            echo "<tr><td>{$role['role_id']}</td><td>{$role['role_code']}</td><td>{$role['role_name']}</td></tr>";
        }
        echo "</table>";
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error checking roles: " . $e->getMessage() . "</p>";
    $allGood = false;
}

// Test 2: Check sites
echo "<h2>Test 2: Active Sites</h2>";
try {
    $stmt = $db->query("SELECT site_id, site_name, site_code, site_status FROM sites WHERE site_status = 'active'");
    $sites = $stmt->fetchAll();
    
    if (count($sites) == 0) {
        echo "<p class='error'>❌ No active sites found!</p>";
        echo "<div class='info'><strong>Fix:</strong> Create at least one active site first.</div>";
        $allGood = false;
    } else {
        echo "<p class='success'>✅ Found " . count($sites) . " active site(s):</p>";
        echo "<table>";
        echo "<tr><th>Site ID</th><th>Site Name</th><th>Site Code</th><th>Status</th></tr>";
        foreach ($sites as $site) {
            echo "<tr><td>{$site['site_id']}</td><td>{$site['site_name']}</td><td>{$site['site_code']}</td><td>{$site['site_status']}</td></tr>";
        }
        echo "</table>";
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error checking sites: " . $e->getMessage() . "</p>";
    $allGood = false;
}

// Test 3: Check user_sites table
echo "<h2>Test 3: user_sites Table</h2>";
try {
    $stmt = $db->query("SHOW TABLES LIKE 'user_sites'");
    if ($stmt->rowCount() > 0) {
        echo "<p class='success'>✅ user_sites table exists</p>";
        
        // Check structure
        $stmt = $db->query("DESCRIBE user_sites");
        $columns = $stmt->fetchAll();
        echo "<p>Table structure:</p>";
        echo "<table>";
        echo "<tr><th>Field</th><th>Type</th><th>Null</th><th>Key</th></tr>";
        foreach ($columns as $col) {
            echo "<tr><td>{$col['Field']}</td><td>{$col['Type']}</td><td>{$col['Null']}</td><td>{$col['Key']}</td></tr>";
        }
        echo "</table>";
    } else {
        echo "<p class='warning'>⚠️ user_sites table does NOT exist (optional - will skip if missing)</p>";
    }
} catch (Exception $e) {
    echo "<p class='warning'>⚠️ Could not check user_sites table: " . $e->getMessage() . "</p>";
}

// Test 4: Check users table structure
echo "<h2>Test 4: users Table Structure</h2>";
try {
    $stmt = $db->query("DESCRIBE users");
    $columns = $stmt->fetchAll();
    $requiredFields = ['username', 'email', 'password_hash', 'full_name', 'role_id', 'site_id', 'user_status'];
    $missingFields = [];
    
    $existingFields = array_column($columns, 'Field');
    foreach ($requiredFields as $field) {
        if (!in_array($field, $existingFields)) {
            $missingFields[] = $field;
        }
    }
    
    if (count($missingFields) > 0) {
        echo "<p class='error'>❌ Missing required fields: " . implode(', ', $missingFields) . "</p>";
        $allGood = false;
    } else {
        echo "<p class='success'>✅ All required fields present</p>";
    }
} catch (Exception $e) {
    echo "<p class='error'>❌ Error checking users table: " . $e->getMessage() . "</p>";
    $allGood = false;
}

// Test 5: Test insert (dry run)
echo "<h2>Test 5: Database Permissions</h2>";
try {
    $db->beginTransaction();
    
    // Test if we can prepare insert statement
    $stmt = $db->prepare("
        INSERT INTO users (
            username, email, password_hash, full_name, phone, 
            role_id, site_id, user_status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    echo "<p class='success'>✅ INSERT statement can be prepared</p>";
    
    $db->rollBack();
} catch (Exception $e) {
    echo "<p class='error'>❌ Cannot prepare INSERT: " . $e->getMessage() . "</p>";
    $allGood = false;
}

// Summary
echo "<h2>📊 Summary</h2>";
if ($allGood) {
    echo "<div class='info' style='background: #d4edda; border-left-color: #28a745;'>";
    echo "<p class='success'><strong>✅ All checks passed!</strong></p>";
    echo "<p>You should be able to create HR Admin successfully.</p>";
    echo "<p><a href='hr_admin_create.php' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>→ Try Creating HR Admin</a></p>";
    echo "</div>";
} else {
    echo "<div class='info' style='background: #f8d7da; border-left-color: #dc3545;'>";
    echo "<p class='error'><strong>❌ Some checks failed!</strong></p>";
    echo "<p>Please fix the issues above before creating HR Admin.</p>";
    echo "</div>";
}

echo "<hr>";
echo "<p><a href='hr_admin_create.php' style='background: #2196F3; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>← Back to Create HR Admin</a></p>";
echo "</body></html>";
?>
