<?php
/**
 * Registers an ACF field group on the `bw-product` edit screen so admins can
 * edit the product detail fields directly in the backend — the same fields the
 * Gravity Forms "Product Update Form" writes via update_field().
 *
 * Field NAMES here MUST match the acf_field names used in the GF -> meta map
 * (class-product-update.php) and the keys read by the single-bw-product.php
 * template, so the form workflow and manual backend editing stay in lockstep.
 */

namespace BwWinner;

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

class Product_Fields {

	public function __construct () {
		add_action( 'acf/init', array( $this, 'register_fields' ) );
	}

	public function register_fields () {
		if ( ! function_exists( 'acf_add_local_field_group' ) ) {
			return; // ACF not active.
		}

		acf_add_local_field_group( array(
			'key'         => 'group_bw_product_details',
			'title'       => 'Product Details',
			'fields'      => array(
				$this->image( 'brand_logo', 'Brand Logo' ),
				$this->image( 'product_image', 'Product Image' ),
				$this->text( 'alcohol_by_volume', 'Alcohol by Volume (%)' ),
				$this->text( 'bottle_size', 'Bottle Size' ),
				$this->text( 'distillery_location', 'Distillery Location', 'City, Country' ),
				$this->text( 'retail_price', 'Retail Price' ),
				$this->textarea( 'tasting_notes', 'Tasting Notes' ),
				$this->textarea( 'product_description', 'Product Description' ),
				$this->url( 'brand_link', 'Brand Link' ),
				$this->url( 'product_link', 'Product Link' ),
				$this->url( 'purchase_link', 'Purchase Link' ),
				$this->url( 'video_link', 'Video Link' ),
			),
			'location'    => array(
				array(
					array(
						'param'    => 'post_type',
						'operator' => '==',
						'value'    => 'bw-product',
					),
				),
			),
			'menu_order'      => 0,
			'position'        => 'normal',
			'style'           => 'default',
			'label_placement' => 'top',
			'active'          => true,
			'description'     => 'Product detail fields. Also populated automatically by the Product Update Form (Gravity Forms).',
		) );
	}

	private function base ( $name, $label, $type ) {
		return array(
			'key'   => 'field_bwp_' . $name,
			'label' => $label,
			'name'  => $name,
			'type'  => $type,
		);
	}

	private function text ( $name, $label, $instructions = '' ) {
		$f                 = $this->base( $name, $label, 'text' );
		$f['instructions'] = $instructions;
		return $f;
	}

	private function textarea ( $name, $label ) {
		$f              = $this->base( $name, $label, 'textarea' );
		$f['rows']      = 4;
		$f['new_lines'] = '';
		return $f;
	}

	private function url ( $name, $label ) {
		return $this->base( $name, $label, 'url' );
	}

	private function image ( $name, $label ) {
		$f                  = $this->base( $name, $label, 'image' );
		$f['return_format'] = 'id';   // GF stores attachment IDs; template reads IDs.
		$f['preview_size']  = 'medium';
		$f['library']       = 'all';
		return $f;
	}
}
