<?php
declare(strict_types=1);

namespace Help4BuilderSuite\Modules\Industry;

use Help4BuilderSuite\Contracts\ModuleContract;
use WP_REST_Response;

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

final class Module implements ModuleContract
{
    public function key(): string
    {
        return 'industry';
    }

    public function boot(): void
    {
        add_action('init', [$this, 'registerTaxonomy']);
        add_action('rest_api_init', [$this, 'registerRestRoutes']);
        add_shortcode('h4_industry_templates', [$this, 'renderIndustryTemplates']);
    }

    public function registerTaxonomy(): void
    {
        register_taxonomy(
            'h4_industry',
            ['post', 'page', 'h4_template', 'h4_slider'],
            [
                'label'        => __('Help4 Industry Packs', 'help4-builder-suite'),
                'show_ui'      => true,
                'show_in_rest' => true,
                'rewrite'      => ['slug' => 'industry-pack'],
            ]
        );

        foreach (array_keys($this->packs()) as $slug) {
            if (! term_exists($slug, 'h4_industry')) {
                wp_insert_term(ucfirst($slug), 'h4_industry', ['slug' => $slug]);
            }
        }
    }

    public function registerRestRoutes(): void
    {
        register_rest_route(
            'h4bs/v1',
            '/industry-packs',
            [
                'methods'             => 'GET',
                'callback'            => [$this, 'listPacks'],
                'permission_callback' => '__return_true',
            ]
        );
    }

    public function listPacks(): WP_REST_Response
    {
        return new WP_REST_Response(['items' => $this->packs()]);
    }

    /**
     * @param array<string, mixed> $atts
     */
    public function renderIndustryTemplates(array $atts): string
    {
        $atts = shortcode_atts(['industry' => 'doctors', 'limit' => 12], $atts, 'h4_industry_templates');
        $industry = sanitize_key((string) $atts['industry']);
        $postStatus = current_user_can('edit_posts') ? ['publish', 'draft'] : ['publish'];

        // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Industry template shortcode intentionally filters the template CPT by its taxonomy.
        $items = get_posts(
            [
                'post_type'      => 'h4_template',
                'post_status'    => $postStatus,
                'posts_per_page' => max(1, min(24, (int) $atts['limit'])),
                'tax_query'      => [
                    [
                        'taxonomy' => 'h4_industry',
                        'field'    => 'slug',
                        'terms'    => [$industry],
                    ],
                ],
            ]
        );
        // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_tax_query

        if (! $items) {
            return '<p>No templates exist for this industry yet.</p>';
        }

        ob_start();
        ?>
        <div class="h4bs-template-library">
            <?php foreach ($items as $item) : ?>
                <article class="h4bs-template-card">
                    <h3><?php echo esc_html($item->post_title); ?></h3>
                    <p><?php echo esc_html(wp_trim_words($item->post_excerpt ?: $item->post_content, 18)); ?></p>
                    <?php if (current_user_can('edit_post', $item->ID)) : ?>
                        <a href="<?php echo esc_url(get_edit_post_link($item->ID)); ?>">
                            <?php esc_html_e('Edit Template', 'help4-builder-suite'); ?>
                        </a>
                    <?php endif; ?>
                </article>
            <?php endforeach; ?>
        </div>
        <?php
        return (string) ob_get_clean();
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    private function packs(): array
    {
        return [
            'doctors' => [
                'name'     => 'Doctors',
                'features' => [
                    'Appointment CTA and scheduling templates',
                    'Medical service schema starter',
                    'Clinic map and provider profile blocks',
                ],
            ],
            'lawyers' => [
                'name'     => 'Lawyers',
                'features' => [
                    'Practice area template clusters',
                    'Attorney profile cards',
                    'Case result and disclaimer block starter',
                ],
            ],
            'realtors' => [
                'name'     => 'Realtors',
                'features' => [
                    'MLS / IDX provider settings hook',
                    'Listing + map page templates',
                    'Neighborhood spotlight sections',
                ],
            ],
            'roofers' => [
                'name'     => 'Roofers',
                'features' => [
                    'Service area map sections',
                    'Estimate request templates',
                    'Before/after project gallery blocks',
                ],
            ],
            'trades' => [
                'name'     => 'Trades',
                'features' => [
                    'Dispatcher style contact templates',
                    'Emergency service CTA layouts',
                    'Crew and credentials showcase blocks',
                ],
            ],
        ];
    }
}
