<?php
namespace AcademyProEmail;

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

class Helper {

	public static function sanitize_email_template_data( $template_data ) {
		if ( ! is_array( $template_data ) ) {
			return $template_data;
		}
		$prepared_template_data = [];
		foreach ( $template_data as $template_name => $template_arr ) {
			$prepared_template_data[ $template_name ] = self::sanitize_email_template_item( $template_arr );
		}
		return $prepared_template_data;
	}

	public static function sanitize_email_template_item( $template_arr ) {
		if ( ! is_array( $template_arr ) ) {
			return $template_arr;
		}
		return array(
			'is_enable' => filter_var( sanitize_text_field( $template_arr['is_enable'] ), FILTER_VALIDATE_BOOLEAN ),
			'email_subject' => sanitize_text_field( $template_arr['email_subject'] ),
			'email_heading' => sanitize_text_field( $template_arr['email_heading'] ),
			'email_content' => wp_kses_post( $template_arr['email_content'] ),
		);
	}

	public static function get_instructors_email_by_course_id( $courseid ) {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$instructorsdata = $wpdb->get_results(
			$wpdb->prepare( "SELECT {$wpdb->users}.ID as user_id,{$wpdb->users}.user_email,{$wpdb->posts}.ID AS course_id FROM {$wpdb->posts} INNER JOIN {$wpdb->usermeta} ON {$wpdb->posts}.ID = {$wpdb->usermeta}.meta_value  INNER JOIN {$wpdb->users} ON {$wpdb->usermeta}.user_id = {$wpdb->users}.ID WHERE {$wpdb->posts}.ID = %d", $courseid ), ARRAY_A
		);

		$instructorsemail = [];

		foreach ( $instructorsdata as $instructor ) {
			array_push( $instructorsemail, $instructor['user_email'] );
		}

		return $instructorsemail;
	}


	public static function get_users_email_by_role( $role = 'Administrator' ) {
		$adminsobj = new \WP_User_Query( array( 'role' => $role ) );
		$adminsdata = $adminsobj->results;
		$adminemails = [];
		foreach ( $adminsdata as $adminemail ) {
			array_push( $adminemails, $adminemail->data->user_email );
		}

		return $adminemails;
	}

	public static function get_email_template_name( $template_name, $template_sub_name ) {
		if ( $template_sub_name ) {
			return str_replace( '_', '-', $template_name ) . '-' . $template_sub_name . '.php';
		}
		return str_replace( '_', '-', $template_name ) . '.php';
	}

	public static function get_instructor_email_by_booking_id( $booking_id ) {
		global $wpdb;

		$booking_id = (int) $booking_id;
		if ( ! $booking_id ) {
			return [];
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$results = $wpdb->get_col(
			$wpdb->prepare(
				"
				SELECT u.user_email
				FROM {$wpdb->posts} AS p
				INNER JOIN {$wpdb->users} AS u ON p.post_author = u.ID
				WHERE p.ID = %d
				",
				$booking_id
			)
		);
		return $results;
	}

}
