<?php
namespace AcademyProNotifications;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Notification
 * insert or update notification details
 */
class Helper {

	public static function insert_notification_details( $args ) {
		if ( ! is_array( $args ) ) {
			return false;
		}

		global $wpdb;

		$defaults = array(
			'title' => '',
			'content' => '',
			'status'  => 'UNREAD',
			'receiver_id' => 0,
			'post_id'  => 0,
			'topic_id' => 0,
			'type' => '',
			'created_at' => current_time( 'mysql' ),
		);

		$args = wp_parse_args( $args, $defaults );

		$table_name = $wpdb->prefix . 'academy_notifications';

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->insert(
			$table_name,
			array(
				'title'       => $args['title'],
				'content'     => $args['content'],
				'status'      => $args['status'],
				'receiver_id' => $args['receiver_id'],
				'post_id'     => $args['post_id'],
				'topic_id'    => $args['topic_id'],
				'type'        => $args['type'],
				'created_at'  => $args['created_at'],
			),
			array(
				'%s',
				'%s',
				'%s',
				'%d',
				'%d',
				'%d',
				'%s',
				'%s',
			)
		);
	}

	public static function get_all_notifications_by_user_id( $user_id ) {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$notifications = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}academy_notifications
				WHERE receiver_id = %d ORDER BY created_at DESC",
				$user_id
			),
			OBJECT
		);

		foreach ( $notifications as $notification ) {
			switch ( $notification->type ) {
				case 'user-dashboard':
					$notification->topic_url = \Academy\Helper::get_page_permalink( 'frontend_dashboard_page' );
					break;
				case 'academy_courses':
					$notification->topic_url = get_permalink( $notification->post_id );
					break;
				case 'instructor-approval-request':
					$notification->topic_url = admin_url( 'admin.php?page=academy-instructors' );
					break;
				case 'student-registration':
					$notification->topic_url = admin_url( 'admin.php?page=academy-students' );
					break;
				case 'academy_quizzes':
					$notification->topic_url = esc_url( \Academy\Helper::get_frontend_dashboard_endpoint_url( 'quizzes/attempts/' ) );
					break;
				case 'evaluate_quiz':
					$notification->topic_url = esc_url( \Academy\Helper::get_start_course_permalink( $notification->post_id ) ) . '#/quiz/' . $notification->topic_id;
					if ( \Academy\Helper::get_settings( 'is_enabled_lessons_php_render' ) ) {
						$topic = [
							'type' => 'quiz',
							'slug' => get_post_field( 'post_name', $notification->topic_id )
						];
						$notification->topic_url = \Academy\Helper::get_topic_play_link( $topic, $notification->post_id );
					}
					break;
				case 'academy_pro_assignments':
					$notification->topic_url = esc_url( \Academy\Helper::get_frontend_dashboard_endpoint_url( 'assignments/submitted-assignments/' ) );
					break;
				case 'evaluate_assignments':
					$notification->topic_url = esc_url( \Academy\Helper::get_start_course_permalink( $notification->post_id ) ) . '#/assignment/' . $notification->topic_id;
					if ( \Academy\Helper::get_settings( 'is_enabled_lessons_php_render' ) ) {
						$topic = [
							'type' => 'assignment',
							'slug' => get_post_field( 'post_name', $notification->topic_id )
						];
						$notification->topic_url = \Academy\Helper::get_topic_play_link( $topic, $notification->post_id );
					}
					break;
				case 'question_answer_submit':
					$notification->topic_url = esc_url( \Academy\Helper::get_frontend_dashboard_endpoint_url( 'question-answer' ) );
					break;
				case 'question_answer_reply':
				case 'announcement_publish':
					$notification->topic_url = esc_url( \Academy\Helper::get_start_course_permalink( $notification->post_id ) );
					break;
				case 'withdraw-request':
					$notification->topic_url = esc_url( \Academy\Helper::get_frontend_dashboard_endpoint_url( 'withdrawal' ) );
			}//end switch
		}//end foreach
		return $notifications;
	}

	public static function mark_as_read( $id ) {
		global $wpdb;

		$table = $wpdb->prefix . 'academy_notifications';

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->update(
			$table,
			array(
				'status' => 'READ'
			),
			array(
				'ID' => $id
			),
			array(
				'%s'
			),
			array(
				'%d'
			)
		);
	}

	public static function mark_as_unread( $id ) {
		global $wpdb;

		$table = $wpdb->prefix . 'academy_notifications';

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->update(
			$table,
			array(
				'status' => 'UNREAD'
			),
			array(
				'ID' => $id
			),
			array(
				'%s'
			),
			array(
				'%d'
			)
		);
	}

	public static function delete_notification( $ID ) {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->delete( $wpdb->prefix . 'academy_notifications', array( 'ID' => $ID ), array( '%d' ) );
	}

	public static function get_students_ids_by_course_id( $course_id ) : array {
		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT post_author FROM {$wpdb->posts} WHERE post_parent = %d",
				$course_id
			),
			OBJECT
		);
	}

	public static function get_setting( $setting_name ) : bool {
		$settings = Admin\Settings::get_saved_data();
		if ( array_key_exists( $setting_name, $settings ) ) {
			return $settings[ $setting_name ];
		}

		return false;
	}

	public static function get_instructors( $course_id ) {
		$instructors_data = \Academy\Helper::get_instructors_by_course_id( $course_id );
		$instructors = [];
		if ( ! empty( $instructors_data ) ) {
			foreach ( $instructors_data as $instructor ) {
				$instructors[] = $instructor->ID;
			}
		}
		return $instructors;
	}

	public static function is_enrollment_completed( int $course_id, int $user_id ) : bool {
		global $wpdb;
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		return intval($wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*)
					 FROM {$wpdb->posts} 
					 	WHERE 
							post_type = %s AND
							post_status = %s AND 
							post_author = %d AND 
							post_parent = %d
				",
				'academy_enrolled',
				'completed',
				$user_id,
				$course_id,
			)
		)) > 0;
	}

	public static function is_duplicate( int $course_id, int $user_id ) : bool {
		global $wpdb;
		$table = esc_sql( $wpdb->prefix . ACADEMY_PLUGIN_SLUG . '_notifications' );

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$query = $wpdb->prepare(
			"SELECT COUNT(*) FROM {$table} WHERE type = %s AND status = %s AND receiver_id = %d	AND post_id = %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			'academy_courses',
			'UNREAD',
			$user_id,
			$course_id
		);

		return ( $wpdb->get_var( $query ) > 0 );// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	}

}
