<?php
/**
 * Test HR List - Debug Page
 * Check if HR users are properly configured
 */

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

$db = getDB();
$siteId = getCurrentSiteId();

echo "<!DOCTYPE html>";
echo "<html><head><title>Test HR List</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; }
    .info { background: #e3f2fd; padding: 15px; border-left: 4px solid #2196F3; margin: 20px 0; }
</style>";
echo "</head><body>";

echo "<h1>🔍 HR List Test Page</h1>";

try {
    // Test 1: Check all roles
    echo "<h2>Test 1: All Roles in Database</h2>";
    $rolesStmt = $db->query("SELECT role_id, role_code, role_name FROM roles ORDER BY role_id");
    $roles = $rolesStmt->fetchAll();
    
    echo "<table>";
    echo "<tr><th>Role ID</th><th>Role Code</th><th>Role Name</th></tr>";
    foreach ($roles as $role) {
        echo "<tr>";
        echo "<td>{$role['role_id']}</td>";
        echo "<td>{$role['role_code']}</td>";
        echo "<td>{$role['role_name']}</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    // Test 2: Check HR Admin users
    echo "<h2>Test 2: All HR Admin Users</h2>";
    $hrStmt = $db->prepare("
        SELECT u.user_id, u.username, u.full_name, u.email, u.user_status, u.site_id, r.role_code, r.role_name
        FROM users u
        INNER JOIN roles r ON u.role_id = r.role_id
        WHERE (LOWER(r.role_code) = 'hr_admin' OR r.role_code = 'HR_ADMIN' OR r.role_code LIKE '%hr%')
        ORDER BY u.user_id
    ");
    $hrStmt->execute();
    $hrUsers = $hrStmt->fetchAll();
    
    if (count($hrUsers) == 0) {
        echo "<p class='error'>❌ No HR Admin users found!</p>";
        echo "<div class='info'><strong>Solution:</strong> You need to create HR Admin users first.</div>";
    } else {
        echo "<p class='success'>✅ Found " . count($hrUsers) . " HR user(s)</p>";
        echo "<table>";
        echo "<tr><th>User ID</th><th>Username</th><th>Full Name</th><th>Email</th><th>Role Code</th><th>Role Name</th><th>Status</th><th>Site ID</th></tr>";
        foreach ($hrUsers as $hr) {
            $statusColor = $hr['user_status'] == 'active' ? 'green' : 'red';
            echo "<tr>";
            echo "<td>{$hr['user_id']}</td>";
            echo "<td>{$hr['username']}</td>";
            echo "<td>{$hr['full_name']}</td>";
            echo "<td>{$hr['email']}</td>";
            echo "<td>{$hr['role_code']}</td>";
            echo "<td>{$hr['role_name']}</td>";
            echo "<td style='color: $statusColor;'>{$hr['user_status']}</td>";
            echo "<td>{$hr['site_id']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    // Test 3: Check employees per HR
    echo "<h2>Test 3: Employees per HR Manager</h2>";
    $empPerHRStmt = $db->prepare("
        SELECT 
            u.user_id,
            u.full_name as hr_name,
            r.role_code,
            COUNT(DISTINCT e.employee_id) as emp_count,
            GROUP_CONCAT(CONCAT(e.first_name, ' ', e.last_name) SEPARATOR ', ') as employees
        FROM users u
        INNER JOIN roles r ON u.role_id = r.role_id
        LEFT JOIN employees e ON e.created_by = u.user_id AND e.employment_status = 'active' AND e.site_id = ?
        WHERE (LOWER(r.role_code) = 'hr_admin' OR r.role_code = 'HR_ADMIN')
        AND u.user_status = 'active'
        AND u.site_id = ?
        GROUP BY u.user_id, u.full_name, r.role_code
        ORDER BY u.full_name
    ");
    $empPerHRStmt->execute([$siteId, $siteId]);
    $hrWithEmps = $empPerHRStmt->fetchAll();
    
    if (count($hrWithEmps) == 0) {
        echo "<p class='error'>❌ No active HR users found for site ID: $siteId</p>";
    } else {
        echo "<p class='success'>✅ Found " . count($hrWithEmps) . " active HR(s) for current site</p>";
        echo "<table>";
        echo "<tr><th>User ID</th><th>HR Name</th><th>Role Code</th><th>Employee Count</th><th>Employees</th></tr>";
        foreach ($hrWithEmps as $hr) {
            echo "<tr>";
            echo "<td>{$hr['user_id']}</td>";
            echo "<td>{$hr['hr_name']}</td>";
            echo "<td>{$hr['role_code']}</td>";
            echo "<td>{$hr['emp_count']}</td>";
            echo "<td>" . ($hr['employees'] ?: 'None') . "</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    // Test 4: Current user info
    echo "<h2>Test 4: Current Logged-in User</h2>";
    echo "<div class='info'>";
    echo "<p><strong>User ID:</strong> {$_SESSION['user_id']}</p>";
    echo "<p><strong>Username:</strong> {$_SESSION['username']}</p>";
    echo "<p><strong>Full Name:</strong> {$_SESSION['full_name']}</p>";
    echo "<p><strong>Role Code:</strong> {$_SESSION['role_code']}</p>";
    echo "<p><strong>Role Name:</strong> {$_SESSION['role_name']}</p>";
    echo "<p><strong>Site ID:</strong> $siteId</p>";
    echo "<p><strong>Site Name:</strong> {$_SESSION['site_name']}</p>";
    echo "<p><strong>Is Super Admin:</strong> " . (isSuperAdmin() ? '✅ Yes' : '❌ No') . "</p>";
    echo "<p><strong>Is HR Admin:</strong> " . (isHRAdmin() ? '✅ Yes' : '❌ No') . "</p>";
    echo "</div>";
    
    // Test 5: SQL for dropdown
    echo "<h2>Test 5: Exact SQL Used in Dropdown</h2>";
    echo "<pre style='background: #f5f5f5; padding: 15px; border: 1px solid #ddd;'>";
    echo "SELECT u.user_id, u.full_name, COUNT(DISTINCT e.employee_id) as emp_count
FROM users u
INNER JOIN roles r ON u.role_id = r.role_id
LEFT JOIN employees e ON e.created_by = u.user_id AND e.employment_status = 'active' AND e.site_id = $siteId
WHERE (LOWER(r.role_code) = 'hr_admin' OR r.role_code = 'HR_ADMIN') 
AND u.user_status = 'active' 
AND u.site_id = $siteId
GROUP BY u.user_id, u.full_name
ORDER BY u.full_name";
    echo "</pre>";
    
    echo "<p><strong>Results:</strong></p>";
    if (count($hrWithEmps) > 0) {
        echo "<ul>";
        foreach ($hrWithEmps as $hr) {
            echo "<li><strong>{$hr['hr_name']}</strong> (User ID: {$hr['user_id']}) - {$hr['emp_count']} employee(s)</li>";
        }
        echo "</ul>";
        echo "<p class='success'>✅ These HRs should appear in the dropdown!</p>";
    } else {
        echo "<p class='error'>❌ No results - dropdown will be empty!</p>";
    }
    
} catch (Exception $e) {
    echo "<p class='error'>❌ Error: " . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
}

echo "<hr>";
echo "<p><a href='salary_register.php' style='background: #4CAF50; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>← Back to Salary Register</a></p>";
echo "</body></html>";
?>
