<?php
/**
 * Product context resolution for Gutenberg blocks.
 *
 * Resolves a product from block attributes or falls back to page context,
 * mirroring the logic in GGM_Commerce_Base_Widget::get_product_data().
 *
 * @package GGM Commerce
 */

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

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

/**
 * Resolve product data for a block.
 *
 * Priority:
 *  1. Explicit productId attribute
 *  2. Custom product_source/product_id (Elementor compat)
 *  3. Global ggmc_current_product_id (Quick View AJAX)
 *  4. Page context via GGM_Commerce_Helpers::get_current_product_id()
 *
 * @param array $attributes Block attributes.
 * @return object|null Product row from wp_ggmc_products or null.
 */
function ggmc_block_get_product_data( array $attributes ) {
	global $wpdb;
	$table = $wpdb->prefix . 'ggmc_products';

	// 1. Explicit block productId attribute.
	if ( ! empty( $attributes['productId'] ) ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$product = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE id = %d", absint( $attributes['productId'] ) ) );
		if ( $product ) {
			return $product;
		}
	}

	// 2. Elementor-style custom product source.
	if ( isset( $attributes['product_source'] ) && $attributes['product_source'] === 'custom' && ! empty( $attributes['product_id'] ) ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$product = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE id = %d", absint( $attributes['product_id'] ) ) );
		if ( $product ) {
			return $product;
		}
	}

	// 3. Global product context (set by Quick View, etc.).
	if ( ! empty( $GLOBALS['ggmc_current_product_id'] ) ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$product = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE id = %d", absint( $GLOBALS['ggmc_current_product_id'] ) ) );
		if ( $product ) {
			return $product;
		}
	}

	// 4. Page context — same logic the Elementor widgets use.
	if ( class_exists( 'GGM_Commerce_Helpers' ) ) {
		$product_id = GGM_Commerce_Helpers::get_current_product_id();
		if ( $product_id ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE id = %d", absint( $product_id ) ) );
		}
	}

	return null;
}
