<?php

class Auth
{
    public static function check()
    {
        if (!isset($_SESSION['user_id'])) {
            return false;
        }

        $timeout = defined('SESSION_TIMEOUT') ? SESSION_TIMEOUT : 28800;

        if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $timeout)) {
            session_destroy();
            return false;
        }

        $_SESSION['last_activity'] = time();
        return true;
    }

    public static function user()
    {
        if (!self::check()) {
            return null;
        }
        return $_SESSION;
    }

    public static function id()
    {
        return $_SESSION['user_id'] ?? null;
    }

    public static function role()
    {
        return $_SESSION['role'] ?? null;
    }

    public static function isAdmin()
    {
        return self::role() === 'ADMIN';
    }

    public static function isCapturist()
    {
        return self::role() === 'CAPTURIST' || self::isAdmin();
    }

    public static function isViewer()
    {
        return self::role() === 'VIEWER';
    }

    public static function isLector()
    {
        return self::role() === 'LECTOR';
    }

    public static function getAccessibleHouseIds()
    {
        $db = Database::getInstance();

        if (self::isAdmin()) {
            $result = $db->fetchAll("SELECT id FROM houses");
            return array_column($result, 'id');
        }
        elseif (self::isLector()) {
            $userId = self::id();
            $result = $db->fetchAll(
                "SELECT house_id FROM user_house_permissions WHERE user_id = ?",
            [$userId]
            );
            return array_column($result, 'house_id');
        }
        else {
            $result = $db->fetchAll("SELECT id FROM houses");
            return array_column($result, 'id');
        }
    }

    public static function canViewHouse($houseId)
    {
        if (self::isAdmin()) {
            return true;
        }
        $accessibleIds = self::getAccessibleHouseIds();
        return in_array($houseId, $accessibleIds);
    }

    public static function requireAuth()
    {
        if (!self::check()) {
            header('Location: /login.php');
            exit;
        }
    }

    public static function requireAdmin()
    {
        self::requireAuth();
        if (!self::isAdmin()) {
            header('Location: /dashboard.php');
            exit;
        }
    }

    public static function requireCapturist()
    {
        self::requireAuth();
        if (!self::isCapturist()) {
            header('Location: /dashboard.php');
            exit;
        }
    }

    public static function login($user)
    {
        session_regenerate_id(true);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];
        $_SESSION['first_name'] = $user['first_name'];
        $_SESSION['last_name'] = $user['last_name'];
        $_SESSION['last_activity'] = time();

        $db = Database::getInstance();
        $db->execute(
            "UPDATE users SET last_login = NOW() WHERE id = ?",
        [$user['id']]
        );

        self::logActivity('login', "Usuario {$user['username']} inició sesión");
    }

    public static function logout()
    {
        self::logActivity('logout', "Usuario {$_SESSION['username']} cerró sesión");
        session_destroy();
        header('Location: /login.php');
        exit;
    }

    public static function logActivity($action, $details = '')
    {
        if (!self::check()) {
            return;
        }

        $db = Database::getInstance();
        $db->execute(
            "INSERT INTO activity_logs (user_id, action, details, ip_address) VALUES (?, ?, ?, ?)",
        [
            self::id(),
            $action,
            $details,
            $_SERVER['REMOTE_ADDR'] ?? null
        ]
        );
    }
}