<?php
if (!defined('ABSPATH')) {
    exit;
}

function launchmind_register_blocks() {
    if (!function_exists('register_block_type')) {
        return;
    }

    // Register custom block category
    add_filter('block_categories_all', function($categories) {
        return array_merge(
            array(
                array(
                    'slug' => 'launchmind',
                    'title' => __('Launchmind', 'launchmind-blog'),
                    'icon' => 'media-document',
                ),
            ),
            $categories
        );
    }, 10, 1);

    $base_url = LAUNCHMIND_BLOG_PLUGIN_URL . 'blocks/';
    $version = LAUNCHMIND_BLOG_VERSION;

    // Blog list block assets
    wp_register_script(
        'launchmind-blog-list-block',
        $base_url . 'blog-list/block.js',
        array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n', 'wp-block-editor'),
        $version,
        true
    );
    wp_localize_script('launchmind-blog-list-block', 'launchmindBlock', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('launchmind_admin'),
    ));

    wp_register_style(
        'launchmind-blog-list-style',
        $base_url . 'blog-list/style.css',
        array(),
        $version
    );
    wp_register_style(
        'launchmind-blog-list-editor',
        $base_url . 'blog-list/editor.css',
        array('wp-edit-blocks'),
        $version
    );

    register_block_type('launchmind/blog-list', array(
        'editor_script' => 'launchmind-blog-list-block',
        'style' => 'launchmind-blog-list-style',
        'editor_style' => 'launchmind-blog-list-editor',
        'render_callback' => 'launchmind_render_blog_list_block',
        'attributes' => array(
            'postsLimit' => array('type' => 'number', 'default' => 6),
            'columns' => array('type' => 'number', 'default' => 3),
            'layout' => array('type' => 'string', 'default' => 'grid'),
            'showExcerpt' => array('type' => 'boolean', 'default' => true),
            'showDate' => array('type' => 'boolean', 'default' => true),
            'showImage' => array('type' => 'boolean', 'default' => true),
            'showReadMore' => array('type' => 'boolean', 'default' => true),
            'cardStyle' => array('type' => 'string', 'default' => 'elevated'),
            'heading' => array('type' => 'string', 'default' => ''),
            'subtitle' => array('type' => 'string', 'default' => ''),
            'showBranding' => array('type' => 'boolean', 'default' => false),
        ),
    ));

    // Single post block assets
    wp_register_script(
        'launchmind-blog-post-block',
        $base_url . 'blog-post/block.js',
        array('wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-i18n', 'wp-block-editor'),
        $version,
        true
    );

    wp_register_style(
        'launchmind-blog-post-style',
        $base_url . 'blog-post/style.css',
        array(),
        $version
    );

    register_block_type('launchmind/blog-post', array(
        'editor_script' => 'launchmind-blog-post-block',
        'style' => 'launchmind-blog-post-style',
        'render_callback' => 'launchmind_render_blog_post_block',
        'attributes' => array(
            'slug' => array('type' => 'string', 'default' => ''),
            'showTitle' => array('type' => 'boolean', 'default' => true),
            'showDate' => array('type' => 'boolean', 'default' => true),
            'showAuthor' => array('type' => 'boolean', 'default' => true),
            'showImage' => array('type' => 'boolean', 'default' => true),
            'showTags' => array('type' => 'boolean', 'default' => true),
        ),
    ));
}
add_action('init', 'launchmind_register_blocks');

