<?php

namespace Waypoint\Agent\Rest\Handler;

class Site_Context {

	public function handle( \WP_REST_Request $request ): \WP_REST_Response {
		$theme      = wp_get_theme();
		$theme_slug = $theme->get_stylesheet();

		$acf_blocks = [];
		$registry   = \WP_Block_Type_Registry::get_instance();
		foreach ( $registry->get_all_registered() as $name => $block_type ) {
			if ( str_starts_with( $name, 'acf/' ) ) {
				$acf_blocks[] = [
					'name'  => $name,
					'label' => ! empty( $block_type->title ) ? $block_type->title : $name,
				];
			}
		}

		$patterns = [];
		if ( class_exists( 'WP_Block_Patterns_Registry' ) ) {
			foreach ( \WP_Block_Patterns_Registry::get_instance()->get_all_registered() as $pattern ) {
				if ( isset( $pattern['name'] ) ) {
					$patterns[] = $pattern['name'];
				}
			}
		}

		$business_data = [
			'phone_display' => '',
			'phone_tel'     => '',
			'address'       => '',
		];

		if ( class_exists( '\Victoria\Utilities\Local_Info' ) ) {
			$phone_raw = \Victoria\Utilities\Local_Info::get_primary_phone();
			if ( is_array( $phone_raw ) ) {
				$business_data['phone_display'] = isset( $phone_raw['display'] ) ? (string) $phone_raw['display'] : '';
				$business_data['phone_tel']     = isset( $phone_raw['tel'] ) ? (string) $phone_raw['tel'] : preg_replace( '/[^0-9+]/', '', $business_data['phone_display'] );
			} elseif ( is_string( $phone_raw ) ) {
				$business_data['phone_display'] = $phone_raw;
				$business_data['phone_tel']     = preg_replace( '/[^0-9+]/', '', $phone_raw );
			}
			$address = \Victoria\Utilities\Local_Info::get_address();
			if ( is_string( $address ) ) {
				$business_data['address'] = $address;
			}
		}

		return rest_ensure_response( [
			'site_url'                  => home_url(),
			'business_name'             => get_bloginfo( 'name' ),
			'plugin_version'            => WAYPOINT_AGENT_VERSION,
			'theme'                     => $theme_slug,
			'redirection_plugin_active' => class_exists( 'Red_Item' ),
			'block_library'             => [
				'version' => '1.0.0',
				'blocks'  => $acf_blocks,
			],
			'patterns'                  => $patterns,
			'business_data'             => $business_data,
			'local_form_id'             => $this->detect_fluent_form_id(),
		] );
	}

	private function detect_fluent_form_id(): ?int {
		global $wpdb;
		$table = $wpdb->prefix . 'fluentform_forms';
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		if ( $wpdb->get_var( "SHOW TABLES LIKE '$table'" ) !== $table ) {
			return null;
		}
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$id = $wpdb->get_var( "SELECT id FROM {$table} WHERE status = 'published' ORDER BY id ASC LIMIT 1" );
		return $id ? (int) $id : null;
	}
}
