<?php
/**
 * Plugin Name:       Button
 * Description:       Example block scaffolded with Create Block tool.
 * Requires at least: 6.6
 * Requires PHP:      7.2
 * Version:           0.1.0
 * Author:            The WordPress Contributors
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       button
 *
 * @package CreateBlock
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Registers the block using the metadata loaded from the `block.json` file.
 * Behind the scenes, it registers also all assets so they can be enqueued
 * through the block editor in the corresponding context.
 *
 * @see https://developer.wordpress.org/reference/functions/register_block_type/
 */
function create_block_button_block_init() {
	register_block_type( __DIR__ . '/build' );
}
add_action( 'init', 'create_block_button_block_init' );


/* REST API */
function register_icons_rest_api_endpoint() {
    register_rest_route( 'lcp/v1', '/icons', array(
        'methods' => 'GET',
        'callback' => 'get_icons_data_from_db',
        'permission_callback' => '__return_true', // Public access; modify this if needed
    ) );
}

add_action( 'rest_api_init', 'register_icons_rest_api_endpoint' );

function get_icons_data_from_db() {
    global $wpdb;

    // Query the lcp_icons table
    $results = $wpdb->get_results(
        "SELECT id, name, paths, viewbox FROM {$wpdb->prefix}lcp_icons"
    );

    // If no icons are found, return an empty array
    if ( empty( $results ) ) {
        return [];
    }

    // Format the results for the frontend
    $icons = array_map( function( $icon ) {
        return [
            'iconSvgId' => $icon->id,           // Icon ID
            'iconSvgPaths' => $icon->paths,     // SVG paths (can be multiple)
            'selectedIconViewbox' => $icon->viewbox, // ViewBox for the SVG
            'name' => $icon->name,              // Add name field
        ];
    }, $results );

    return $icons;
}

