<?php

namespace BwWinner;

class Product_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_product_title', array( $this, 'bw_product_title' ) );

		add_shortcode( 'bw_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;

				$company_id = $brand ? $brand->company_id : false;

				if ( $company_id && get_post_type( $company_id ) === 'company' ) {

					$company = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}bw_winners_companies WHERE id = %d", $company_id ) );

					if ($company) $parts[] = $company->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;
	}
}