<?php

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

if (!class_exists('babPlugin')) {
    class babPlugin
    {
        public function __construct()
        {
            add_action('plugins_loaded', [$this, 'pluginsDependency']);
            add_action('admin_enqueue_scripts', [$this, 'adminEnqueueScripts']);
            add_shortcode('accordion', [$this, 'bab_shortcode_handler']);
            add_action('enqueue_block_assets', [$this, 'enqueueBlockAssets']);

        }
        public function pluginsDependency()
        {
            require_once BAB_DIR_PATH . 'includes/function.php';
            require_once BAB_DIR_PATH . 'accordion-block.php';
            require_once BAB_DIR_PATH . 'includes/class_babAdmin.php';
        }
        public function adminEnqueueScripts($screen)
        {
            global $typenow;

            if ('accordion_block' === $typenow) {
                wp_enqueue_script('shortcode-js', BAB_DIR_URL . '/build/shortcode.js', [], BAB_PLUGIN_VERSION, true);
                wp_enqueue_style('shortcode-css', BAB_DIR_URL . '/build/shortcode.css', [], BAB_PLUGIN_VERSION);
            }

            if ('accordion_block_page_bab_Dashboard' === $screen) {
                $asset = include BAB_DIR_PATH . 'build/admin-dashboard.asset.php';
                wp_enqueue_script('vgb-admin-script', BAB_DIR_URL . 'build/admin-dashboard.js', array_merge($asset['dependencies'], ['wp-util']), BAB_PLUGIN_VERSION, true);

                wp_enqueue_style('vgb-admin-style', BAB_DIR_URL . '/build/admin-dashboard.css', false, BAB_PLUGIN_VERSION);
            }

        }
        public function enqueueBlockAssets()
        {
            wp_register_script('zebra_accordion', BAB_ASSETS_DIR . 'js/zebra_accordion.min.js', ['jquery'], BAB_PLUGIN_VERSION, true);
        }
        public function bab_shortcode_handler($atts)
        {
            $atts = shortcode_atts(
                array(
                    'id' => 0
                ),
                $atts,
                'accordion'
            );
            $post_id = intval($atts['id']);
            if (!$post_id) {
                return '<p>Please provide a valid ID.</p>';
            }
            $post = get_post(absint($post_id));
            if (
                !$post ||
                $post->post_type !== 'accordion_block' ||
                $post->post_status !== 'publish'
            ) {
                return '<p>Invalid accordion ID.</p>';
            }

            $blocks = parse_blocks($post->post_content);

            if (!empty($blocks)) {
                $output = '';
                foreach ($blocks as $block) {
                    $output .= render_block($block);
                }
                return $output;
            }
            return '';
        }
    }
}
