<?php
/**
 * Register custom post types and taxonomies.
 *
 * - Event (nt_event): the shows/performances
 * - Instance (nt_instance): individual performance dates linked to an Event
 * - Event Category (event_category): Drama, Comedy, Music, Dance, Family, Other
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

/**
 * Register the Event post type.
 */
function northfield_register_event_post_type() {
	$labels = array(
		'name'                  => _x( 'Events', 'Post type general name', 'northfield-theatre' ),
		'singular_name'         => _x( 'Event', 'Post type singular name', 'northfield-theatre' ),
		'menu_name'             => _x( 'Events', 'Admin menu text', 'northfield-theatre' ),
		'add_new'               => __( 'Add New Event', 'northfield-theatre' ),
		'add_new_item'          => __( 'Add New Event', 'northfield-theatre' ),
		'new_item'              => __( 'New Event', 'northfield-theatre' ),
		'edit_item'             => __( 'Edit Event', 'northfield-theatre' ),
		'view_item'             => __( 'View Event', 'northfield-theatre' ),
		'all_items'             => __( 'All Events', 'northfield-theatre' ),
		'search_items'          => __( 'Search Events', 'northfield-theatre' ),
		'not_found'             => __( 'No events found.', 'northfield-theatre' ),
		'not_found_in_trash'    => __( 'No events found in Trash.', 'northfield-theatre' ),
		'featured_image'        => __( 'Event Image', 'northfield-theatre' ),
		'set_featured_image'    => __( 'Set event image', 'northfield-theatre' ),
		'remove_featured_image' => __( 'Remove event image', 'northfield-theatre' ),
		'use_featured_image'    => __( 'Use as event image', 'northfield-theatre' ),
		'archives'              => __( 'Event Archives', 'northfield-theatre' ),
	);

	$args = array(
		'labels'             => $labels,
		'public'             => true,
		'publicly_queryable' => true,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'show_in_rest'       => true,
		'query_var'          => true,
		'rewrite'            => array( 'slug' => 'events', 'with_front' => false ),
		'capability_type'    => 'post',
		'has_archive'        => true,
		'hierarchical'       => false,
		'menu_position'      => 5,
		'menu_icon'          => 'dashicons-tickets-alt',
		'supports'           => array(
			'title',
			'editor',
			'thumbnail',
			'excerpt',
			'custom-fields',
			'revisions',
		),
		'taxonomies'         => array( 'event_category', 'post_tag' ),
	);

	register_post_type( 'nt_event', $args );
}
add_action( 'init', 'northfield_register_event_post_type' );

/**
 * Register the Instance post type (performance dates linked to Events).
 */
function northfield_register_instance_post_type() {
	$labels = array(
		'name'               => _x( 'Instances', 'Post type general name', 'northfield-theatre' ),
		'singular_name'      => _x( 'Instance', 'Post type singular name', 'northfield-theatre' ),
		'menu_name'          => _x( 'Instances', 'Admin menu text', 'northfield-theatre' ),
		'add_new'            => __( 'Add New Instance', 'northfield-theatre' ),
		'add_new_item'       => __( 'Add New Instance', 'northfield-theatre' ),
		'edit_item'          => __( 'Edit Instance', 'northfield-theatre' ),
		'view_item'          => __( 'View Instance', 'northfield-theatre' ),
		'all_items'          => __( 'All Instances', 'northfield-theatre' ),
		'search_items'       => __( 'Search Instances', 'northfield-theatre' ),
		'not_found'          => __( 'No instances found.', 'northfield-theatre' ),
		'not_found_in_trash' => __( 'No instances found in Trash.', 'northfield-theatre' ),
	);

	$args = array(
		'labels'             => $labels,
		'public'             => false,
		'publicly_queryable' => false,
		'show_ui'            => true,
		'show_in_menu'       => 'edit.php?post_type=nt_event',
		'show_in_rest'       => true,
		'query_var'          => false,
		'capability_type'    => 'post',
		'has_archive'        => false,
		'hierarchical'       => false,
		'supports'           => array( 'title', 'custom-fields' ),
	);

	register_post_type( 'nt_instance', $args );
}
add_action( 'init', 'northfield_register_instance_post_type' );

