<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
require_once 'db/config.php';
$pdo = db();

$userId = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);

// If no user ID is specified, show a list of all users.
if (!$userId) {
    $stmt = $pdo->query("SELECT u.id, u.username, u.email, r.name as role_name FROM users u LEFT JOIN roles r ON u.role_id = r.id ORDER BY u.username");
    $users = $stmt->fetchAll();
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>HR Employee Directory - FinMox</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <style>
            @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
            * { font-family: 'Inter', sans-serif; }
        </style>
    </head>
    <body class="bg-gray-100">
        <div class="flex h-screen bg-gray-200">
            <?php include '_sidebar.php'; ?>
            <main class="flex-1 overflow-x-hidden overflow-y-auto bg-[#fafafa]">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 md:px-8 py-8">
                    <h1 class="text-3xl font-bold text-gray-900 mb-6">Employee Directory</h1>
                    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
                                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Role</th>
                                        <th scope="col" class="relative px-6 py-3">
                                            <span class="sr-only">View</span>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <?php foreach ($users as $user): ?>
                                        <tr>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($user['username']); ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($user['email']); ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($user['role_name'] ?? 'N/A'); ?></td>
                                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                                <a href="?user_id=<?php echo $user['id']; ?>" class="text-blue-600 hover:text-blue-900">View Overview</a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </body>
    </html>
    <?php
    exit; // Stop execution after showing the list
}

// --- Existing code for showing a single user's overview ---

// Fetch user and role
$stmt = $pdo->prepare("SELECT u.username, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    exit('Employee not found.');
}

// Fetch tasks for the user
$task_stmt = $pdo->prepare("SELECT * FROM tasks WHERE assignee_id = ? ORDER BY due_date");
$task_stmt->execute([$userId]);
$tasks = $task_stmt->fetchAll();

$pending_tasks = array_filter($tasks, fn($task) => $task['status'] !== 'completed');
$completed_tasks = array_filter($tasks, fn($task) => $task['status'] === 'completed');
$total_tasks = count($tasks);
$progress = ($total_tasks > 0) ? (count($completed_tasks) / $total_tasks) * 100 : 0;

