<?php
/**
 * Metabox — per-post / per-page protection settings.
 *
 * @package PrivexPasswordProtect
 */

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

/**
 * Class PPMSTR_Metabox
 */
class PPMSTR_Metabox {

	/**
	 * Register hooks.
	 */
	public function init() {
		add_action( 'add_meta_boxes', array( $this, 'register' ) );
		add_action( 'save_post', array( $this, 'save' ), 10, 2 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	/**
	 * Register the metabox on enabled post types.
	 */
	public function register() {
		$post_types = $this->get_enabled_post_types();

		foreach ( $post_types as $pt ) {
			add_meta_box(
				'ppmstr_protection',
				__( 'Password Protection', 'privex-password-protect' ),
				array( $this, 'render' ),
				$pt,
				'side',
				'high'
			);
		}
	}

	private function get_enabled_post_types() {
		return get_post_types( array( 'public' => true ), 'names' );
	}

	/**
	 * Enqueue metabox-specific assets.
	 *
	 * @param string $hook_suffix Admin page hook.
	 */
	public function enqueue( $hook_suffix ) {
		if ( ! in_array( $hook_suffix, array( 'post.php', 'post-new.php' ), true ) ) {
			return;
		}

		wp_enqueue_style(
			'ppmstr-admin-metabox',
			PPMSTR_PLUGIN_URL . 'assets/css/ppmstr-admin-metabox.css',
			array(),
			PPMSTR_VERSION
		);

		wp_enqueue_script(
			'ppmstr-admin',
			PPMSTR_PLUGIN_URL . 'assets/js/ppmstr-admin.js',
			array(),
			PPMSTR_VERSION,
			true
		);
	}

	/**
	 * Render the metabox HTML.
	 *
	 * @param \WP_Post $post Current post object.
	 */
	public function render( $post ) {
		$protected     = get_post_meta( $post->ID, '_ppmstr_protected', true );
		$has_pass      = get_post_meta( $post->ID, '_ppmstr_password', true );
		$allowed_roles = get_post_meta( $post->ID, '_ppmstr_allowed_roles', true );
		$allowed_users = get_post_meta( $post->ID, '_ppmstr_allowed_users', true );
		$sched_start   = get_post_meta( $post->ID, '_ppmstr_schedule_start', true );
		$sched_end     = get_post_meta( $post->ID, '_ppmstr_schedule_end', true );

		if ( ! is_array( $allowed_roles ) ) {
			$allowed_roles = array();
		}
		if ( ! is_array( $allowed_users ) ) {
			$allowed_users = array();
		}

		// Get all editable roles.
		$all_roles = wp_roles()->get_names();
		unset( $all_roles['administrator'] ); // Admin already bypasses.

		// Get users for the selector (limited to 50).
		$wp_users = get_users( array(
			'number'  => 50,
			'orderby' => 'display_name',
			'order'   => 'ASC',
			'fields'  => array( 'ID', 'display_name', 'user_email' ),
		) );

		wp_nonce_field( 'ppmstr_save_meta_' . $post->ID, 'ppmstr_meta_nonce' );
		?>
		<div class="ppmstr-metabox">
			<!-- Toggle + Password -->
			<div class="ppmstr-metabox-field">
				<label class="ppmstr-toggle-wrap">
					<input
						type="checkbox"
						name="ppmstr_protected"
						id="ppmstr-protected-toggle"
						value="1"
						<?php checked( $protected, '1' ); ?>
					/>
					<span class="ppmstr-toggle-slider"></span>
					<span class="ppmstr-toggle-label">
						<?php esc_html_e( 'Enable Protection', 'privex-password-protect' ); ?>
					</span>
				</label>
			</div>

			<div class="ppmstr-metabox-field ppmstr-password-field" id="ppmstr-password-wrap">
				<label for="ppmstr-password-input">
					<?php esc_html_e( 'Password', 'privex-password-protect' ); ?>
				</label>
				<div class="ppmstr-input-group">
					<input
						type="password"
						name="ppmstr_password"
						id="ppmstr-password-input"
						value=""
						placeholder="<?php echo $has_pass ? esc_attr__( '••••••••  (leave blank to keep)', 'privex-password-protect' ) : esc_attr__( 'Enter password', 'privex-password-protect' ); ?>"
						autocomplete="new-password"
					/>
					<button type="button" class="ppmstr-toggle-visibility" id="ppmstr-toggle-pass" aria-label="<?php esc_attr_e( 'Toggle password visibility', 'privex-password-protect' ); ?>">
						<span class="dashicons dashicons-visibility"></span>
					</button>
				</div>
			</div>

			<!-- Divider -->
			<div class="ppmstr-metabox-divider"></div>

			<!-- Access Rules -->
			<div class="ppmstr-metabox-section" id="ppmstr-access-rules-wrap">
				<div class="ppmstr-metabox-section-header" data-toggle="ppmstr-access-rules-body">
					<strong><?php esc_html_e( 'Access Rules', 'privex-password-protect' ); ?></strong>
					<span class="dashicons dashicons-arrow-down-alt2 ppmstr-section-arrow"></span>
				</div>
				<div class="ppmstr-metabox-section-body" id="ppmstr-access-rules-body">
					<!-- Allowed Roles -->
					<div class="ppmstr-metabox-field">
						<label><?php esc_html_e( 'Allowed Roles', 'privex-password-protect' ); ?></label>
						<p class="ppmstr-metabox-hint"><?php esc_html_e( 'These roles can access without password.', 'privex-password-protect' ); ?></p>
						<div class="ppmstr-metabox-roles">
							<?php foreach ( $all_roles as $role_slug => $role_name ) : ?>
								<label class="ppmstr-metabox-checkbox">
									<input type="checkbox" name="ppmstr_allowed_roles[]"
										value="<?php echo esc_attr( $role_slug ); ?>"
										<?php checked( in_array( $role_slug, $allowed_roles, true ) ); ?> />
									<?php echo esc_html( translate_user_role( $role_name ) ); ?>
								</label>
							<?php endforeach; ?>
						</div>
					</div>

					<!-- Allowed Users -->
					<div class="ppmstr-metabox-field">
						<label><?php esc_html_e( 'Allowed Users', 'privex-password-protect' ); ?></label>
						<p class="ppmstr-metabox-hint"><?php esc_html_e( 'Specific users who can access without password.', 'privex-password-protect' ); ?></p>
						<select name="ppmstr_allowed_users[]" multiple class="ppmstr-metabox-select">
							<?php foreach ( $wp_users as $u ) : ?>
								<option value="<?php echo absint( $u->ID ); ?>"
									<?php selected( in_array( (int) $u->ID, $allowed_users, true ) ); ?>>
									<?php echo esc_html( $u->display_name ); ?> (<?php echo esc_html( $u->user_email ); ?>)
								</option>
							<?php endforeach; ?>
						</select>
					</div>
				</div>
			</div>

			<!-- Divider -->
			<div class="ppmstr-metabox-divider"></div>

			<!-- Schedule -->
			<div class="ppmstr-metabox-section" id="ppmstr-schedule-wrap">
				<div class="ppmstr-metabox-section-header" data-toggle="ppmstr-schedule-body">
					<strong><?php esc_html_e( 'Auto-Unlock / Auto-Lock', 'privex-password-protect' ); ?></strong>
					<span class="dashicons dashicons-arrow-down-alt2 ppmstr-section-arrow"></span>
				</div>
				<div class="ppmstr-metabox-section-body" id="ppmstr-schedule-body">
					<p class="ppmstr-metabox-hint"><?php esc_html_e( 'Optionally schedule when this content should automatically unlock (become public) or auto-lock (require password).', 'privex-password-protect' ); ?></p>
					<div class="ppmstr-metabox-field">
						<label for="ppmstr-sched-start"><?php esc_html_e( 'Auto-Unlock At', 'privex-password-protect' ); ?></label>
						<p class="ppmstr-metabox-hint" style="margin-top:0;"><?php esc_html_e( 'Content becomes freely accessible after this date. A countdown timer will appear on the password form.', 'privex-password-protect' ); ?></p>
						<input type="datetime-local" name="ppmstr_schedule_start" id="ppmstr-sched-start"
							value="<?php echo esc_attr( $sched_start ); ?>" style="width:100%;" />
					</div>
					<div class="ppmstr-metabox-field">
						<label for="ppmstr-sched-end"><?php esc_html_e( 'Auto-Lock At', 'privex-password-protect' ); ?></label>
						<p class="ppmstr-metabox-hint" style="margin-top:0;"><?php esc_html_e( 'Content protection turns back ON after this date.', 'privex-password-protect' ); ?></p>
						<input type="datetime-local" name="ppmstr_schedule_end" id="ppmstr-sched-end"
							value="<?php echo esc_attr( $sched_end ); ?>" style="width:100%;" />
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Save metabox data.
	 *
	 * @param int      $post_id Post ID.
	 * @param \WP_Post $post    Post object.
	 */
	public function save( $post_id, $post ) {
		if ( ! isset( $_POST['ppmstr_meta_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ppmstr_meta_nonce'] ) ), 'ppmstr_save_meta_' . $post_id ) ) {
			return;
		}

		$post_type_obj = get_post_type_object( $post->post_type );
		if ( ! current_user_can( $post_type_obj->cap->edit_post, $post_id ) ) {
			return;
		}

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

		// Protection toggle.
		$protected = ! empty( $_POST['ppmstr_protected'] ) ? '1' : '';
		update_post_meta( $post_id, '_ppmstr_protected', $protected );

		// Password (legacy single).
		if ( ! empty( $_POST['ppmstr_password'] ) ) {
			$raw    = sanitize_text_field( wp_unslash( $_POST['ppmstr_password'] ) );
			$hashed = wp_hash_password( $raw );
			update_post_meta( $post_id, '_ppmstr_password', $hashed );
		}

		// Phase 4: Allowed roles.
		$allowed_roles = array();
		if ( isset( $_POST['ppmstr_allowed_roles'] ) && is_array( $_POST['ppmstr_allowed_roles'] ) ) {
			$allowed_roles = array_map( 'sanitize_key', $_POST['ppmstr_allowed_roles'] );
		}
		update_post_meta( $post_id, '_ppmstr_allowed_roles', $allowed_roles );

		// Phase 4: Allowed users.
		$allowed_users = array();
		if ( isset( $_POST['ppmstr_allowed_users'] ) && is_array( $_POST['ppmstr_allowed_users'] ) ) {
			$allowed_users = array_map( 'absint', $_POST['ppmstr_allowed_users'] );
		}
		update_post_meta( $post_id, '_ppmstr_allowed_users', $allowed_users );

		// Phase 4: Protection schedule.
		$sched_start = isset( $_POST['ppmstr_schedule_start'] ) ? sanitize_text_field( wp_unslash( $_POST['ppmstr_schedule_start'] ) ) : '';
		$sched_end   = isset( $_POST['ppmstr_schedule_end'] ) ? sanitize_text_field( wp_unslash( $_POST['ppmstr_schedule_end'] ) ) : '';
		update_post_meta( $post_id, '_ppmstr_schedule_start', $sched_start );
		update_post_meta( $post_id, '_ppmstr_schedule_end', $sched_end );
	}
}
