<?php

namespace App\Services;

use App\Core\Database;

class HomepageMarketplaceService
{
    public static function catalog(int $orgId = 0): array
    {
        $db = Database::getInstance();

        $stmt = $db->query("

            SELECT

                /*----------------------------------------------------
                Template Identity
                ----------------------------------------------------*/

                t.id                 AS template_id,
                t.id                 AS apply_id,

                /*----------------------------------------------------
                Template Information
                ----------------------------------------------------*/

                t.name,
                t.version_no,
                t.sections_json,
                t.blocks_json,
                t.is_favorite,
                t.org_id,

                t.created_at         AS template_created_at,
                t.created_by         AS template_created_by,

                /*----------------------------------------------------
                Marketplace Information
                ----------------------------------------------------*/

                m.id                AS marketplace_id,
                m.title,
                m.description,
                m.category,
                m.preview_image,
                m.is_public,
                m.created_by        AS marketplace_created_by,
                m.created_at        AS marketplace_created_at

            FROM conference_home_templates t

            LEFT JOIN conference_home_marketplace m
                   ON m.template_id=t.id

            ORDER BY

                COALESCE(
                    m.created_at,
                    t.created_at
                ) DESC,

                t.id DESC

        ");

        return
            $stmt->fetchAll(\PDO::FETCH_ASSOC)
            ?: [];
    }

    public static function publish(
        int $templateId,
        string $title,
        string $description,
        string $category,
        int $userId
    ): bool
    {
        $db = Database::getInstance();

        return $db->prepare("

            INSERT INTO conference_home_marketplace
            (
                template_id,
                title,
                description,
                category,
                is_public,
                created_by
            )
            VALUES
            (
                ?, ?, ?, ?, 1, ?
            )

        ")->execute([

            $templateId,
            $title,
            $description,
            $category,
            $userId

        ]);
    }
}
