<?php

namespace BwWinner;

class Winners_Metaboxes {
	public function __construct () {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
		add_action( 'save_post', array( $this, 'save_post' ), 10, 2 );
	}

	public function add_meta_boxes () {
		add_meta_box(
			'winers_company_meta_box',
			esc_html__( 'Company', 'bw-winner' ),
			array( $this, 'company_meta_box' ),
			'company',
			'normal',
			'high'
		);
		add_meta_box(
			'winers_brand_meta_box',
			esc_html__( 'Brand', 'bw-winner' ),
			array( $this, 'brand_meta_box' ),
			'brand',
			'normal',
			'high'
		);
		add_meta_box(
			'winers_product_meta_box',
			esc_html__( 'Product', 'bw-winner' ),
			array( $this, 'product_meta_box' ),
			'bw-product',
			'normal',
			'high'
		);
	}

	public function save_post ( $post_id, $post ) {
		$post_type = get_post_type_object( $post->post_type );

		if ( !current_user_can( $post_type->cap->edit_post, $post_id ) ) {
			return $post_id;
		}

		global $bw_winners;
		global $wpdb;

		if ( isset( $_POST['winners_company_nonce'] ) && wp_verify_nonce( $_POST['winners_company_nonce'], basename( __FILE__ ) ) ) {

			$bw_winners->entities->update_company( array(
				'id' => $post_id,
				'name' => $post->post_title,
				'url' => $_POST['winners_company_url'],
				'email' => $_POST['winners_company_email'],
			) );

			return;
		}

		if ( isset( $_POST['winners_brand_nonce'] ) && wp_verify_nonce( $_POST['winners_brand_nonce'], basename( __FILE__ ) ) ) {
			$brand = array(
				'id' => $post_id,
				'name' => $post->post_title,
				'url' => $_POST['winners_brand_url'],
				'company_id' => NULL
			);

			if ( ! empty( $_POST['winners_brand_company'] ) ) {
				$brand['company_id'] = $_POST['winners_brand_company'];
			}

			$bw_winners->entities->update_brand( $brand );

			return;
		}

		if ( isset( $_POST['winners_product_nonce'] ) && wp_verify_nonce( $_POST['winners_product_nonce'], basename( __FILE__ ) ) ) {
			$product = array(
				'id' => $post_id,
				'name' => $post->post_title,
				'url' => $_POST['winners_product_url'],
				'type' => $_POST['winners_product_type'],
				'price' => $_POST['winners_product_price'],
				'country' => $_POST['winners_product_country'],
				'brand_id' => NULL
			);

			if ( ! empty( $_POST['winners_product_brand'] ) ) {
				$product['brand_id'] = $_POST['winners_product_brand'];
			}

			$bw_winners->entities->update_product( $product );

			if ( empty( $_POST['winners_product_entries'] ) ) {
				// drop all entries
				$bw_winners->entities->delete_product_entries( $post_id );
			} else {
				// drop removed entries
				$ids = array();
				foreach ( $_POST['winners_product_entries'] as $entry ) {
					if ( ! empty( $entry['id'] ) ) $ids[] = intval($entry['id']);
				}

				$bw_winners->entities->delete_product_entries( $post_id, $ids );
				
				// update / insert entries
				foreach ( $_POST['winners_product_entries'] as $entry ) {
					if ( ! empty( $entry['id'] ) ) {
						$bw_winners->entities->update_entry( array(
							'id' => $entry['id'],
							'product_id' => $post_id,
							'year' => $entry['year'],
							'score' => $entry['score']
						) );
					} else {
						$bw_winners->entities->insert_entry( array(
							'product_id' => $post_id,
							'year' => $entry['year'],
							'score' => $entry['score']
						) );
					}
				}
			}
			return;
		}
	}
	
	public function company_meta_box ( $post ) {
		wp_nonce_field( basename( __FILE__ ), 'winners_company_nonce' );

		global $bw_winners;

		$company = $bw_winners->entities->get_company( $post->ID );

		$url = $company ? $company['url'] : '';
		$email = $company ? $company['email'] : '';

		?>
			<p>
				<label for="winners_company_url"><?php _e( "Company URL", 'bw-winner' ); ?></label>
				<br />
				<input class="widefat" type="text" name="winners_company_url" id="winners_company_url" value="<?php echo esc_attr( $url ); ?>" size="30" />
			</p>
			<p>
				<label for="winners_company_email"><?php _e( "Email", 'bw-winner' ); ?></label>
				<br />
				<input class="widefat" type="text" name="winners_company_email" id="winners_company_email" value="<?php echo esc_attr( $email ); ?>" size="30" />
			</p>
		<?php
	}
	
	public function brand_meta_box ( $post ) {
		wp_nonce_field( basename( __FILE__ ), 'winners_brand_nonce' );
		
		global $wpdb;
		global $bw_winners;

		$brand = $bw_winners->entities->get_brand( $post->ID );
		

		$url = $brand ? $brand['url'] : '';
		$company_id = $brand ? $brand['company_id'] : '';

		$companies = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}bw_winners_companies" ) );