// The rest of the data is still static for now
$employee = [
    'id' => $userId,
    'name' => $user['username'],
    'role' => $user['role_name'],
    'manager' => 'Sarah Johnson', // Static for now
    'startDate' => '2024-12-14', // Static for now
    'progress' => round($progress),
    'pending_tasks' => array_map(function($task) {
        return ['name' => $task['task_name'], 'due' => $task['due_date'], 'description' => $task['description']];
    }, $pending_tasks),
    'completed_tasks' => array_map(function($task) {
        return ['name' => $task['task_name'], 'completed_on' => $task['updated_at']];
    }, $completed_tasks),
    'activity_log' => [
        ['date' => 'Dec 16, 2024', 'event' => 'Magic link generated and sent to employee.'],
        ['date' => 'Dec 15, 2024', 'event' => 'Onboarding process initiated by HR.'],
    ]
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HR Employee Overview - FinMox</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        * { font-family: 'Inter', sans-serif; }
        body { background-color: #fafafa; -webkit-font-smoothing: antialiased; }
    </style>
</head>
<body class="bg-gray-100">
    <div class="flex h-screen bg-gray-200">
        <?php include '_sidebar.php'; ?>

        <main class="flex-1 overflow-x-hidden overflow-y-auto bg-[#fafafa]">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 md:px-8 py-8">
                
                <!-- Page Header -->
                <div class="mb-8">
                    <h1 class="text-3xl font-bold text-gray-900">HR Employee Overview</h1>
                    <p class="text-gray-600 mt-1">Detailed onboarding progress for <span class="font-semibold"><?php echo htmlspecialchars($employee['name']); ?></span>.</p>
                </div>

                <!-- Main Grid -->
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

                    <!-- Left Column: Tasks and Logs -->
                    <div class="lg:col-span-2 space-y-8">
                        
                        <!-- Task Checklist -->
                        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">Onboarding Task Checklist</h3>
                            <div class="space-y-4">
                                <!-- Pending Tasks -->
                                <?php foreach ($employee['pending_tasks'] as $task): ?>
                                <div class="p-3 border rounded-lg">
                                    <div class="flex items-center justify-between">
                                        <p class="font-semibold text-gray-800"><?php echo htmlspecialchars($task['name']); ?></p>
                                        <span class="text-xs font-medium text-yellow-800 bg-yellow-100 px-2 py-1 rounded-full">Pending</span>
                                    </div>
                                    <p class="text-sm text-gray-600 mt-1"><?php echo htmlspecialchars($task['description']); ?></p>
                                    <p class="text-xs text-gray-500 mt-2">Due: <?php echo htmlspecialchars($task['due']); ?></p>
                                </div>
                                <?php endforeach; ?>
                                <!-- Completed Tasks -->
                                <?php foreach ($employee['completed_tasks'] as $task): ?>
                                <div class="p-3 border rounded-lg bg-gray-50">
                                    <div class="flex items-center justify-between">
                                        <p class="font-semibold text-gray-500 line-through"><?php echo htmlspecialchars($task['name']); ?></p>
                                        <span class="text-xs font-medium text-green-800 bg-green-100 px-2 py-1 rounded-full">Completed</span>
                                    </div>
                                     <p class="text-xs text-gray-500 mt-2">Completed On: <?php echo htmlspecialchars($task['completed_on']); ?></p>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Activity Log -->
                        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">Activity Log</h3>
                            <ul class="space-y-4">
                                <?php foreach ($employee['activity_log'] as $log): ?>
                                <li class="flex items-start">
                                    <div class="w-20 text-xs text-gray-500 shrink-0"><?php echo $log['date']; ?></div>
                                    <div class="ml-4 text-sm text-gray-700"><?php echo htmlspecialchars($log['event']); ?></div>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>

                    </div>

                    <!-- Right Column: Details and Actions -->
                    <div class="space-y-8">

                        <!-- Employee Details -->
                        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">Employee Details</h3>
                            <div class="space-y-3">
                                <p class="text-sm"><span class="font-semibold text-gray-600">Role:</span> <?php echo htmlspecialchars($employee['role']); ?></p>
                                <p class="text-sm"><span class="font-semibold text-gray-600">Manager:</span> <?php echo htmlspecialchars($employee['manager']); ?></p>
                                <p class="text-sm"><span class="font-semibold text-gray-600">Start Date:</span> <?php echo htmlspecialchars($employee['startDate']); ?></p>
                            </div>
                        </div>

                        <!-- HR Actions -->
                        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                            <h3 class="text-lg font-semibold text-gray-900 mb-4">HR Actions</h3>
                            <div class="space-y-3">
                                <a href="generate_magic_link.php?user_id=<?php echo $employee['id']; ?>" target="_blank" class="block w-full text-center bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg transition">Generate Magic Link</a>
                                <a href="impersonate.php?user_id=<?php echo $employee['id']; ?>" class="block w--full text-center bg-green-500 hover:bg-green-600 text-white font-semibold py-2 px-4 rounded-lg transition">View as Employee</a>
                                <button class="w-full text-left bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-4 rounded-lg transition">Send Reminder Email</button>
                                <button class="w-full text-left bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-4 rounded-lg transition">Add Internal Note</button>
                            </div>
                        </div>
                        
                        <!-- Onboarding Progress -->
                        <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                             <h3 class="text-lg font-semibold text-gray-900 mb-2">Onboarding Progress</h3>
                            <p class="text-3xl font-bold text-gray-900"><?php echo $employee['progress']; ?>%</p>
                            <div class="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                                <div class="bg-blue-600 h-2.5 rounded-full" style="width: <?php echo $employee['progress']; ?>%"></div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </main>
    </div>
    <script>
        lucide.createIcons();
    </script>
</body>
</html>
