<?php
/**
 * Plugin Name: LCP Visualize
 * Description: Data visualization blocks using D3.js
 * Version: 1.0.0
 * Author: LCP
 */

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

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

    // Register AG Grid styles
    wp_register_style(
        'ag-grid',
        'https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css',
        [],
        '27.1.0'
    );

    wp_register_style(
        'ag-grid-theme',
        'https://unpkg.com/ag-grid-community/dist/styles/ag-theme-balham.css',
        [],
        '27.1.0'
    );

    // Register Bar Graph block
    register_block_type_from_metadata(
        __DIR__ . '/blocks/bar-graph/build',
        array(
            'editor_style' => ['ag-grid', 'ag-grid-theme'],
            'render_callback' => 'render_block_lcp_bar_graph'
        )
    );

    // Register Line Graph block
    register_block_type_from_metadata(
        __DIR__ . '/blocks/line-graph/build',
        array(
            'editor_style' => ['ag-grid', 'ag-grid-theme'],
            'render_callback' => 'render_block_lcp_line_graph'
        )
    );
}
add_action('init', 'lcp_visualize_register_blocks');

function render_block_lcp_bar_graph($attributes) {
    wp_enqueue_style('ag-grid');
    wp_enqueue_style('ag-grid-theme');
    
    $wrapper_attributes = get_block_wrapper_attributes([
        'class' => 'wp-block-lcp-bar-graph'
    ]);

    $chart_data = $attributes['chartData'] ?? [];
    $chart_data_json = wp_json_encode($chart_data);

    ob_start();
    ?>
    <div <?php echo $wrapper_attributes; ?>>
        <div class="lcp-bar-graph-container" data-chart='<?php echo esc_attr($chart_data_json); ?>'></div>
    </div>
    <?php
    return ob_get_clean();
}

function render_block_lcp_line_graph($attributes) {
    wp_enqueue_style('ag-grid');
    wp_enqueue_style('ag-grid-theme');
    
    $wrapper_attributes = get_block_wrapper_attributes([
        'class' => 'wp-block-lcp-line-graph'
    ]);

    $chart_data = $attributes['chartData'] ?? [];
    $chart_data_json = wp_json_encode($chart_data);

    ob_start();
    ?>
    <div <?php echo $wrapper_attributes; ?>>
        <div class="lcp-line-graph-container" data-chart='<?php echo esc_attr($chart_data_json); ?>'></div>
    </div>
    <?php
    return ob_get_clean();
}