/**
 * Register the Event Category taxonomy.
 */
function northfield_register_event_category_taxonomy() {
	$labels = array(
		'name'              => _x( 'Event Categories', 'Taxonomy general name', 'northfield-theatre' ),
		'singular_name'     => _x( 'Event Category', 'Taxonomy singular name', 'northfield-theatre' ),
		'search_items'      => __( 'Search Categories', 'northfield-theatre' ),
		'all_items'         => __( 'All Categories', 'northfield-theatre' ),
		'edit_item'         => __( 'Edit Category', 'northfield-theatre' ),
		'update_item'       => __( 'Update Category', 'northfield-theatre' ),
		'add_new_item'      => __( 'Add New Category', 'northfield-theatre' ),
		'new_item_name'     => __( 'New Category Name', 'northfield-theatre' ),
		'menu_name'         => __( 'Categories', 'northfield-theatre' ),
	);

	$args = array(
		'labels'            => $labels,
		'hierarchical'      => true,
		'public'            => true,
		'show_ui'           => true,
		'show_admin_column' => true,
		'show_in_rest'      => true,
		'query_var'         => true,
		'rewrite'           => array( 'slug' => 'event-category', 'with_front' => false ),
	);

	register_taxonomy( 'event_category', array( 'nt_event' ), $args );
}
add_action( 'init', 'northfield_register_event_category_taxonomy' );

/**
 * Register default Event Category terms on theme activation.
 */
function northfield_create_default_event_categories() {
	$categories = array(
		'Drama'  => 'Plays, Shakespeare, and dramatic performances',
		'Comedy' => 'Stand-up, farce, and comedic theatre',
		'Music'  => 'Concerts, gigs, and musical performances',
		'Dance'  => 'Ballet, contemporary dance, and movement',
		'Family' => 'Shows suitable for children and families',
		'Other'  => 'Talks, special events, and more',
	);

	foreach ( $categories as $name => $description ) {
		if ( ! term_exists( $name, 'event_category' ) ) {
			wp_insert_term(
				$name,
				'event_category',
				array( 'description' => $description )
			);
		}
	}
}
add_action( 'after_switch_theme', 'northfield_create_default_event_categories' );

/**
 * Register meta boxes for Event custom fields.
 *
 * These provide a native WordPress admin UI for event meta.
 * If ACF is installed, ACF field groups take precedence for the editor.
 */
function northfield_register_event_meta() {
	$event_meta_fields = array(
		'_nt_event_json_id'       => 'string',
		'_nt_summary'             => 'string',
		'_nt_age_guidance'        => 'string',
		'_nt_run_time'            => 'integer',
		'_nt_content_warnings'    => 'string',
		'_nt_venue'               => 'string',
		'_nt_min_price'           => 'number',
		'_nt_max_price'           => 'number',
		'_nt_is_featured'         => 'boolean',
		'_nt_sale_status'         => 'string',
		'_nt_availability'        => 'string',
	);

	foreach ( $event_meta_fields as $key => $type ) {
		register_post_meta( 'nt_event', $key, array(
			'show_in_rest'  => true,
			'single'        => true,
			'type'          => $type,
			'auth_callback' => function () {
				return current_user_can( 'edit_posts' );
			},
		) );
	}

	$instance_meta_fields = array(
		'_nt_instance_json_id'  => 'string',
		'_nt_event_json_id'     => 'string',
		'_nt_datetime'          => 'string',
		'_nt_venue'             => 'string',
		'_nt_availability'      => 'string',
		'_nt_available_seats'   => 'integer',
		'_nt_total_seats'       => 'integer',
		'_nt_sale_status'       => 'string',
	);

	foreach ( $instance_meta_fields as $key => $type ) {
		register_post_meta( 'nt_instance', $key, array(
			'show_in_rest'  => true,
			'single'        => true,
			'type'          => $type,
			'auth_callback' => function () {
				return current_user_can( 'edit_posts' );
			},
		) );
	}
}
add_action( 'init', 'northfield_register_event_meta' );

