<?php
/**
 * Block Template Manager
 *
 * @package NemtlyBooking\Core
 */

namespace NemtlyBooking\Core;

/**
 * Class to manage block templates from the plugin.
 */
class Block_Template_Manager {

    /**
     * Initialize hooks.
     */
    public function init() {
        // Register block template support
        add_filter( 'get_block_templates', [ $this, 'add_block_templates' ], 10, 3 );
        add_filter( 'get_block_template', [ $this, 'get_block_template' ], 10, 3 );
    }

    /**
     * Add template to the list of available templates.
     *
     * @param array  $query_result Array of found templates.
     * @param array  $query        Arguments to retrieve templates.
     * @param string $template_type Template type.
     * @return array
     */
    public function add_block_templates( $query_result, $query, $template_type ) {
        if ( 'wp_template' !== $template_type ) {
            return $query_result;
        }

        $post_type = isset( $query['post_type'] ) ? $query['post_type'] : '';
        $slugs     = isset( $query['slug__in'] ) ? $query['slug__in'] : [];

        $templates_to_check = [
            'single-nemtly_event'         => 'single-nemtly_event',
            'archive-nemtly_event'        => 'archive-nemtly_event',
            'single-nemtly_event-modern'  => 'single-nemtly_event-modern',
            'archive-nemtly_event-modern' => 'archive-nemtly_event-modern',
        ];

        foreach ( $templates_to_check as $slug => $file_slug ) {
            if ( ! empty( $slugs ) && ! in_array( $slug, $slugs, true ) ) {
                continue;
            }

            $has_template = false;
            foreach ( $query_result as $template ) {
                if ( $slug === $template->slug ) {
                    $has_template = true;
                    break;
                }
            }

            if ( ! $has_template ) {
                $template = $this->get_template_object( $slug );
                if ( $template ) {
                    $query_result[] = $template;
                }
            }
        }

        return $query_result;
    }

    /**
     * Get the template object/content when requested.
     *
     * @param \WP_Block_Template|null $block_template The found block template.
     * @param string                 $id             Template ID (e.g. theme-slug//single-nemtly_event).
     * @param string                 $template_type  Template type.
     * @return \WP_Block_Template|null
     */
    public function get_block_template( $block_template, $id, $template_type ) {
        if ( 'wp_template' !== $template_type ) {
            return $block_template;
        }

        // A theme file or a Site Editor customization already resolved — let it
        // win. Ours is only a fallback for when nothing else provides one.
        if ( $block_template ) {
            return $block_template;
        }

        // Check if this is one of our templates
        // ID format: theme_slug//template_slug
        $parts = explode( '//', $id );
        if ( count( $parts ) < 2 ) {
            return $block_template;
        }

        $slug = $parts[1];

        $our_slugs = [
            'single-nemtly_event',
            'archive-nemtly_event',
            'single-nemtly_event-modern',
            'archive-nemtly_event-modern',
        ];

        if ( in_array( $slug, $our_slugs, true ) ) {
            // Return our template object if it exists
            $template = $this->get_template_object( $slug );
			if ( $template ) {
				return $template;
			}
        }

        return $block_template;
    }

    /**
     * Create a WP_Block_Template object from our plugin file.
     *
     * @param string $slug Template slug.
     * @return \WP_Block_Template|null
     */
    private function get_template_object( $slug ) {
        $file_path = NEMTLY_BOOKING_PATH . 'templates/' . $slug . '.html';

        if ( ! file_exists( $file_path ) ) {
            return null;
        }

        $content = file_get_contents( $file_path );

        $template                 = new \WP_Block_Template();
        $template->type           = 'wp_template';
        $template->author         = 'Nemtly';
        $template->theme          = get_stylesheet(); // Emulate being part of the active theme
        $template->slug           = $slug;
        $template->id             = get_stylesheet() . '//' . $slug;
        $template->title          = $this->get_template_title( $slug );
        $template->description    = $this->get_template_description( $slug );
        $template->content        = $content;
        $template->source         = 'plugin';
        $template->status         = 'publish';
        $template->has_theme_file = false;
        $template->is_custom      = false;
        $template->post_types     = [ 'nemtly_event' ]; // Associate with our CPT

        return $template;
    }

    /**
     * Get English title for template.
     *
     * @param string $slug Template slug.
     * @return string
     */
    private function get_template_title( $slug ) {
        if ( 'single-nemtly_event' === $slug ) {
            return __( 'Single Event', 'nemtly-booking' );
        }
        if ( 'archive-nemtly_event' === $slug ) {
            return __( 'Events Archive', 'nemtly-booking' );
        }
        if ( 'single-nemtly_event-modern' === $slug ) {
            return __( 'Single Event (Modern)', 'nemtly-booking' );
        }
        if ( 'archive-nemtly_event-modern' === $slug ) {
            return __( 'Events Archive (Modern)', 'nemtly-booking' );
        }
        return $slug;
    }

    /**
     * Get description for template.
     *
     * @param string $slug Template slug.
     * @return string
     */
	private function get_template_description( $slug ) {
        if ( 'single-nemtly_event' === $slug ) {
            return __( 'The default template for displaying a single event.', 'nemtly-booking' );
        }
        if ( 'archive-nemtly_event' === $slug ) {
            return __( 'The default template for displaying the list of events.', 'nemtly-booking' );
        }
        if ( 'single-nemtly_event-modern' === $slug ) {
            return __( 'A modern, SEO-friendly template for displaying a single event.', 'nemtly-booking' );
        }
        if ( 'archive-nemtly_event-modern' === $slug ) {
            return __( 'A modern, SEO-friendly template for displaying the list of events.', 'nemtly-booking' );
        }
        return '';
    }
}
