<?php

class ApiAuth {
    public static function authenticate() {
        $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
        $customHeader = $_SERVER['HTTP_X_AUTH_TOKEN'] ?? '';

        // 1. Intentar JWT primero (para móvil) - header estándar
        if (preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
            require_once __DIR__ . '/JWT.php';
            $token = $matches[1];
            $decoded = JWT::decode($token);

            if ($decoded) {
                return $decoded;
            }

            http_response_code(401);
            echo json_encode([
                'success' => false,
                'message' => 'Token inválido o expirado'
            ]);
            exit;
        }

        // 2. Intentar JWT con header personalizado X-Auth-Token (fallback)
        if (!empty($customHeader)) {
            require_once __DIR__ . '/JWT.php';
            $decoded = JWT::decode($customHeader);

            if ($decoded) {
                return $decoded;
            }

            http_response_code(401);
            echo json_encode([
                'success' => false,
                'message' => 'Token inválido o expirado'
            ]);
            exit;
        }

        // 3. Fallback a sesión PHP (para web)
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        if (isset($_SESSION['user_id'])) {
            return [
                'user_id' => $_SESSION['user_id'],
                'username' => $_SESSION['username'],
                'role' => $_SESSION['role'],
                'first_name' => $_SESSION['first_name'] ?? '',
                'last_name' => $_SESSION['last_name'] ?? ''
            ];
        }

        // 4. Sin autenticación
        http_response_code(401);
        echo json_encode([
            'success' => false,
            'message' => 'No autenticado'
        ]);
        exit;
    }

    public static function requireAdmin() {
        $user = self::authenticate();

        if ($user['role'] !== 'ADMIN') {
            http_response_code(403);
            echo json_encode([
                'success' => false,
                'message' => 'Se requiere rol de Administrador'
            ]);
            exit;
        }

        return $user;
    }

    public static function requireCapturist() {
        $user = self::authenticate();

        if ($user['role'] !== 'ADMIN' && $user['role'] !== 'CAPTURIST') {
            http_response_code(403);
            echo json_encode([
                'success' => false,
                'message' => 'Se requiere rol de Capturista o Administrador'
            ]);
            exit;
        }

        return $user;
    }

    public static function getAccessibleHouseIds() {
        $user = self::authenticate();

        if ($user['role'] === 'ADMIN') {
            require_once __DIR__ . '/../models/House.php';
            $db = Database::getInstance();
            $result = $db->fetchAll("SELECT id FROM houses");
            return array_column($result, 'id');
        }

        if ($user['role'] === 'LECTOR') {
            require_once __DIR__ . '/../models/UserPermission.php';
            return UserPermission::getUserHouseIds($user['user_id']);
        }

        // VIEWER, CAPTURIST
        require_once __DIR__ . '/../models/House.php';
        $db = Database::getInstance();
        $result = $db->fetchAll("SELECT id FROM houses");
        return array_column($result, 'id');
    }

    public static function isLector() {
        $user = self::authenticate();
        return $user['role'] === 'LECTOR';
    }

    public static function getUserId() {
        $user = self::authenticate();
        return $user['user_id'];
    }

    public static function getRole() {
        $user = self::authenticate();
        return $user['role'];
    }
}