/**
 * Add meta boxes to Event edit screen.
 */
function northfield_add_event_meta_boxes() {
	add_meta_box(
		'northfield_event_details',
		__( 'Event Details', 'northfield-theatre' ),
		'northfield_event_details_meta_box',
		'nt_event',
		'normal',
		'high'
	);
}
add_action( 'add_meta_boxes', 'northfield_add_event_meta_boxes' );

/**
 * Render the Event Details meta box.
 *
 * @param WP_Post $post The current post object.
 */
function northfield_event_details_meta_box( $post ) {
	wp_nonce_field( 'northfield_event_meta', 'northfield_event_meta_nonce' );

	$fields = array(
		'_nt_summary'          => array( 'label' => 'Summary', 'type' => 'textarea' ),
		'_nt_age_guidance'     => array( 'label' => 'Age Guidance', 'type' => 'text', 'placeholder' => 'e.g. 12+' ),
		'_nt_run_time'         => array( 'label' => 'Running Time (minutes)', 'type' => 'number' ),
		'_nt_content_warnings' => array( 'label' => 'Content Warnings (comma separated)', 'type' => 'text' ),
		'_nt_venue'            => array( 'label' => 'Venue', 'type' => 'select', 'options' => array( 'Main Auditorium', 'Studio', 'Foyer' ) ),
		'_nt_min_price'        => array( 'label' => 'Min Price (£)', 'type' => 'number', 'step' => '0.01' ),
		'_nt_max_price'        => array( 'label' => 'Max Price (£)', 'type' => 'number', 'step' => '0.01' ),
		'_nt_sale_status'      => array( 'label' => 'Sale Status', 'type' => 'select', 'options' => array( 'OnSale', 'NotOnSale', 'SoldOut', 'Closed' ) ),
		'_nt_availability'     => array( 'label' => 'Availability', 'type' => 'select', 'options' => array( 'Available', 'LastFew', 'SoldOut' ) ),
		'_nt_is_featured'      => array( 'label' => 'Featured Event', 'type' => 'checkbox' ),
	);

	echo '<table class="form-table">';
	foreach ( $fields as $key => $field ) {
		$value = get_post_meta( $post->ID, $key, true );
		echo '<tr>';
		echo '<th><label for="' . esc_attr( $key ) . '">' . esc_html( $field['label'] ) . '</label></th>';
		echo '<td>';

		switch ( $field['type'] ) {
			case 'textarea':
				printf(
					'<textarea id="%s" name="%s" rows="3" class="large-text">%s</textarea>',
					esc_attr( $key ),
					esc_attr( $key ),
					esc_textarea( $value )
				);
				break;
			case 'select':
				printf( '<select id="%s" name="%s">', esc_attr( $key ), esc_attr( $key ) );
				echo '<option value="">— Select —</option>';
				foreach ( $field['options'] as $option ) {
					printf(
						'<option value="%s"%s>%s</option>',
						esc_attr( $option ),
						selected( $value, $option, false ),
						esc_html( $option )
					);
				}
				echo '</select>';
				break;
			case 'checkbox':
				printf(
					'<input type="checkbox" id="%s" name="%s" value="1" %s />',
					esc_attr( $key ),
					esc_attr( $key ),
					checked( $value, '1', false )
				);
				break;
			case 'number':
				printf(
					'<input type="number" id="%s" name="%s" value="%s" class="small-text" step="%s" />',
					esc_attr( $key ),
					esc_attr( $key ),
					esc_attr( $value ),
					esc_attr( isset( $field['step'] ) ? $field['step'] : '1' )
				);
				break;
			default:
				printf(
					'<input type="text" id="%s" name="%s" value="%s" class="regular-text" placeholder="%s" />',
					esc_attr( $key ),
					esc_attr( $key ),
					esc_attr( $value ),
					esc_attr( isset( $field['placeholder'] ) ? $field['placeholder'] : '' )
				);
				break;
		}

		echo '</td></tr>';
	}
	echo '</table>';
}

