<?php
// हेडर को शामिल करें
require_once 'header.php';

// सुरक्षा जांच
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}
$is_admin_or_manager = userHasRole(['Admin', 'Manager']);

$message = '';
$message_type = '';

// --- RESET PASSWORD LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['reset_password'])) {
    if ($is_admin_or_manager) {
        $user_id_to_reset = $_POST['user_id'];
        $default_password = "Digify@1270";
        $password_hash = password_hash($default_password, PASSWORD_DEFAULT);

        $stmt = $conn->prepare("UPDATE users SET password_hash = ? WHERE id = ?");
        $stmt->bind_param("si", $password_hash, $user_id_to_reset);

        if ($stmt->execute()) {
            $message = "Password reset successfully to '" . $default_password . "'.";
            $message_type = 'success';
        } else {
            $message = "Error resetting password: " . $stmt->error;
            $message_type = 'error';
        }
        $stmt->close();
    }
}

// --- DATA FETCHING (सर्च के साथ अपडेट किया गया) ---
$search_term = $_GET['search'] ?? '';
$params = [];
$param_types = '';

$sql = "SELECT u.id, u.name, u.email, GROUP_CONCAT(r.name SEPARATOR ', ') as roles
        FROM users u
        LEFT JOIN user_roles ur ON u.id = ur.user_id
        LEFT JOIN roles r ON ur.role_id = r.id
        WHERE 1=1";

if (!empty($search_term)) {
    $sql .= " AND (u.name LIKE ? OR u.email LIKE ?)";
    $search_like = "%" . $search_term . "%";
    $params = [$search_like, $search_like];
    $param_types = 'ss';
}

$sql .= " GROUP BY u.id ORDER BY u.name ASC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$users_result = $stmt->get_result();
$users = [];
while ($row = $users_result->fetch_assoc()) {
    $users[] = $row;
}
$conn->close();
?>

<title>Manage Employees - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Manage Employees</h2>

<main class="p-6 md:p-10">
    <div class="bg-white p-4 rounded-lg shadow-md mb-8">
        <div class="flex flex-col md:flex-row justify-between items-center gap-4">
            <form method="GET" action="employees.php" class="flex-grow md:max-w-md">
                <div class="relative">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search_term); ?>" placeholder="Search by name or email..." class="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                    </div>
                </div>
            </form>
            <a href="add-employee.php" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-sm w-full md:w-auto text-center">
                + Add Employee
            </a>
        </div>
    </div>

    <?php if (!empty($message)): ?>
        <div class="mb-4 p-4 rounded <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
    
    <div class="bg-white rounded-lg shadow-lg overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Employee Name</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Roles</th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($users)): ?>
                        <tr><td colspan="3" class="px-6 py-10 text-center text-gray-500">No employees found matching your criteria.</td></tr>
                    <?php else: ?>
                        <?php foreach ($users as $user): ?>
                            <tr class="hover:bg-gray-50 transition-colors duration-200">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-semibold text-gray-900"><?php echo htmlspecialchars($user['name']); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($user['email']); ?></div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600"><?php echo htmlspecialchars($user['roles'] ?? 'No roles assigned'); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium flex items-center gap-4">
                                    <a href="employee-profile.php?id=<?php echo $user['id']; ?>" class="text-blue-600 hover:text-blue-900">View</a>
                                    <a href="edit-employee.php?id=<?php echo $user['id']; ?>" class="text-green-600 hover:text-green-900">Edit</a>
                                    
                                    <?php if ($is_admin_or_manager && $user['id'] != $_SESSION['user_id']): ?>
                                    <form method="POST" action="login_as_user.php">
                                        <input type="hidden" name="user_id_to_login" value="<?php echo $user['id']; ?>">
                                        <button type="submit" class="text-yellow-600 hover:text-yellow-900">Login</button>
                                    </form>
                                    <?php endif; ?>

                                    <form method="POST" action="employees.php" onsubmit="return confirm('Are you sure you want to reset this user\'s password?');">
                                        <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                        <button type="submit" name="reset_password" class="text-red-600 hover:text-red-900">Reset Password</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>