<?php
/**
 * Alpha Blocks API class
 * Serves block info (name, image, etc) with pagination for block-modal
 */
class ALPHA_Blocks_API {
	private $blocks = null;

	private function get_all_blocks() {
		if ( $this->blocks === null ) {
			$this->blocks = array();
			$plugin_dir   = trailingslashit( plugin_dir_path( __FILE__ ) . '../' );
			$demos_dir    = $plugin_dir . 'assets/demos/';
			if ( is_dir( $demos_dir ) ) {
				$block_dirs = glob( $demos_dir . '*', GLOB_ONLYDIR );
				foreach ( $block_dirs as $block_dir ) {
					$block_name = basename( $block_dir );
					$file_path  = $block_dir . "/block_data_{$block_name}.php";
					if ( file_exists( $file_path ) ) {
						$data = include $file_path;
						if ( is_array( $data ) ) {
							$this->blocks = array_merge( $this->blocks, $data );
						}
					}
				}
			}
		}
		return $this->blocks;
	}

	public function __construct() {
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
						add_filter( 'block_type_metadata', array( $this, 'add_block_example' ), 10, 1 );    }



	public function add_block_example( $metadata ) {
		if ( isset( $metadata['name'] ) ) {
			$all_blocks = $this->get_all_blocks();

			$matching_examples = array_filter(
				$all_blocks,
				function ( $block ) use ( $metadata ) {
					return isset( $block['name'] ) && $block['name'] === $metadata['name'];
				}
			);

			if ( ! empty( $matching_examples ) ) {
				$example_data = null;

				// First, look for a default example
				foreach ( $matching_examples as $block ) {
					if ( isset( $block['is_default'] ) && $block['is_default'] === true ) {
						$example_data = $block['example'];
						break;
					}
				}

				// If no default is found, use the first available example
				if ( $example_data === null ) {
					$first_example = reset( $matching_examples ); // Get the first element
					if ( isset( $first_example['example'] ) ) {
						$example_data = $first_example['example'];
					}
				}

				if ( $example_data ) {
					if ( is_string( $example_data ) ) {
						$metadata['example'] = json_decode( $example_data, true );
					} elseif ( is_array( $example_data ) || is_object( $example_data ) ) {
						$metadata['example'] = (array) $example_data;
					}
				}
			}
		}
		return $metadata;
	}
	public function register_routes() {
		register_rest_route(
			'alpha-blocks/v1',
			'/blocks',
			array(
				'methods'             => 'GET',
				'callback'            => array( $this, 'get_blocks' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
				'args'                => array(
					'page'     => array(
						'default'           => 1,
						'sanitize_callback' => 'absint',
					),
					'per_page' => array(
						'default'           => 8,
						'sanitize_callback' => 'absint',
					),
					'type'     => array(
						'default'           => '',
						'sanitize_callback' => 'sanitize_text_field',
					),
					'name'     => array(
						'default'           => '',
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
			)
		);

		register_rest_route(
			'alpha-blocks/v1',
			'/upload_block_data',
			array(
				'methods'             => 'POST',
				'callback'            => array( $this, 'upload_block_data' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);

		register_rest_route(
			'alpha-blocks/v1',
			'/delete_block_data',
			array(
				'methods'             => 'POST', // Using POST as discussed in JS part
				'callback'            => array( $this, 'delete_block_data' ),
				'permission_callback' => function () {
					return current_user_can( 'manage_options' );
				},
			)
		);
	}

	public function get_blocks( $request ) {
		$page     = $request->get_param( 'page' );
		$per_page = $request->get_param( 'per_page' );
		$type     = $request->get_param( 'type' );
		$name     = $request->get_param( 'name' );

		$blocks = $this->get_all_blocks();

		if ( ! empty( $type ) ) {
			$blocks = array_filter(
				$blocks,
				function ( $block ) use ( $type ) {
					return isset( $block['type'] ) && $block['type'] === $type;
				}
			);
		}

		if ( ! empty( $name ) ) {
			$blocks = array_filter(
				$blocks,
				function ( $block ) use ( $name ) {
					return isset( $block['name'] ) && $block['name'] === $name;
				}
			);
		}

		$total       = count( $blocks );
		$total_pages = ceil( $total / $per_page );
		$offset      = ( $page - 1 ) * $per_page;
		$blocks      = array_slice( $blocks, $offset, $per_page );
		return array(
			'blocks'      => $blocks,
			'page'        => $page,
			'per_page'    => $per_page,
			'total'       => $total,
			'total_pages' => $total_pages,
		);
	}

	public function upload_block_data( $request ) {

		$name       = $request->get_param( 'name' );
		$id         = $request->get_param( 'id' );
		$image      = $request->get_param( 'image' );
		$type       = $request->get_param( 'type' );
		$content    = $request->get_param( 'content' );
		$key_id     = $request->get_param( 'key_id' );
		$example    = $request->get_param( 'example' );
		$variations = $request->get_param( 'variations' );
		$is_default = $request->get_param( 'is_default_example' );

		$new_data               = compact( 'name', 'id', 'image', 'type', 'content', 'key_id', 'example', 'variations' );
		$new_data['is_default'] = $is_default;

		$name_parts = explode( '/', $name );
		$safe_name  = isset( $new_data['type'] ) ? $new_data['type'] : end( $name_parts );

		$dir_path = ALPHADIR . "assets/demos/{$safe_name}";
		if ( ! is_dir( $dir_path ) ) {
			mkdir( $dir_path, 0755, true );
		}

		$file_path     = $dir_path . "/block_data_{$safe_name}.php";
		$existing_data = array();
		if ( file_exists( $file_path ) ) {
			$existing_data = include $file_path;
			if ( ! is_array( $existing_data ) ) {
				$existing_data = array();
			}
		}

		$is_new_entry = false;
		if ( empty( $new_data['key_id'] ) ) {
			$is_new_entry       = true;
			$name_for_key       = str_replace( '/', '-', $new_data['name'] );
			$new_data['key_id'] = $name_for_key . '-' . count( $existing_data );
		}

		if ( strpos( $new_data['image'], 'data:image/png;base64,' ) === 0 ) {
			$image_data = base64_decode( str_replace( 'data:image/png;base64,', '', $new_data['image'] ) );
			$image_name = $new_data['key_id'] . '.png';
			$image_path = $dir_path . '/' . $image_name;
			file_put_contents( $image_path, $image_data );
			$new_data['image'] =  "assets/demos/{$safe_name}/" . $image_name; //ALPHAURL .
		}

		$found_and_replaced = false;
		if ( ! $is_new_entry ) {
			foreach ( $existing_data as $index => $data ) {
				if ( isset( $data['key_id'] ) && $data['key_id'] === $new_data['key_id'] ) {
					$existing_data[ $index ] = $new_data;
					$found_and_replaced      = true;
					break;
				}
			}
		}

		if ( ! $found_and_replaced ) {
			$existing_data[] = $new_data;
		}

		if ( ! empty( $new_data['is_default'] ) ) {
			foreach ( $existing_data as &$data ) {
				if ( isset( $data['name'] ) && $data['name'] === $new_data['name'] && $data['key_id'] !== $new_data['key_id'] ) {
					$data['is_default'] = false;
				}
			}
			unset( $data );
		}

		$file_content      = "<?php\n\nreturn " . var_export( $existing_data, true ) . ";\n";
		$is_file_generated = file_put_contents( $file_path, $file_content );

		return new WP_REST_Response( array( 'Block data saved.', $is_file_generated ), 200 );
	}

	public function delete_block_data( $request ) {
		$key_id = $request->get_param( 'key_id' );
		$name   = $request->get_param( 'name' );
		$type   = $request->get_param( 'type' );

		if ( empty( $key_id ) || empty( $name ) || empty( $type ) ) {
			return new WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Missing key_id, name or type.',
				),
				400
			);
		}

		$safe_name  = $type;
		$dir_path   = ALPHADIR . "assets/demos/{$safe_name}";
		$file_path  = $dir_path . "/block_data_{$safe_name}.php";

		if ( ! file_exists( $file_path ) ) {
			return new WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Block data file not found.',
				),
				404
			);
		}

		$existing_data = include $file_path;
		if ( ! is_array( $existing_data ) ) {
			$existing_data = array();
		}

		$updated_data = array_filter(
			$existing_data,
			function ( $data ) use ( $key_id ) {
				return ! isset( $data['key_id'] ) || $data['key_id'] !== $key_id;
			}
		);

		if ( count( $existing_data ) === count( $updated_data ) ) {
			return new WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Block with key_id not found.',
				),
				404
			);
		}

		$file_content      = "<?php\n\nreturn " . var_export( $updated_data, true ) . ";\n";
		$is_file_generated = file_put_contents( $file_path, $file_content );

		if ( $is_file_generated === false ) {
			return new WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Failed to save updated block data.',
				),
				500
			);
		}

		return new WP_REST_Response(
			array(
				'success' => true,
				'message' => 'Block data deleted successfully.',
			),
			200
		);
	}
}

// To use, instantiate in your plugin bootstrap:
// new Alpha_Blocks_API();