/**
 * Save Event meta box data.
 *
 * @param int $post_id The post ID.
 */
function northfield_save_event_meta( $post_id ) {
	if ( ! isset( $_POST['northfield_event_meta_nonce'] ) ) {
		return;
	}

	if ( ! wp_verify_nonce( $_POST['northfield_event_meta_nonce'], 'northfield_event_meta' ) ) {
		return;
	}

	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$text_fields = array(
		'_nt_summary',
		'_nt_age_guidance',
		'_nt_content_warnings',
		'_nt_venue',
		'_nt_sale_status',
		'_nt_availability',
	);

	foreach ( $text_fields as $field ) {
		if ( isset( $_POST[ $field ] ) ) {
			update_post_meta( $post_id, $field, sanitize_text_field( wp_unslash( $_POST[ $field ] ) ) );
		}
	}

	$number_fields = array( '_nt_run_time', '_nt_min_price', '_nt_max_price' );
	foreach ( $number_fields as $field ) {
		if ( isset( $_POST[ $field ] ) ) {
			update_post_meta( $post_id, $field, floatval( $_POST[ $field ] ) );
		}
	}

	$featured = isset( $_POST['_nt_is_featured'] ) ? '1' : '0';
	update_post_meta( $post_id, '_nt_is_featured', $featured );
}
add_action( 'save_post_nt_event', 'northfield_save_event_meta' );

/**
 * Add venue column to Events admin list.
 *
 * @param array $columns Existing columns.
 * @return array Modified columns.
 */
function northfield_event_admin_columns( $columns ) {
	$new_columns = array();
	foreach ( $columns as $key => $label ) {
		$new_columns[ $key ] = $label;
		if ( $key === 'title' ) {
			$new_columns['nt_venue']        = __( 'Venue', 'northfield-theatre' );
			$new_columns['nt_dates']        = __( 'Dates', 'northfield-theatre' );
			$new_columns['nt_availability'] = __( 'Availability', 'northfield-theatre' );
		}
	}
	return $new_columns;
}
add_filter( 'manage_nt_event_posts_columns', 'northfield_event_admin_columns' );

/**
 * Populate custom admin columns for Events.
 *
 * @param string $column  Column name.
 * @param int    $post_id Post ID.
 */
function northfield_event_admin_column_content( $column, $post_id ) {
	switch ( $column ) {
		case 'nt_venue':
			echo esc_html( get_post_meta( $post_id, '_nt_venue', true ) );
			break;
		case 'nt_dates':
			$run_time = get_post_meta( $post_id, '_nt_run_time', true );
			if ( $run_time ) {
				$hours   = floor( $run_time / 60 );
				$minutes = $run_time % 60;
				if ( $hours > 0 && $minutes > 0 ) {
					printf( '%dh %dm', $hours, $minutes );
				} elseif ( $hours > 0 ) {
					printf( '%dh', $hours );
				} else {
					printf( '%dm', $minutes );
				}
			}
			break;
		case 'nt_availability':
			$availability = get_post_meta( $post_id, '_nt_availability', true );
			$classes      = array(
				'Available' => 'badge--available',
				'LastFew'   => 'badge--low',
				'SoldOut'   => 'badge--soldout',
			);
			if ( $availability ) {
				$display = str_replace( array( 'LastFew', 'SoldOut' ), array( 'Last Few', 'Sold Out' ), $availability );
				printf(
					'<span style="padding: 2px 8px; border-radius: 3px; font-size: 12px; font-weight: 600;">%s</span>',
					esc_html( $display )
				);
			}
			break;
	}
}
add_action( 'manage_nt_event_posts_custom_column', 'northfield_event_admin_column_content', 10, 2 );

/**
 * Flush rewrite rules on theme activation to register CPT URLs.
 */
function northfield_flush_rewrite_rules() {
	northfield_register_event_post_type();
	northfield_register_instance_post_type();
	northfield_register_event_category_taxonomy();
	flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'northfield_flush_rewrite_rules' );
