<?php

namespace MODELORA\Core;

if (! defined('ABSPATH')) {
    exit;
}

class PostType
{
    public static function register(): void
    {
        add_action('init', [__CLASS__, 'register_type']);
        add_filter('manage_modelora_model_posts_columns', [__CLASS__, 'add_shortcode_column']);
        add_action('manage_modelora_model_posts_custom_column', [__CLASS__, 'render_shortcode_column'], 10, 2);
    }

    public static function register_type(): void
    {
        register_post_type('modelora_model', [
            'labels' => [
                'name' => __('3D Models', 'modelora-3d-product-viewer'),
                'singular_name' => __('3D Model', 'modelora-3d-product-viewer'),
                'add_new_item' => __('Add New 3D Model', 'modelora-3d-product-viewer'),
                'edit_item' => __('Edit 3D Model', 'modelora-3d-product-viewer'),
            ],
            'public' => false,
            'show_ui' => true,
            'show_in_menu' => false,
            'show_in_rest' => true,
            'supports' => ['title', 'thumbnail'],
            'menu_icon' => 'dashicons-format-image',
        ]);
    }

    public static function add_shortcode_column(array $columns): array
    {
        $inserted = [];

        foreach ($columns as $key => $label) {
            $inserted[$key] = $label;

            if ($key === 'title') {
                $inserted['modelora_shortcode'] = __('Shortcode', 'modelora-3d-product-viewer');
            }
        }

        if (! isset($inserted['modelora_shortcode'])) {
            $inserted['modelora_shortcode'] = __('Shortcode', 'modelora-3d-product-viewer');
        }

        return $inserted;
    }

    public static function render_shortcode_column(string $column, int $post_id): void
    {
        if ($column !== 'modelora_shortcode') {
            return;
        }

        $shortcode = sprintf('[modelora_viewer id="%d"]', $post_id);

        printf(
            '<input type="text" class="widefat" readonly value="%s" onclick="this.select();" aria-label="%s" />',
            esc_attr($shortcode),
            esc_attr__('Viewer shortcode', 'modelora-3d-product-viewer')
        );
    }
}

