<?php

namespace BwWinnersGlobalSite\Product_Update;

if ( ! class_exists( __NAMESPACE__ . '\Update_Form' ) ) {

	class Update_Form {

		public $form_page_name = 'listing-upgrade';

		public function __construct () {

			// Hooking up methods as callbacks
			add_action( 'init', array( $this, 'custom_rewrite_rule' ) );

			add_filter( 'query_vars', array( $this, 'add_custom_query_vars' ) );

			add_shortcode( 'bw-v2-product-title', array( $this, 'bw_product_title' ) );

			add_shortcode( 'bw-v2-brand-title', array( $this, 'bw_brand_title' ) );

			add_filter( 'gform_field_value_product_id', array( $this, 'set_product_id_field' ) );
		}

		public function custom_rewrite_rule () {
			add_rewrite_rule(
				'^' . $this->form_page_name . '/(\d+)/?',
				'index.php?pagename=' . $this->form_page_name . '&product-id=$matches[1]', 
				'top'
			);
		}

		public function add_custom_query_vars ( $query_vars ) {
			$query_vars[] = 'product-id';
			return $query_vars;
			
		}

		public function bw_product_title ( $atts = [], $content = null ) {

			$attributes = shortcode_atts( array(
				'product_id' => get_query_var( 'product-id', false ),
			), $atts );

			$product_id = intval( $attributes['product_id'] );

			if ( $attributes['product_id'] !== false && get_post_type( $product_id ) === 'bw-product' ) {

				global $wpdb;

				$product = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}bw_winners_products WHERE id = %d", $product_id ) );

				if ( $product ) return $product->name;
			}
			
			return $content;
		}

		public function bw_brand_title ( $atts = [], $content = null ) {
			
			$attributes = shortcode_atts( array(
				'product_id' => get_query_var( 'product-id', false ),
			), $atts );

			$product_id = intval( $attributes['product_id'] );

			$parts = array();

			if ( $attributes['product_id'] !== false && get_post_type( $product_id ) === 'bw-product' ) {

				global $wpdb;

				$product = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}bw_winners_products WHERE id = %d", $product_id ) );

				$brand_id = $product ? $product->brand_id : false;

				if ( $brand_id && get_post_type( $brand_id ) === 'brand' ) {

					$brand = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}bw_winners_brands WHERE id = %d", $brand_id ) );

					if ( $brand ) $parts[] = $brand->name;
				}
			}
			
			return implode( ' - ', $parts );
		}

		public function set_product_id_field ( $value ) {
			$product_id = get_query_var( 'product-id', false );
			return $product_id ? $product_id : $value;
		}
	}
}