		?>
			<p>
				<label for="winners_brand_company"><?php _e( "Company", 'bw-winner' ); ?></label>
				<br />
				<select class="widefat" name="winners_brand_company" id="winners_brand_company">
					<option value="">
						-- Select a Company --
					</option>
					<?php
					if ($companies) {
						foreach ( $companies as $company ) {
							?>
								<option value="<?php echo $company->id; ?>" <?php echo $company->id == $company_id ? 'selected' : ''; ?>>
									<?php echo $company->name; ?>
								</option>
							<?php
						}
					}
					?>
				</select>
			</p>
			<p>
				<label for="winners_brand_url"><?php _e( "Brand URL", 'bw-winner' ); ?></label>
				<br />
				<input class="widefat" type="text" name="winners_brand_url" id="winners_brand_url" value="<?php echo esc_attr( $url ); ?>" size="30" />
			</p>
		<?php
	}
	
	public function product_meta_box ( $post ) {
		wp_nonce_field( basename( __FILE__ ), 'winners_product_nonce' );
		
		global $wpdb;
		global $bw_winners;

		$product = $bw_winners->entities->get_product( $post->ID );

		$url = $product ? $product['url'] : '';
		$type = $product ? $product['type'] : '';
		$price = $product ? $product['price'] : '';
		$country = $product ? $product['country'] : '';

		$brand_id = $product ? $product['brand_id'] : '';

		$brands = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}bw_winners_brands" ) );

		$entries = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}bw_winners_entries WHERE product_id = %d", $post->ID ) );

		?>
			<p>
				<label for="winners_product_brand"><?php _e( "Brand", 'bw-winner' ); ?></label>
				<br />
				<select class="widefat" name="winners_product_brand" id="winners_product_brand">
					<option value="">
						-- Select a Brand --
					</option>
					<?php
					if ($brands) {
						foreach ( $brands as $brand ) {
							?>
								<option value="<?php echo $brand->id; ?>" <?php echo $brand->id == $brand_id ? 'selected' : ''; ?>>
									<?php echo $brand->name; ?>
								</option>
							<?php
						}
					}
					?>
				</select>
			</p>
			<p>
				<label for="winners_product_type"><?php _e( "Product Type", 'bw-winner' ); ?></label>
				<br />
				<input class="widefat" type="text" name="winners_product_type" id="winners_product_type" value="<?php echo esc_attr( $type ); ?>" size="30" />
			</p>
			<p>
				<label for="winners_product_price"><?php _e( "Product Price Category", 'bw-winner' ); ?></label>
				<br />
				<input class="widefat" type="text" name="winners_product_price" id="winners_product_price" value="<?php echo esc_attr( $price ); ?>" size="30" />
			</p>
			<p>
				<label for="winners_product_country"><?php _e( "Product Country", 'bw-winner' ); ?></label>
				<br />
				<input class="widefat" type="text" name="winners_product_country" id="winners_product_country" value="<?php echo esc_attr( $country ); ?>" size="30" />
			</p>
			
			<h4>Entries</h4>
			<div class="bw-entries-repeater">
				<?php
				if ( $product['entries'] ) {
					foreach (  $product['entries'] as $index => $entry ) {
						?>
							<div class="bw-field-group">
								<input type="hidden" name="winners_product_entries[<?php echo $index; ?>][id]" value="<?php echo $entry['id'] ?>" size="30" />
								<p>
									<label><?php _e( "Entry Year", 'bw-winner' ); ?>
										<br />
										<input class="widefat" type="number" name="winners_product_entries[<?php echo $index; ?>][year]" value="<?php echo esc_attr( $entry['year'] ); ?>" size="30" />
									</label>
								</p>
								<p>
									<label><?php _e( "Entry Score", 'bw-winner' ); ?>
										<br />
										<input class="widefat" type="number" name="winners_product_entries[<?php echo $index; ?>][score]" value="<?php echo esc_attr( $entry['score'] ); ?>" size="30" />
									</label>
								</p>
								<button type="button" class="bw-field-group-remove components-button is-secondary is-destructive">Remove Entry</button>
							</div>
						<?php
					}
				}
				?>
			</div>
			<button type="button" class="bw-field-group-add components-button is-secondary">Add Entry</button>
			<style>
				.bw-field-group {
					margin:8px;
					border: 1px solid #ddd;
					padding: 12px;
				}
				.bw-field-group p {
					margin-top: 0;
				}
			</style>
			<script>
				(function ($) {
					let index = jQuery('.bw-entries-repeater').children().length;
					
					function removeEntry (event) {
						$(event.target).closest('.bw-field-group').remove();
					}
					function addEntry (event) {
						$('.bw-entries-repeater').append(
							`<div class="bw-field-group">
								<input type="hidden" name="winners_product_entries[${index}][id]" value="" />
								<p>
									<label>Entry Year
										<br>
										<input class="widefat" type="number" name="winners_product_entries[${index}][year]" value="" size="30">
									</label>
								</p>
								<p>
									<label>Entry Score
										<br>
										<input class="widefat" type="number" name="winners_product_entries[${index}][score]" value="" size="30">
									</label>
								</p>
								<button type="button" class="bw-field-group-remove components-button is-secondary is-destructive">Remove Entry</button>
							</div>`
						);
						$('.bw-entries-repeater').children().last().find('.bw-field-group-remove').on('click', removeEntry);
						index++;
					}
					$('.bw-field-group-remove').on('click', removeEntry);
					$('.bw-field-group-add').on('click', addEntry);
				})(jQuery);
			</script>
		<?php
	}
}