function launchmind_render_blog_list_block($attributes) {
    $defaults = array(
        'postsLimit' => 6,
        'columns' => 3,
        'layout' => 'grid',
        'showExcerpt' => true,
        'showDate' => true,
        'showImage' => true,
        'showReadMore' => true,
        'cardStyle' => 'elevated',
        'heading' => '',
        'subtitle' => '',
        'showBranding' => false,
    );
    $atts = wp_parse_args($attributes, $defaults);

    $posts = Launchmind_API::get_posts(array('limit' => (int) $atts['postsLimit']));
    if (is_wp_error($posts)) {
        return '<div class="lm-block-error">' . esc_html($posts->get_error_message()) . '</div>';
    }

    ob_start();
    $columns = max(1, min(4, (int) $atts['columns']));
    $layout_class = $atts['layout'] === 'list' ? ' lm-block-grid--list' : '';
    ?>
    <div class="lm-block">
        <?php if (!empty($atts['heading']) || !empty($atts['subtitle'])): ?>
            <div class="lm-block-header">
                <?php if (!empty($atts['heading'])): ?><h2><?php echo esc_html($atts['heading']); ?></h2><?php endif; ?>
                <?php if (!empty($atts['subtitle'])): ?><p><?php echo esc_html($atts['subtitle']); ?></p><?php endif; ?>
            </div>
        <?php endif; ?>
        <div class="lm-block-grid lm-columns-<?php echo (int) $columns; ?><?php echo esc_attr($layout_class); ?>">
            <?php foreach ($posts as $post): ?>
                <article class="lm-block-card lm-block-card--<?php echo esc_attr($atts['cardStyle']); ?>">
                    <?php if (!empty($atts['showImage']) && !empty($post['coverImage'])): ?>
                        <img src="<?php echo esc_url($post['coverImage']); ?>" alt="<?php echo esc_attr($post['title']); ?>">
                    <?php endif; ?>
                    <div class="lm-block-card__content">
                        <?php if (!empty($atts['showDate']) && !empty($post['publishedAt'])): ?>
                            <span class="lm-block-card__date"><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($post['publishedAt']))); ?></span>
                        <?php endif; ?>
                        <h3><?php echo esc_html($post['title']); ?></h3>
                        <?php if (!empty($atts['showExcerpt']) && !empty($post['excerpt'])): ?>
                            <p><?php echo esc_html(wp_trim_words($post['excerpt'], 22)); ?></p>
                        <?php endif; ?>
                        <?php if (!empty($atts['showReadMore'])): ?>
                            <span class="lm-block-card__link"><?php esc_html_e('Read more', 'launchmind-blog'); ?> →</span>
                        <?php endif; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </div>
        <?php if (!empty($atts['showBranding']) && !empty($posts)): ?>
            <div class="lm-block-branding"><?php esc_html_e('Blog powered by Launchmind.io', 'launchmind-blog'); ?></div>
        <?php endif; ?>
    </div>
    <?php
    return ob_get_clean();
}

function launchmind_render_blog_post_block($attributes) {
    $defaults = array(
        'slug' => '',
        'showTitle' => true,
        'showDate' => true,
        'showAuthor' => true,
        'showImage' => true,
        'showTags' => true,
    );
    $atts = wp_parse_args($attributes, $defaults);

    if (empty($atts['slug'])) {
        return '<div class="lm-block-error">' . esc_html__('Please set a post slug.', 'launchmind-blog') . '</div>';
    }

    $post = Launchmind_API::get_post($atts['slug']);
    if (is_wp_error($post) || empty($post)) {
        return '<div class="lm-block-error">' . esc_html__('Post not found.', 'launchmind-blog') . '</div>';
    }

    ob_start();
    ?>
    <article class="lm-post-block">
        <?php if (!empty($atts['showTitle'])): ?><h2><?php echo esc_html($post['title']); ?></h2><?php endif; ?>
        <?php if (!empty($atts['showDate']) || !empty($atts['showAuthor'])): ?>
            <div class="lm-post-meta">
                <?php if (!empty($atts['showDate']) && !empty($post['publishedAt'])): ?>
                    <time datetime="<?php echo esc_attr($post['publishedAt']); ?>"><?php echo esc_html(date_i18n(get_option('date_format'), strtotime($post['publishedAt']))); ?></time>
                <?php endif; ?>
                <?php if (!empty($atts['showAuthor']) && !empty($post['author'])): ?>
                    <span class="lm-post-author"><?php echo esc_html($post['author']); ?></span>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        <?php if (!empty($atts['showImage']) && !empty($post['coverImage'])): ?>
            <div class="lm-post-image"><img src="<?php echo esc_url($post['coverImage']); ?>" alt="<?php echo esc_attr($post['title']); ?>"></div>
        <?php endif; ?>
        <div class="lm-post-body"><?php echo wp_kses_post($post['html']); ?></div>
        <?php if (!empty($atts['showTags']) && !empty($post['tags'])): ?>
            <div class="lm-post-tags">
                <?php foreach ($post['tags'] as $tag): ?>
                    <span class="lm-tag"><?php echo esc_html($tag); ?></span>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </article>
    <?php
    return ob_get_clean();
}
