<?php
/**
 * Host Override Meta Box
 *
 * @package SOVLIX\ZMEET
 */

namespace SOVLIX\ZMEET\Admin;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Zmeet_Host_Metabox' ) ) {
	/**
	 * Adds a meta box to zmeet_meeting posts so admins can override the displayed host name.
	 */
	class Zmeet_Host_Metabox {

		/**
		 * Constructor.
		 */
		public function __construct() {
			add_action( 'add_meta_boxes', array( $this, 'register' ) );
			add_action( 'save_post_zmeet_meeting', array( $this, 'save' ) );
		}

		/**
		 * Register the meta box.
		 */
		public function register() {
			add_meta_box(
				'zmeet_host_metabox',
				__( 'Meeting Host', 'zoomeet' ),
				array( $this, 'render' ),
				'zmeet_meeting',
				'side',
				'default'
			);
		}

		/**
		 * Render meta box HTML.
		 *
		 * @param \WP_Post $post Current post object.
		 */
		public function render( $post ) {
			wp_nonce_field( 'zmeet_host_nonce_action', 'zmeet_host_nonce_field' );

			$zoom_host_email    = get_post_meta( $post->ID, 'zmeet_zoom_host_email', true );
			$host_override_name = get_post_meta( $post->ID, 'zmeet_host_override_name', true );

			echo '<p><strong>' . esc_html__( 'Zoom Host Email:', 'zoomeet' ) . '</strong> ';
			echo '<code>' . esc_html( $zoom_host_email ? $zoom_host_email : __( 'Not set', 'zoomeet' ) ) . '</code></p>';

			echo '<p><label for="zmeet_host_override_name"><strong>' . esc_html__( 'Display Name Override:', 'zoomeet' ) . '</strong></label></p>';
			echo '<input type="text" id="zmeet_host_override_name" name="zmeet_host_override_name" value="' . esc_attr( $host_override_name ) . '" style="width:100%;" placeholder="' . esc_attr__( 'Leave blank to use Zoom host email', 'zoomeet' ) . '" />';
			echo '<p class="description">' . esc_html__( 'Overrides the "Hosted By" name shown on the meeting page.', 'zoomeet' ) . '</p>';
		}

		/**
		 * Save meta box value.
		 *
		 * @param int $post_id Post ID.
		 */
		public function save( $post_id ) {
			if ( ! isset( $_POST['zmeet_host_nonce_field'] ) ) {
				return;
			}
			if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['zmeet_host_nonce_field'] ) ), 'zmeet_host_nonce_action' ) ) {
				return;
			}
			if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
				return;
			}
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
				return;
			}
			if ( isset( $_POST['zmeet_host_override_name'] ) ) {
				update_post_meta( $post_id, 'zmeet_host_override_name', sanitize_text_field( wp_unslash( $_POST['zmeet_host_override_name'] ) ) );
			}
		}
	}
}
