<?php

declare(strict_types=1);

namespace BeycanPress\Tokenico;

use BeycanPress\Tokenico\Models\Presale;
use BeycanPress\Tokenico\PluginHero\Helpers;

class Shortcode
{
    /**
     * @var Presale
     */
    private Presale $presale;

    /**
     * Shortcode constructor.
     */
    public function __construct()
    {
        $this->presale = new Presale();
        add_action('init', [$this, 'init']);
    }

    /**
     * Register shortcode
     * @return void
     */
    public function init(): void
    {
        if (!defined('BP_TOKENICO_PRO_LOADED') || Helpers::getProp('premiumIsInitialized', false)) {
            add_shortcode('tokenico-list', [$this, 'list']);
            add_shortcode('tokenico-single', [$this, 'single']);
        }
    }

    /**
     * @param array<mixed> $atts
     * @return string
     */
    public function list(array $atts): string
    {
        $atts = shortcode_atts(
            [],
            $atts
        );

        [$records, $totalPage] = $this->presale->filter([
            'page' => 0,
        ]);

        Service::initAssets([
            'list' => true,
            'listProps' => [
                'records' => $records,
                'totalPage' => $totalPage,
            ],
        ]);

        return Helpers::view('shortcode/list');
    }

    /**
     * @param array<mixed> $atts
     * @return string
     */
    public function single(array $atts): string
    {
        $atts = shortcode_atts(
            [
                'key' => '',
            ],
            $atts
        );

        if (empty($atts['key'])) {
            return esc_html__('Presale key is required', 'tokenico');
        }

        $presale = $this->presale->findOneBy([
            'key' => $atts['key'],
            'premium' => defined('BP_TOKENICO_PRO_LOADED') ? 1 : 0,
        ]);

        if (empty($presale)) {
            return esc_html__('Presale not found', 'tokenico');
        }

        Service::initAssets([
            'single' => true,
            'singleProps' => [
                'presaleKey' => $atts['key'],
                'presaleRecord' => Service::presaleFormat($presale),
            ],
        ]);

        return Helpers::view('shortcode/single');
    }
}
