<?php
/**
 * Location meta box for editing individual location data.
 *
 * @package SEOvaultSEO\LocalSEO
 */

namespace SEOvaultSEO\LocalSEO;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class LocationMetaBox {

	public static function init() {
		add_action( 'add_meta_boxes', array( __CLASS__, 'add_meta_boxes' ) );
		add_action( 'save_post', array( __CLASS__, 'save' ), 10, 2 );
	}

	public static function add_meta_boxes() {
		$pt = PostType::get_post_type();

		add_meta_box(
			'seovault_location_details',
			__( 'Location Details', 'seovault-ai' ),
			array( __CLASS__, 'render_details' ),
			$pt,
			'normal',
			'high'
		);

		add_meta_box(
			'seovault_location_hours',
			__( 'Opening Hours', 'seovault-ai' ),
			array( __CLASS__, 'render_hours' ),
			$pt,
			'normal',
			'default'
		);
	}

	public static function render_details( $post ) {
		wp_nonce_field( 'seovault_location_meta', 'seovault_location_nonce' );

		$fields         = LocationMeta::get_fields();
		$values         = LocationMeta::get_all( $post->ID );
		$countries      = Countries::get_all();
		$business_types = BusinessTypes::flatten();

		?>
		<table class="form-table">
			<tr>
				<th><label for="business_type"><?php esc_html_e( 'Business Type', 'seovault-ai' ); ?></label></th>
				<td>
					<select name="seovault_location[business_type]" id="business_type" class="seovaultseo-select">
						<option value=""><?php esc_html_e( 'Select a type', 'seovault-ai' ); ?></option>
						<?php foreach ( $business_types as $key => $label ) : ?>
							<option value="<?php echo esc_attr( $key ); ?>" <?php selected( $values['business_type'], $key ); ?>><?php echo esc_html( $label ); ?></option>
						<?php endforeach; ?>
					</select>
				</td>
			</tr>
			<tr>
				<th><label for="business_name"><?php esc_html_e( 'Business Name', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_name]" id="business_name" class="regular-text" value="<?php echo esc_attr( $values['business_name'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_address"><?php esc_html_e( 'Street Address', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_address]" id="business_address" class="regular-text" value="<?php echo esc_attr( $values['business_address'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_address_2"><?php esc_html_e( 'Address Line 2', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_address_2]" id="business_address_2" class="regular-text" value="<?php echo esc_attr( $values['business_address_2'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_city"><?php esc_html_e( 'City', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_city]" id="business_city" class="regular-text" value="<?php echo esc_attr( $values['business_city'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_state"><?php esc_html_e( 'State / Province', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_state]" id="business_state" class="regular-text" value="<?php echo esc_attr( $values['business_state'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_zipcode"><?php esc_html_e( 'Postal Code', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_zipcode]" id="business_zipcode" class="regular-text" value="<?php echo esc_attr( $values['business_zipcode'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_country"><?php esc_html_e( 'Country', 'seovault-ai' ); ?></label></th>
				<td>
					<select name="seovault_location[business_country]" id="business_country" class="seovaultseo-select">
						<option value=""><?php esc_html_e( 'Choose a country', 'seovault-ai' ); ?></option>
						<?php foreach ( $countries as $code => $name ) : ?>
							<?php
							if ( '' === $code ) {
								continue;}
							?>
							<option value="<?php echo esc_attr( $code ); ?>" <?php selected( $values['business_country'], $code ); ?>><?php echo esc_html( $name ); ?></option>
						<?php endforeach; ?>
					</select>
				</td>
			</tr>
			<tr>
				<th><label for="business_phone"><?php esc_html_e( 'Phone', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_phone]" id="business_phone" class="regular-text" value="<?php echo esc_attr( $values['business_phone'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_phone_2nd"><?php esc_html_e( 'Secondary Phone', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_phone_2nd]" id="business_phone_2nd" class="regular-text" value="<?php echo esc_attr( $values['business_phone_2nd'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_fax"><?php esc_html_e( 'Fax', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_fax]" id="business_fax" class="regular-text" value="<?php echo esc_attr( $values['business_fax'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_email"><?php esc_html_e( 'Email', 'seovault-ai' ); ?></label></th>
				<td><input type="email" name="seovault_location[business_email]" id="business_email" class="regular-text" value="<?php echo esc_attr( $values['business_email'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_url"><?php esc_html_e( 'Website URL', 'seovault-ai' ); ?></label></th>
				<td><input type="url" name="seovault_location[business_url]" id="business_url" class="regular-text" value="<?php echo esc_attr( $values['business_url'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="coordinates_lat"><?php esc_html_e( 'Latitude', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[coordinates_lat]" id="coordinates_lat" class="regular-text" value="<?php echo esc_attr( $values['coordinates_lat'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="coordinates_long"><?php esc_html_e( 'Longitude', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[coordinates_long]" id="coordinates_long" class="regular-text" value="<?php echo esc_attr( $values['coordinates_long'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_price_range"><?php esc_html_e( 'Price Range', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_price_range]" id="business_price_range" class="regular-text" value="<?php echo esc_attr( $values['business_price_range'] ); ?>" placeholder="$$"></td>
			</tr>
			<tr>
				<th><label for="business_area_served"><?php esc_html_e( 'Area Served', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_area_served]" id="business_area_served" class="regular-text" value="<?php echo esc_attr( $values['business_area_served'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_vat"><?php esc_html_e( 'VAT ID', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_vat]" id="business_vat" class="regular-text" value="<?php echo esc_attr( $values['business_vat'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_tax"><?php esc_html_e( 'Tax ID', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_tax]" id="business_tax" class="regular-text" value="<?php echo esc_attr( $values['business_tax'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_contact_phone"><?php esc_html_e( 'Contact Phone', 'seovault-ai' ); ?></label></th>
				<td><input type="text" name="seovault_location[business_contact_phone]" id="business_contact_phone" class="regular-text" value="<?php echo esc_attr( $values['business_contact_phone'] ); ?>"></td>
			</tr>
			<tr>
				<th><label for="business_contact_email"><?php esc_html_e( 'Contact Email', 'seovault-ai' ); ?></label></th>
				<td><input type="email" name="seovault_location[business_contact_email]" id="business_contact_email" class="regular-text" value="<?php echo esc_attr( $values['business_contact_email'] ); ?>"></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Primary Location', 'seovault-ai' ); ?></th>
				<td>
					<input type="checkbox" name="seovault_location[is_primary_location]" value="on" <?php checked( $values['is_primary_location'], 'on' ); ?>>
					<span class="description"><?php esc_html_e( 'Mark this as the primary business location.', 'seovault-ai' ); ?></span>
				</td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Open 24/7', 'seovault-ai' ); ?></th>
				<td>
					<input type="checkbox" name="seovault_location[open_247]" value="on" <?php checked( $values['open_247'], 'on' ); ?>>
				</td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Multiple Time Slots', 'seovault-ai' ); ?></th>
				<td>
					<input type="checkbox" name="seovault_location[multiple_opening_hours]" value="on" <?php checked( $values['multiple_opening_hours'], 'on' ); ?>>
				</td>
			</tr>
		</table>
		<?php
	}

	public static function render_hours( $post ) {
		$hours = LocationMeta::get_opening_hours( $post->ID );
		$days  = OpeningHours::get_days();

		?>
		<table class="widefat striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Day', 'seovault-ai' ); ?></th>
					<th><?php esc_html_e( 'First Open', 'seovault-ai' ); ?></th>
					<th><?php esc_html_e( 'First Close', 'seovault-ai' ); ?></th>
					<th><?php esc_html_e( 'Second Open', 'seovault-ai' ); ?></th>
					<th><?php esc_html_e( 'Second Close', 'seovault-ai' ); ?></th>
					<th><?php esc_html_e( '24h', 'seovault-ai' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $days as $day ) : ?>
					<?php $h = $hours[ $day ] ?? array(); ?>
					<tr>
						<td><strong><?php echo esc_html( OpeningHours::get_day_full( $day ) ); ?></strong></td>
						<td><input type="time" name="seovault_location[opening_hours][<?php echo esc_attr( $day ); ?>][_from]" value="<?php echo esc_attr( $h['_from'] ?? '' ); ?>"></td>
						<td><input type="time" name="seovault_location[opening_hours][<?php echo esc_attr( $day ); ?>][_to]" value="<?php echo esc_attr( $h['_to'] ?? '' ); ?>"></td>
						<td><input type="time" name="seovault_location[opening_hours][<?php echo esc_attr( $day ); ?>][_second_from]" value="<?php echo esc_attr( $h['_second_from'] ?? '' ); ?>"></td>
						<td><input type="time" name="seovault_location[opening_hours][<?php echo esc_attr( $day ); ?>][_second_to]" value="<?php echo esc_attr( $h['_second_to'] ?? '' ); ?>"></td>
						<td><input type="checkbox" name="seovault_location[opening_hours][<?php echo esc_attr( $day ); ?>][_24h]" value="on" <?php checked( $h['_24h'] ?? '', 'on' ); ?>></td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php
	}

	public static function save( $post_id, $post ) {
		if ( ! isset( $_POST['seovault_location_nonce'] ) ) {
			return;
		}

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['seovault_location_nonce'] ) ), 'seovault_location_meta' ) ) {
			return;
		}

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

		$pt = PostType::get_post_type();
		if ( $pt !== $post->post_type ) {
			return;
		}

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

		// phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce verified above.
		$data = isset( $_POST['seovault_location'] ) && is_array( $_POST['seovault_location'] )
			? map_deep( wp_unslash( $_POST['seovault_location'] ), 'sanitize_text_field' )
			: array();
		// phpcs:enable WordPress.Security.NonceVerification.Missing

		if ( ! is_array( $data ) ) {
			return;
		}

		if ( isset( $data['is_primary_location'] ) && 'on' === $data['is_primary_location'] ) {
			self::clear_other_primaries( $post_id );
		}

		LocationMeta::set_all( $post_id, $data );
	}

	protected static function clear_other_primaries( $current_id ) {
		$pt = PostType::get_post_type();
		// phpcs:disable WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Small location set; post__not_in required to clear a single primary flag.
		$query = new \WP_Query(
			array(
				'post_type'      => $pt,
				'post_status'    => 'any',
				'posts_per_page' => -1,
				'post__not_in'   => array( $current_id ),
				'meta_key'       => LocationMeta::META_PREFIX . 'is_primary_location',
				'meta_value'     => 'on',
				'fields'         => 'ids',
			)
		);
		// phpcs:enable WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_post__not_in, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value

		if ( $query->have_posts() ) {
			foreach ( $query->posts as $pid ) {
				LocationMeta::set( $pid, 'is_primary_location', '' );
			}
		}
	}
}
