<?php
/**
 * REST API endpoints for Gutenberg block editor.
 *
 * Provides product search, single product lookup, and license status
 * so block Inspector Controls can work without full page reloads.
 *
 * @package GGM Commerce
 */

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

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching

class GGMC_Block_REST_API {

	/**
	 * Boot the REST API routes.
	 */
	public static function init() {
		add_action( 'rest_api_init', array( __CLASS__, 'register_routes' ) );
	}

	/**
	 * Register REST routes under /wp-json/ggmc/v1/.
	 */
	public static function register_routes() {
		register_rest_route(
			'ggmc/v1',
			'/products/search',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'search_products' ),
				'permission_callback' => array( __CLASS__, 'editor_permission_check' ),
				'args'                => array(
					'q' => array(
						'required'          => false,
						'type'              => 'string',
						'sanitize_callback' => 'sanitize_text_field',
					),
				),
			)
		);

		register_rest_route(
			'ggmc/v1',
			'/products/(?P<id>\\d+)',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_product' ),
				'permission_callback' => array( __CLASS__, 'editor_permission_check' ),
				'args'                => array(
					'id' => array(
						'required'          => true,
						'type'              => 'integer',
						'sanitize_callback' => 'absint',
					),
				),
			)
		);

		register_rest_route(
			'ggmc/v1',
			'/categories',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_categories' ),
				'permission_callback' => array( __CLASS__, 'editor_permission_check' ),
			)
		);

		register_rest_route(
			'ggmc/v1',
			'/license/status',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_license_status' ),
				'permission_callback' => array( __CLASS__, 'editor_permission_check' ),
			)
		);
	}

	/**
	 * Only users who can edit posts may use these endpoints.
	 */
	public static function editor_permission_check() {
		return current_user_can( 'edit_posts' );
	}

	/**
	 * Search products by name/SKU.
	 *
	 * @param \WP_REST_Request $request
	 * @return \WP_REST_Response
	 */
	public static function search_products( $request ) {
		global $wpdb;
		$table = $wpdb->prefix . 'ggmc_products';
		$q     = $request->get_param( 'q' );

		if ( empty( $q ) ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$products = $wpdb->get_results( "SELECT id, name, sku, price, sale_price FROM $table ORDER BY name ASC LIMIT 20" );
		} else {
			$like = '%' . $wpdb->esc_like( $q ) . '%';
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$products = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT id, name, sku, price, sale_price FROM $table WHERE name LIKE %s OR sku LIKE %s ORDER BY name ASC LIMIT 20",
					$like,
					$like
				)
			);
		}

		$results = array();
		foreach ( $products as $p ) {
			$results[] = array(
				'id'    => (int) $p->id,
				'name'  => $p->name,
				'sku'   => $p->sku ?? '',
				'price' => $p->price,
			);
		}

		return new \WP_REST_Response( $results, 200 );
	}

	/**
	 * Get a single product by ID.
	 *
	 * @param \WP_REST_Request $request
	 * @return \WP_REST_Response
	 */
	public static function get_product( $request ) {
		global $wpdb;
		$table = $wpdb->prefix . 'ggmc_products';
		$id    = $request->get_param( 'id' );

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$product = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE id = %d", $id ) );

		if ( ! $product ) {
			return new \WP_REST_Response( array( 'message' => 'Product not found' ), 404 );
		}

		return new \WP_REST_Response(
			array(
				'id'    => (int) $product->id,
				'name'  => $product->name,
				'sku'   => $product->sku ?? '',
				'price' => $product->price,
				'slug'  => $product->slug ?? '',
			),
			200
		);
	}

	/**
	 * Get product categories.
	 *
	 * @return \WP_REST_Response
	 */
	public static function get_categories() {
		global $wpdb;
		$table = $wpdb->prefix . 'ggmc_categories';

		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$categories = $wpdb->get_results( "SELECT id, name, slug, parent_id FROM $table ORDER BY name ASC" );

		$results = array();
		foreach ( $categories as $cat ) {
			$results[] = array(
				'id'        => (int) $cat->id,
				'name'      => $cat->name,
				'slug'      => $cat->slug,
				'parent_id' => (int) $cat->parent_id,
			);
		}

		return new \WP_REST_Response( $results, 200 );
	}

	/**
	 * Get premium license activation status.
	 *
	 * @return \WP_REST_Response
	 */
	public static function get_license_status() {
		$status = array( 'active' => false, 'widgets' => array() );

		if ( class_exists( 'GGM_Commerce_License' ) ) {
			$license = GGM_Commerce_License::instance();
			$status['active'] = $license->is_license_valid();
		}

		return new \WP_REST_Response( $status, 200 );
	}
}
