<?php
// init.php ko shaamil karein, jo sab kuch setup karega
require_once 'init.php';

// Agar user pehle se log in hai, to use sahi page par bhej dein.
if (isset($_SESSION['user_id'])) {
    if (userHasRole(['Admin'])) {
        header("Location: dashboard.php");
    } else {
        header("Location: my_tasks.php");
    }
    exit();
}

// --- LOGIN LOGIC ---
$error_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty(trim($_POST["email"])) || empty(trim($_POST["password"]))) {
        $error_message = "Please enter both email and password.";
    } else {
        $email = trim($_POST['email']);
        $password_input = trim($_POST['password']);

        $sql = "SELECT id, name, password_hash FROM users WHERE email = ?";
        
        if ($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("s", $email);
            
            if ($stmt->execute()) {
                $result = $stmt->get_result();

                if ($result->num_rows == 1) {
                    $user = $result->fetch_assoc();
                    
                    if (password_verify($password_input, $user['password_hash'])) {
                        $roles_stmt = $conn->prepare("SELECT r.name FROM roles r JOIN user_roles ur ON r.id = ur.role_id WHERE ur.user_id = ?");
                        $roles_stmt->bind_param("i", $user['id']);
                        $roles_stmt->execute();
                        $roles_result = $roles_stmt->get_result();
                        
                        $user_roles = [];
                        while ($row = $roles_result->fetch_assoc()) {
                            $user_roles[] = $row['name'];
                        }
                        $roles_stmt->close();

                        $_SESSION['user_id'] = $user['id'];
                        $_SESSION['user_name'] = $user['name'];
                        $_SESSION['user_roles'] = $user_roles;

                        if (in_array('Admin', $user_roles)) {
                            header("Location: dashboard.php");
                        } else {
                            header("Location: my_tasks.php"); 
                        }
                        exit();

                    } else {
                        $error_message = "Invalid email or password.";
                    }
                } else {
                    $error_message = "Invalid email or password.";
                }
            } else {
                $error_message = "Oops! Something went wrong. Please try again later.";
            }
            $stmt->close();
        }
    }
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Digify OS</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center h-screen">
    <div class="w-full max-w-md bg-white rounded-lg shadow-md p-8">
        <div class="flex justify-center mb-6">
            <h1 class="text-3xl font-bold text-gray-800">Digify OS</h1>
        </div>
        
        <?php if (!empty($error_message)): ?>
            <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded" role="alert">
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <form method="POST" action="login.php">
            <div>
                <label for="email" class="block text-sm font-medium text-gray-700">Email Address</label>
                <input id="email" type="email" name="email" required autofocus class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm">
            </div>
            <div class="mt-4">
                <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
                <input id="password" type="password" name="password" required class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm">
            </div>

            <div class="flex items-center justify-end mt-4">
                <a href="forgot-password.php" class="text-sm text-blue-600 hover:underline">
                    Forgot Password?
                </a>
            </div>

            <div class="flex items-center justify-end mt-6">
                <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-white hover:bg-blue-700">
                    Log In
                </button>
            </div>
        </form>
    </div>
</body>
</html>