<?php

class User {
    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function login($username_or_pin, $password = null) {
        if ($password === null) {
            // Login with PIN
            $stmt = $this->pdo->prepare("SELECT * FROM users WHERE access_pin = ?");
            $stmt->execute([$username_or_pin]);
        } else {
            // Login with Username/Password
            $stmt = $this->pdo->prepare("SELECT * FROM users WHERE username = ?");
            $stmt->execute([$username_or_pin]);
        }
        
        $user = $stmt->fetch();

        if ($user) {
            if ($password === null || password_verify($password, $user['password'])) {
                 // Set session variables
                $_SESSION['user_id'] = $user['user_id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                return true;
            }
        }
        return false;
    }

    public function generateAccessPin($user_id) {
        // Generate a random 8-digit PIN
        $pin = mt_rand(10000000, 99999999);
        
        // Ensure uniqueness
        while ($this->pinExists($pin)) {
            $pin = mt_rand(10000000, 99999999);
        }

        $stmt = $this->pdo->prepare("UPDATE users SET access_pin = ? WHERE user_id = ?");
        if ($stmt->execute([$pin, $user_id])) {
            return $pin;
        }
        return false;
    }

    private function pinExists($pin) {
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM users WHERE access_pin = ?");
        $stmt->execute([$pin]);
        return $stmt->fetchColumn() > 0;
    }

    public function isLoggedIn() {
        return isset($_SESSION['user_id']);
    }

    public function isAdmin() {
        return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
    }

    public function isTeacher() {
        return isset($_SESSION['role']) && ($_SESSION['role'] === 'teacher' || $_SESSION['role'] === 'admin');
    }

    public function isStudent() {
        return isset($_SESSION['role']) && $_SESSION['role'] === 'student';
    }

    public function hasPermission($permission) {
        if ($this->isAdmin()) {
            return true;
        }
        if (!isset($_SESSION['permissions'])) {
            // Reload permissions if not in session (or fetch from DB)
            if (isset($_SESSION['user_id'])) {
                $stmt = $this->pdo->prepare("SELECT permissions FROM users WHERE user_id = ?");
                $stmt->execute([$_SESSION['user_id']]);
                $perms = $stmt->fetchColumn();
                $_SESSION['permissions'] = $perms ? json_decode($perms, true) : [];
            } else {
                return false;
            }
        }
        
        $perms = $_SESSION['permissions'];
        return is_array($perms) && in_array($permission, $perms);
    }

    public function logout() {
        session_destroy();
        unset($_SESSION['user_id']);
        unset($_SESSION['username']);
        unset($_SESSION['role']);
        unset($_SESSION['permissions']);
        return true;
    }

    public function register($username, $password, $role = 'student', $permissions = []) {
        // Check if username exists
        $stmt = $this->pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetchColumn() > 0) {
            return "Username already exists.";
        }

        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $perms_json = json_encode($permissions);
        
        $stmt = $this->pdo->prepare("INSERT INTO users (username, password, role, permissions) VALUES (?, ?, ?, ?)");
        
        if ($stmt->execute([$username, $hashed_password, $role, $perms_json])) {
            return true;
        }
        return "Registration failed.";
    }

    public function getAllStudents() {
        $stmt = $this->pdo->query("SELECT * FROM users WHERE role = 'student'");
        return $stmt->fetchAll();
    }
}
