<?php
// Sirf config.php ko shaamil karein, jisse session aur database connection mil jayega
require_once 'config.php';

// userHasRole function ko yahan define karein kyunki hum header.php include nahi kar rahe
if (!function_exists('userHasRole')) {
    function userHasRole($required_roles) {
        if (!isset($_SESSION['user_roles'])) return false;
        if (!is_array($required_roles)) {
            $required_roles = [$required_roles];
        }
        return count(array_intersect($required_roles, $_SESSION['user_roles'])) > 0;
    }
}

// Suraksha jaanch: Sirf admin/manager hi is feature ka istemal kar sakte hain
if (!isset($_SESSION['user_id']) || !userHasRole(['Admin', 'Manager'])) {
    // Agar permission nahi hai, to dashboard par bhej dein
    header("Location: dashboard.php");
    exit();
}

// Jis user ki ID mein login karna hai, use prapt karein
$user_id_to_login = $_POST['user_id_to_login'] ?? null;

if ($user_id_to_login) {
    // Admin ki original ID ko session mein store karein taaki hum wapas aa sakein
    if (!isset($_SESSION['admin_id'])) {
        $_SESSION['admin_id'] = $_SESSION['user_id'];
        $_SESSION['admin_name'] = $_SESSION['user_name'];
        $_SESSION['admin_roles'] = $_SESSION['user_roles'];
    }

    // Naye user ki details database se nikalein
    $sql = "SELECT u.id, u.name, 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 u.id = ? 
            GROUP BY u.id";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id_to_login);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();

        // Session ko naye user ki details se overwrite karein
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        $_SESSION['user_roles'] = !empty($user['roles']) ? explode(',', $user['roles']) : [];

        // User ko uske profile page par TURANT bhej dein
        header("Location: employee-profile.php?id=" . $user['id']);
        exit();
    }
}

// Agar koi samasya ho, to wapas employees page par bhej dein
header("Location: employees.php");
exit();
?>