<?php
namespace BwWinnersGlobalSite;

if ( ! class_exists( __NAMESPACE__ . '\Brand_Posts' ) ) {

	class Brand_Posts {

		private $post_type = 'brand';

		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 );
			add_filter( 'posts_clauses', [ $this, 'brand_post_clauses' ], 10, 2 );
		}

		public function register () {

			// brand

			$labels = [
				'name' => 'Brands',
				'singular_name' => 'Brand',
				'add_new' => 'Add New Brand',
				'add_new_item' => 'Add New Brand',
				'edit_item' => 'Edit Brand',
				'new_item' => 'New Brand',
				'all_items' => 'All Brands',
				'view_item' => 'View Brand',
				'search_items' => 'Search Brands',
				'not_found' =>  'No Brand Found',
				'not_found_in_trash' => 'No brand found in Trash', 
				'parent_item_colon' => '',
				'menu_name' => 'Brands',
			];

			$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-tag',
				'supports' => [
					'title',
					'editor',
					'excerpt',
					'revisions',
					'thumbnail',
					'author',
					'page-attributes'
				]
			];

			register_post_type( $this->post_type, $args );
		}

		public function add_meta_boxes () {
			add_meta_box(
				'winners_brand_meta_box',
				esc_html__( 'Brand', 'bw-winners-global-site' ),
				[ $this, 'meta_box' ],
				$this->post_type,
				'normal',
				'high'
			);
		}

		public function meta_box ( $post ) {
			wp_nonce_field( basename( __FILE__ ), 'winners_brand_nonce' );

			global $bw_winners_global_site;

			$brand = $bw_winners_global_site->entities->get_brand( $post->ID );

			if ( empty( $brand ) ) {
				return;
			}

			$competitions = $bw_winners_global_site->entities->get_competitions();

			?>
				<h4>Individual Awards</h4>
				<div class="bw-awards-repeater">
					<?php
						if ( $brand['awards'] ) {
							foreach (  $brand['awards'] as $index => $award ) {
								?>
									<div class="bw-field-group">
										<input type="hidden" name="winners_brand_awards[<?php echo $index; ?>][id]" value="<?php echo $award['id'] ?>" size="30" />
										
										<?php if ( $competitions ) : ?>
											<p>
												<label>
													<?php _e( "Competition", 'bw-winners-global-site' ); ?>
													<select class="widefat" name="winners_brand_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_brand_awards[<?php echo $index; ?>][year]" value="<?php echo esc_attr( $award['year'] ); ?>" size="30" />
											</label>
										</p>
										<p>
											<label><?php _e( "Award Name", 'bw-winners-global-site' ); ?>
												<br />
												<input class="widefat" type="text" name="winners_brand_awards[<?php echo $index; ?>][name]" value="<?php echo esc_attr( $award['name'] ); ?>" size="30" />
											</label>
										</p>
										<p>
											<label><?php _e( "Award Country", 'bw-winners-global-site' ); ?>
												<br />
												<input class="widefat" type="text" name="winners_brand_awards[<?php echo $index; ?>][country]" value="<?php echo esc_attr( $award['country'] ); ?>" size="30" />
											</label>
										</p>
										<p>
											<label><?php _e( "Award Region", 'bw-winners-global-site' ); ?>
												<br />
												<input class="widefat" type="text" name="winners_brand_awards[<?php echo $index; ?>][region]" value="<?php echo esc_attr( $award['region'] ); ?>" size="30" />
											</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 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_brand_awards[${awardIndex}][id]" value="" size="30" />
									
									<?php if ($competitions) : ?>
										<p>
											<label>
												<?php _e( "Competition", 'bw-winners-global-site' ); ?>
												<select class="widefat" name="winners_brand_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_brand_awards[${awardIndex}][year]" value="" size="30" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Name", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_brand_awards[${awardIndex}][name]" value="" size="30" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Country", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_brand_awards[${awardIndex}][country]" value="" size="30" />
										</label>
									</p>
									<p>
										<label><?php _e( "Award Region", 'bw-winners-global-site' ); ?>
											<br />
											<input class="widefat" type="text" name="winners_brand_awards[${awardIndex}][region]" value="" size="30" />
										</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

			$brand = $bw_winners_global_site->entities->get_brand( $post->ID );

			if ( ! $brand ) {
				return;
			}

			$brand['name'] = $post->post_title;

			if ( isset( $_POST['winners_brand_nonce'] ) && wp_verify_nonce( $_POST['winners_brand_nonce'], basename( __FILE__ ) ) ) {

				// Update metabox data here


				if ( empty( $_POST['winners_brand_awards'] ) ) {
					$bw_winners_global_site->entities->delete_brand_awards( $post_id );
				} else {
					$bw_winners_global_site->entities->set_brand_awards( $post_id, $_POST['winners_brand_awards'] );
				}
			}

			$bw_winners_global_site->entities->update_brand( $brand );
		}
		
		public function brand_post_clauses ( $clauses, $wp_query ) {
			global $wpdb;

			$brand_posts_name = $wpdb->prefix . 'bw_winners_v2_brand_posts';

			$brand_id = $wp_query->get('brand_id');

			if ($brand_id) {
				$clauses['join'] .= " INNER JOIN {$brand_posts_name} AS brand_posts ON {$wpdb->posts}.ID = brand_posts.post_id ";
				$clauses['where'] .= $wpdb->prepare( " AND brand_posts.brand_id = %d ", $brand_id );
			}

			return $clauses;
		}
	}
}
