<?php
class TrainingContent
{
    public static function all(bool $activeOnly = false): array
    {
        Database::migrate();
        $sql = 'SELECT tc.*, (SELECT COUNT(*) FROM training_orders o WHERE o.content_id = tc.id) AS total_orders FROM training_contents tc';
        if ($activeOnly) {
            $sql .= ' WHERE tc.is_active = 1';
        }
        $sql .= ' ORDER BY tc.is_active DESC, tc.created_at DESC';
        return Database::pdo()->query($sql)->fetchAll();
    }

    public static function find(int $id): ?array
    {
        Database::migrate();
        $stmt = Database::pdo()->prepare('SELECT * FROM training_contents WHERE id = ? LIMIT 1');
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public static function save(array $data, array $file = [], array $coverFile = []): array
    {
        Database::migrate();
        $title = trim((string)($data['title'] ?? ''));
        $description = trim((string)($data['description'] ?? ''));
        $type = trim((string)($data['content_type'] ?? 'ebook'));
        $videoUrl = trim((string)($data['video_url'] ?? ''));
        $price = parse_money_br($data['price'] ?? '0');
        if ($title === '' || !in_array($type, ['ebook', 'manual', 'video'], true)) {
            return ['ok' => false, 'message' => 'Informe título e tipo de conteúdo válidos.'];
        }
        if ($type === 'video' && !is_valid_http_url($videoUrl)) {
            return ['ok' => false, 'message' => 'Informe um link HTTP ou HTTPS válido para a videoaula.'];
        }
        if ($type !== 'video' && (empty($file) || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK)) {
            return ['ok' => false, 'message' => 'Selecione o arquivo do e-book ou manual.'];
        }

        $cover = save_cover_image_upload($coverFile, 'formacao_instrutores');
        if (!$cover['ok']) {
            return ['ok' => false, 'message' => $cover['message']];
        }

        $filePath = null;
        $originalName = null;
        $mime = null;
        $size = null;
        if ($type !== 'video') {
            $size = (int)($file['size'] ?? 0);
            if ($size <= 0 || $size > 30 * 1024 * 1024) {
                delete_storage_file($cover['path']);
                return ['ok' => false, 'message' => 'O arquivo deve ter no máximo 30 MB.'];
            }
            $finfo = new finfo(FILEINFO_MIME_TYPE);
            $mime = (string)$finfo->file($file['tmp_name']);
            $allowed = [
                'application/pdf' => 'pdf',
                'application/epub+zip' => 'epub',
                'application/msword' => 'doc',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
                'image/jpeg' => 'jpg',
                'image/png' => 'png',
                'image/webp' => 'webp',
            ];
            if (!isset($allowed[$mime])) {
                delete_storage_file($cover['path']);
                return ['ok' => false, 'message' => 'Formato não permitido. Use PDF, EPUB, DOC, DOCX ou imagem.'];
            }
            $dir = STORAGE_PATH . '/training_contents';
            if (!is_dir($dir)) {
                mkdir($dir, 0775, true);
            }
            $filename = bin2hex(random_bytes(20)) . '.' . $allowed[$mime];
            if (!move_uploaded_file($file['tmp_name'], $dir . '/' . $filename)) {
                delete_storage_file($cover['path']);
                return ['ok' => false, 'message' => 'Falha ao armazenar o arquivo.'];
            }
            $filePath = 'storage/training_contents/' . $filename;
            $originalName = basename((string)($file['name'] ?? $filename));
        }

        try {
            $stmt = Database::pdo()->prepare('INSERT INTO training_contents (title, description, content_type, file_path, original_name, mime_type, file_size, video_url, price, cover_path, cover_mime_type, is_active, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)');
            $stmt->execute([
                $title,
                $description,
                $type,
                $filePath,
                $originalName,
                $mime,
                $size,
                $type === 'video' ? $videoUrl : null,
                $price,
                $cover['path'],
                $cover['mime'],
                date('Y-m-d H:i:s'),
            ]);
        } catch (Throwable $e) {
            delete_storage_file($filePath);
            delete_storage_file($cover['path']);
            return ['ok' => false, 'message' => 'Não foi possível cadastrar o conteúdo.'];
        }

        return ['ok' => true, 'message' => 'Conteúdo cadastrado com imagem na área de Formação de Instrutores.'];
    }

    public static function updateCover(int $id, array $coverFile): array
    {
        Database::migrate();
        $record = self::find($id);
        if (!$record) {
            return ['ok' => false, 'message' => 'Registro não encontrado.'];
        }
        $cover = save_cover_image_upload($coverFile, 'formacao_instrutores');
        if (!$cover['ok']) {
            return ['ok' => false, 'message' => $cover['message']];
        }
        if (empty($cover['path'])) {
            return ['ok' => false, 'message' => 'Selecione uma imagem JPG, PNG ou WEBP.'];
        }
        try {
            $stmt = Database::pdo()->prepare('UPDATE training_contents SET cover_path = ?, cover_mime_type = ? WHERE id = ?');
            $stmt->execute([$cover['path'], $cover['mime'], $id]);
        } catch (Throwable $e) {
            delete_storage_file($cover['path']);
            return ['ok' => false, 'message' => 'Não foi possível atualizar a imagem.'];
        }
        delete_storage_file($record['cover_path'] ?? null);
        return ['ok' => true, 'message' => 'Imagem atualizada com sucesso.'];
    }

    public static function toggle(int $id): bool
    {
        $stmt = Database::pdo()->prepare('UPDATE training_contents SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->rowCount() > 0;
    }

    public static function delete(int $id): array
    {
        $content = self::find($id);
        if (!$content) {
            return ['ok' => false, 'message' => 'Conteúdo não encontrado.'];
        }
        $stmt = Database::pdo()->prepare('DELETE FROM training_contents WHERE id = ?');
        $stmt->execute([$id]);
        delete_storage_file($content['file_path'] ?? null);
        delete_storage_file($content['cover_path'] ?? null);
        return ['ok' => true, 'message' => 'Conteúdo apagado.'];
    }

    public static function stream(array $content): never
    {
        $path = ROOT_PATH . '/' . ltrim((string)($content['file_path'] ?? ''), '/');
        if (!is_file($path)) {
            http_response_code(404);
            exit('Arquivo não encontrado.');
        }
        header('Content-Type: ' . (($content['mime_type'] ?? '') ?: 'application/octet-stream'));
        header('Content-Length: ' . filesize($path));
        header('Content-Disposition: inline; filename="' . str_replace('"', '', (string)($content['original_name'] ?? basename($path))) . '"');
        readfile($path);
        exit;
    }

    public static function streamCover(array $content): never
    {
        stream_storage_image($content['cover_path'] ?? null, $content['cover_mime_type'] ?? null);
    }
}
