<?php
class MediaController
{
    public function ebookCover(): void
    {
        $ebookId = (int)($_GET['id'] ?? 0);
        $user = Auth::user();
        $ebook = null;
        if ($user && ($user['role'] ?? '') === 'admin') {
            $ebook = Ebook::find($ebookId);
        } elseif ($user && ($user['role'] ?? '') === 'student') {
            $ebook = Ebook::findForStudent($ebookId, (int)$user['id']);
        }
        if (!$ebook || empty($ebook['cover_path'])) {
            http_response_code(404);
            exit('Imagem não encontrada.');
        }
        Ebook::streamCover($ebook);
    }

    public function professionalMaterialCover(): void
    {
        $materialId = (int)($_GET['id'] ?? 0);
        $user = Auth::user();
        if ($user && ($user['role'] ?? '') === 'admin') {
            $material = ProfessionalMaterial::find($materialId);
        } else {
            $token = trim((string)($_GET['token'] ?? ''));
            $professional = $token !== '' ? Professional::findByToken($token) : Professional::current();
            $material = $professional ? ProfessionalMaterial::findAllowed($materialId, (int)$professional['id']) : null;
        }
        if (!$material || empty($material['cover_path'])) {
            http_response_code(404);
            exit('Imagem não encontrada.');
        }
        ProfessionalMaterial::streamCover($material);
    }

    public function trainingCover(): void
    {
        $content = TrainingContent::find((int)($_GET['id'] ?? 0));
        if (!$content || empty($content['cover_path'])) {
            http_response_code(404);
            exit('Imagem não encontrada.');
        }
        TrainingContent::streamCover($content);
    }
}
