<?php

namespace SugarCalendarBookings\Admin;

use SugarCalendarBookings\Admin\DashboardWidget;
use SugarCalendarBookings\Support\Ajax\AbstractController;

/**
 * Dashboard Widget Controller.
 *
 * @since 1.1.0
 */
class DashboardWidgetController extends AbstractController {

	/**
	 * Check if meta name is valid.
	 *
	 * @since 1.1.0
	 *
	 * @param string $meta_name The meta name to validate.
	 *
	 * @return bool
	 */
	private function is_valid_meta_name( string $meta_name ): bool {

		$valid_meta_names = [
			DashboardWidget::SAVE_WIDGET_META_KEY,
		];

		/**
		 * Filter the valid meta names for dashboard widget.
		 *
		 * @since 1.1.0
		 *
		 * @param array $valid_meta_names The valid meta names.
		 */
		$valid_meta_names = apply_filters( 'sugar_calendar_bookings_admin_dashboard_widget_controller_valid_meta_names', $valid_meta_names );

		return in_array( $meta_name, $valid_meta_names, true );
	}

	/**
	 * Save user preference to hide recommended plugin.
	 *
	 * @since 1.1.0
	 */
	public function save_hide_recommended_plugin() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( esc_html__( 'You are not allowed to perform this action.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$rules = [
			'meta_name'  => 'required|string',
			'meta_value' => 'required|string', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- This is a validation rule, not a DB query.
		];

		$data = $this->get_input_data( $rules );

		// Validate that meta_name is in the allowed list.
		if ( ! $this->is_valid_meta_name( $data['meta_name'] ) ) {
			wp_send_json_error( esc_html__( 'Invalid meta name provided.', 'sugar-calendar-bookings-scheduling-appointments-lite' ) );
		}

		$user_id = get_current_user_id();

		if ( ! empty( $data['meta_value'] ) ) {
			update_user_meta( $user_id, $data['meta_name'], true );
		}

		wp_send_json_success();
	}
}
