<?php
namespace BwWinnersGlobalSite;

if ( ! class_exists( __NAMESPACE__ . '\Product_Posts' ) ) {

	class Product_Posts {

		private $post_type = 'bw-product';

		public function __construct () {
			add_action( 'init', [ $this, 'register' ] );
			add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
			add_action( 'save_post', [ $this, 'save_post' ], 10, 2 );
		}

		public function register () {

			// product

			$labels = [
				'name' => 'Products',
				'singular_name' => 'Product',
				'add_new' => 'Add New Product',
				'add_new_item' => 'Add New Product',
				'edit_item' => 'Edit Product',
				'new_item' => 'New Product',
				'all_items' => 'All Products',
				'view_item' => 'View Product',
				'search_items' => 'Search Products',
				'not_found' =>  'No Product Found',
				'not_found_in_trash' => 'No product found in Trash', 
				'parent_item_colon' => '',
				'menu_name' => 'Products',
			];

			$args = [
				'public' => true,
				'labels' => $labels,
				'has_archive' => true,
				'show_ui' => true,
				'capability_type' => 'post',
				'hierarchical' => false,
				'query_var' => true,
				'show_in_rest' => true,
				'menu_icon' => 'dashicons-products',
				'rewrite' => [
					'slug' => 'product',
				],
				'supports' => [
					'title',
					'editor',
					'excerpt',
					'revisions',
					'thumbnail',
					'author',
					'page-attributes'
				]
			];

			register_post_type( $this->post_type, $args );
			
			register_taxonomy(
				'product-category', 
				$this->post_type, 
				array(
					'hierarchical' => false, 
					'label' => 'Product Category', 
					'query_var' => true,
					'show_in_rest' => true
				)
			);
		}

		public function add_meta_boxes () {

			add_meta_box(
				'bw_winners_product_meta_box',
				esc_html__( 'Product', 'bw-winners-global-site' ),
				[ $this, 'meta_box' ],
				$this->post_type,
				'normal',
				'high'
			);
		}

		public function meta_box ( $post ) {
			wp_nonce_field( basename( __FILE__ ), 'winners_product_nonce' );

			global $bw_winners_global_site;

			$product = $bw_winners_global_site->entities->get_product( $post->ID );

			if ( empty( $product ) ) {
				return;
			}


			$type = $product ? $product['type'] : '';
			$price = $product ? $product['price'] : '';
			$country = $product ? $product['country'] : '';

			$brand_id = $product ? $product['brand_id'] : '';

			$competitions = $bw_winners_global_site->entities->get_competitions();

			$competition_product_categories = [];

			$brands = $bw_winners_global_site->entities->get_brands();

			$entries = $bw_winners_global_site->entities->get_product_entries( $post->ID );

			?>
				<p>
					<label for="winners_product_brand"><?php _e( "Brand", 'bw-winners-global-site' ); ?></label>
					<br />
					<select class="widefat" name="winners_product_brand" id="winners_product_brand">
						<option value="">
							<?php _e( "-- Select a Brand --", 'bw-winners-global-site' ); ?>
						</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-winners-global-site' ); ?></label>
					<br />
					<input class="widefat" type="text" name="winners_product_type" id="winners_product_type" value="<?php echo esc_attr( $type ); ?>" />
				</p>
				<p>
					<label for="winners_product_price"><?php _e( "Product Price Category", 'bw-winners-global-site' ); ?></label>
					<br />
					<input class="widefat" type="text" name="winners_product_price" id="winners_product_price" value="<?php echo esc_attr( $price ); ?>" />
				</p>
				<p>
					<label for="winners_product_country"><?php _e( "Product Country", 'bw-winners-global-site' ); ?></label>
					<br />
					<input class="widefat" type="text" name="winners_product_country" id="winners_product_country" value="<?php echo esc_attr( $country ); ?>" />
				</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'] ?>" />
									
									<?php if ( $competitions ) : ?>
										<p>
											<label>
												<?php _e( "Competition", 'bw-winners-global-site' ); ?>
												<select class="widefat" name="winners_product_entries[<?php echo $index; ?>][competition_id]">
													<option value="">
														<?php _e( "-- Select a Competition --", 'bw-winners-global-site' ); ?>
													</option>
													<?php foreach ( $competitions as $competition ) : ?>
														<option value="<?php echo $competition['id']; ?>" <?php echo ! empty( $entry['competition_id'] ) && $competition['id'] == $entry['competition_id'] ? 'selected' : ''; ?>>
															<?php echo $competition['name']; ?>
														</option>
													<?php endforeach; ?>
												</select>
											</label>
										</p>
									<?php endif ?>

									<p>
										<label><?php _e( "Competition Product Category", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_entries[<?php echo $index; ?>][competition_product_category]" value="<?php echo esc_attr( $entry['competition_product_category'] ); ?>" />
										</label>
									</p>
									<p>
										<label><?php _e( "Entry Year", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="number" name="winners_product_entries[<?php echo $index; ?>][year]" value="<?php echo esc_attr( $entry['year'] ); ?>" />
										</label>
									</p>
									<p>
										<label><?php _e( "Entry Score", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="number" name="winners_product_entries[<?php echo $index; ?>][score]" value="<?php echo esc_attr( $entry['score'] ); ?>" />
										</label>
									</p>
									<button type="button" class="bw-field-group-remove-entry components-button is-secondary is-destructive"><?php _e( "Remove Entry", 'bw-winners-global-site' ); ?></button>
								</div>
							<?php
						}
					}
					?>
				</div>
				<button type="button" class="bw-field-group-add-entry components-button is-secondary"><?php _e( "Add Entry", 'bw-winners-global-site' ); ?></button>
				
				<h4>Individual Awards</h4>
				<div class="bw-awards-repeater">
					<?php
					if ( $product['awards'] ) {
						foreach (  $product['awards'] as $index => $award ) {
							?>
								<div class="bw-field-group">
									<input type="hidden" name="winners_product_awards[<?php echo $index; ?>][id]" value="<?php echo $award['id'] ?>" />
									
									<?php if ( $competitions ) : ?>
										<p>
											<label>
												<?php _e( "Competition", 'bw-winners-global-site' ); ?>
												<select class="widefat" name="winners_product_awards[<?php echo $index; ?>][competition_id]">
													<option value="">
														<?php _e( "-- Select a Competition --", 'bw-winners-global-site' ); ?>
													</option>
													<?php foreach ( $competitions as $competition ) : ?>
														<option value="<?php echo $competition['id']; ?>" <?php echo ! empty( $award['competition_id'] ) && $competition['id'] == $award['competition_id'] ? 'selected' : ''; ?>>
															<?php echo $competition['name']; ?>
														</option>
													<?php endforeach; ?>
												</select>
											</label>
										</p>
									<?php endif ?>

									<p>
										<label><?php _e( "Award Year", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="number" name="winners_product_awards[<?php echo $index; ?>][year]" value="<?php echo esc_attr( $award['year'] ); ?>" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Name", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_awards[<?php echo $index; ?>][name]" value="<?php echo esc_attr( $award['name'] ); ?>" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Country", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_awards[<?php echo $index; ?>][country]" value="<?php echo esc_attr( $award['country'] ); ?>" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Region", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_awards[<?php echo $index; ?>][region]" value="<?php echo esc_attr( $award['region'] ); ?>" />
										</label>
									</p>
									<button type="button" class="bw-field-group-remove-award components-button is-secondary is-destructive"><?php _e( "Remove Award", 'bw-winners-global-site' ); ?></button>
								</div>
							<?php
						}
					}
					?>
				</div>
				<button type="button" class="bw-field-group-add-award components-button is-secondary"><?php _e( "Add Award", 'bw-winners-global-site' ); ?></button>
				<style>
					.bw-field-group {
						margin:8px;
						border: 1px solid #ddd;
						padding: 12px;
					}
					.bw-field-group p {
						margin-top: 0;
					}
				</style>
				<script>
					(function ($) {
						let entryIndex = 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[${entryIndex}][id]" value="" />
									<?php if ($competitions) : ?>
										<p>
											<label>
												<?php _e( "Competition", 'bw-winners-global-site' ); ?>
												<select class="widefat" name="winners_product_entries[${entryIndex}][competition_id]">
													<option value="">
														<?php _e( "-- Select a Competition --", 'bw-winners-global-site' ); ?>
													</option>
													<?php foreach ( $competitions as $competition ) : ?>
														<option value="<?php echo $competition['id']; ?>">
															<?php echo $competition['name']; ?>
														</option>
													<?php endforeach; ?>
												</select>
											</label>
										</p>
									<?php endif ?>
									<p>
										<label><?php _e( "Competition Product Category", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_entries[${entryIndex}][competition_product_category]" value="" />
										</label>
									</p>
									<p>
										<label>Entry Year
											<br>
											<input class="widefat" type="number" name="winners_product_entries[${entryIndex}][year]" value="">
										</label>
									</p>
									<p>
										<label>Entry Score
											<br>
											<input class="widefat" type="number" name="winners_product_entries[${entryIndex}][score]" value="">
										</label>
									</p>
									<button type="button" class="bw-field-group-remove-entry components-button is-secondary is-destructive"><?php _e( "Remove Entry", 'bw-winners-global-site' ); ?></button>
								</div>`
							);
							$('.bw-entries-repeater').children().last().find('.bw-field-group-remove-entry').on('click', removeEntry);
							entryIndex++;
						}
						$('.bw-field-group-remove-entry').on('click', removeEntry);
						$('.bw-field-group-add-entry').on('click', addEntry);


						let awardIndex = jQuery('.bw-awards-repeater').children().length;
						
						function removeAward (event) {
							$(event.target).closest('.bw-field-group').remove();
						}
						function addAward (event) {
							$('.bw-awards-repeater').append(
								`<div class="bw-field-group">
									<input type="hidden" name="winners_product_awards[${awardIndex}][id]" value="" />
									
									<?php if ($competitions) : ?>
										<p>
											<label>
												<?php _e( "Competition", 'bw-winners-global-site' ); ?>
												<select class="widefat" name="winners_product_awards[${awardIndex}][competition_id]">
													<option value="">
														<?php _e( "-- Select a Competition --", 'bw-winners-global-site' ); ?>
													</option>
													<?php foreach ( $competitions as $competition ) : ?>
														<option value="<?php echo $competition['id']; ?>">
															<?php echo $competition['name']; ?>
														</option>
													<?php endforeach; ?>
												</select>
											</label>
										</p>
									<?php endif ?>
									<p>
										<label><?php _e( "Award Year", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="number" name="winners_product_awards[${awardIndex}][year]" value="" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Name", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_awards[${awardIndex}][name]" value="" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Country", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_awards[${awardIndex}][country]" value="" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Region", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_product_awards[${awardIndex}][region]" value="" />
										</label>
									</p>
									<button type="button" class="bw-field-group-remove-award components-button is-secondary is-destructive"><?php _e( "Remove Award", 'bw-winners-global-site' ); ?></button>
								</div>`
							);
							$('.bw-awards-repeater').children().last().find('.bw-field-group-remove-award').on('click', removeAward);
							awardIndex++;
						}
						$('.bw-field-group-remove-award').on('click', removeAward);
						$('.bw-field-group-add-award').on('click', addAward);
					})(jQuery);
				</script>
			<?php
		}

		public function save_post ( $post_id, $post ) {

			if ( get_post_type( $post ) !== $this->post_type ) {
				return;
			}
			
			$post_type_object = get_post_type_object( $post->post_type );

			if ( ! current_user_can( $post_type_object->cap->edit_post, $post_id ) ) {
				return;
			}

			global $bw_winners_global_site;

			// Update non metabox data here

			$product = $bw_winners_global_site->entities->get_product( $post->ID );

			if ( ! $product ) {
				return;
			}

			$product['name'] = $post->post_title;

			if ( isset( $_POST['winners_product_nonce'] ) && wp_verify_nonce( $_POST['winners_product_nonce'], basename( __FILE__ ) ) ) {

				// Update metabox data here

				$product['type'] = $_POST['winners_product_type'];
				$product['price'] = $_POST['winners_product_price'];
				$product['country'] = $_POST['winners_product_country'];

				if ( ! empty( $_POST['winners_product_brand'] ) ) {
					$product['brand_id'] = $_POST['winners_product_brand'];
				}

				if ( empty( $_POST['winners_product_entries'] ) ) {
					$bw_winners_global_site->entities->delete_product_entries( $post_id );
				} else {
					$bw_winners_global_site->entities->set_product_entries( $post_id, $_POST['winners_product_entries'] );
				}

				if ( empty( $_POST['winners_product_awards'] ) ) {
					$bw_winners_global_site->entities->delete_product_awards( $post_id );
				} else {
					$bw_winners_global_site->entities->set_product_awards( $post_id, $_POST['winners_product_awards'] );
				}
			}

			$bw_winners_global_site->entities->update_product( $product );
		}
	}
}
