<?php
/**
 * Plugin Name:       Native Blocks
 * Description:       Custom blocks for gutenberg editor with native interface and settings
 * Version:           1.0.0
 * Requires at least: 6.7
 * Requires PHP:      7.4
 * Author:            Zakaria Binsaifullah
 * License:           GPLv2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       native-blocks
 *
 * @package Nativeblocks
 */

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

// Define Constants
define( 'NTVB_VERSION', '1.0.0' );
define( 'NTVB_PLUGIN_DIR', __DIR__ );
define( 'NTVB_URL_FILE', plugin_dir_url( __FILE__ ) );


// Admin
require_once NTVB_PLUGIN_DIR . '/admin/page.php';

// Require Block Assets
require_once NTVB_PLUGIN_DIR . '/includes/enqueue.php';

// Require Dynamic Styles
require_once NTVB_PLUGIN_DIR . '/includes/style-generate.php';

// Require SVG Upload
require_once NTVB_PLUGIN_DIR . '/includes/svg-upload.php';

/**
 * Register Block Types
 *
 */

function ntvb_register_blocks() {

	if ( function_exists( 'wp_register_block_types_from_metadata_collection' ) ) {
		wp_register_block_types_from_metadata_collection( __DIR__ . '/build/blocks', __DIR__ . '/build/blocks-manifest.php' );
		return;
	}

	if ( function_exists( 'wp_register_block_metadata_collection' ) ) {
		wp_register_block_metadata_collection( __DIR__ . '/build/blocks', __DIR__ . '/build/blocks-manifest.php' );
		return;
	}

	$manifest_data = require __DIR__ . '/build/blocks-manifest.php';
	foreach ( array_keys( $manifest_data ) as $block_type ) {
		register_block_type( __DIR__ . "/build/blocks/{$block_type}" );
	}
}
add_action( 'init', 'ntvb_register_blocks' );

/**
 * Register Native Blocks Category
 *
 */
function ntvb_native_blocks_category( $categories, $post ) {
	return array_merge(
		array(
			array(
				'slug'  => 'native-blocks',
				'title' => __( 'Native Blocks', 'native-blocks' ),
				'icon'  => 'wordpress',
			),
		),
		$categories
	);
}
add_filter( 'block_categories_all', 'ntvb_native_blocks_category', 10, 2 );


// Safe redirect after plugin activation to settings page
function ntvb_activate_redirect( $plugin ) {
	if ( $plugin === plugin_basename( __FILE__ ) ) {
		$redirect_url = esc_url( admin_url( 'options-general.php?page=native-blocks-settings' ) );
		wp_safe_redirect( $redirect_url );
		exit;
	}	
}
add_action( 'activated_plugin', 'ntvb_activate_redirect' );
