<?php

defined( 'ABSPATH' ) || exit;

/**
 * Zapier helper functions.
 *
 * @since 2.12.0
 */

use Masteriyo\Addons\Zapier\Setting;
use Masteriyo\Query\CourseQuery;
use Masteriyo\Query\CourseReviewQuery;
use Masteriyo\Query\LessonQuery;
use Masteriyo\Query\QuizQuery;
use Masteriyo\Query\WPUserQuery;
use Masteriyo\Resources\CourseQuestionAnswerResource;
use Masteriyo\Resources\CourseResource;
use Masteriyo\Resources\CourseReviewResource;
use Masteriyo\Resources\LessonResource;
use Masteriyo\Resources\QuizAttemptResource;
use Masteriyo\Resources\QuizResource;
use Masteriyo\Resources\UserCourseResource;
use Masteriyo\Resources\UserResource;

/**
 * Masteriyo zapier get setting.
 *
 * @since 2.12.0
 * @param string $key
 * @param mixed $default_value
 * @return mixed
 */
function masteriyo_zapier_get_setting( $key, $default_value = null ) {
	Setting::read();
	return Setting::get( $key, $default_value );
}

/**
 * Update zapier setting.
 *
 * @since 2.12.0
 * @param string $key
 * @param mixed $value
 * @return void
 */
function masteriyo_zapier_update_setting( $key, $value ) {
	Setting::read();
	Setting::set( $key, $value );
}

/**
 * Masteriyo generate a rand hash.
 *
 * @since 2.12.0
 * @return string
 */
function masteriyo_zapier_rand_hash() {
	if ( ! function_exists( 'openssl_random_pseudo_bytes' ) ) {
		return sha1( wp_rand() );
	}
	return bin2hex( openssl_random_pseudo_bytes( 20 ) );
}

/**
 * Masteriyo zapier api hash.
 *
 * @since 2.12.0
 * @param string $data
 * @return string
 */
function masteriyo_zapier_api_hash( $data ) {
	return hash_hmac( 'sha256', $data, 'mas-zapier-api' );
}

/**
 * Masteriyo zapier verify api .
 *
 * @since 2.12.0
 * @param string $api_key
 * @return boolean
 */
function masteriyo_zapier_verify_api_hash( $user_api_key ) {
	if ( empty( $user_api_key ) ) {
		return false;
	}
	$saved_api_key = masteriyo_zapier_get_setting( 'api_key' );
	return hash_equals( $saved_api_key, $user_api_key );
}

/**
 * Masteriyo zapier send response.
 *
 * @since 2.12.0
 * @param array $response
 * @return void
 */
function masteriyo_zapier_send_response( $response, $status_code = 200 ) {
	header( 'Content-Type: application/json;charset=utf-8;' );
	http_response_code( $status_code );
	echo wp_json_encode( $response );
	exit( -1 );
}

/**
 * Send zapier response message.
 *
 * @since 2.12.0
 * @param string $message
 * @param integer $status_code
 * @return void
 */
function masteriyo_zapier_send_message( $message = '', $status_code = 200 ) {
	$args = array(
		'status' => $status_code,
		'error'  => $message,
	);
	masteriyo_zapier_send_response( $args );
}

/**
 * Retrieve zapier data.
 *
 * @since 2.12.0
 * @return array
 */
function masteriyo_zapier_retrieve_request_data() {
	$request = array_map( 'trim', array_map( 'sanitize_text_field', $_GET ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$posted  = json_decode( file_get_contents( 'php://input' ), true );
	$posted  = $posted ? $posted : array();
	$posted  = array_map( 'trim', array_map( 'sanitize_text_field', $posted ) );
	return array_merge( $request, $posted );
}

/**
 * Get course sample for zapier.
 *
 * @since 2.12.0
 * @return array|false
 */
function masteriyo_zapier_get_course_sample() {
	$course_query = new CourseQuery(
		array(
			'posts_per_page' => 1,
		)
	);
	$course       = current( $course_query->get_courses() );

	return $course ? CourseResource::to_array( $course ) : false;
}

/**
 * Get lesson sample for zapier.
 *
 * @since 2.12.0
 * @return array|false
 */
function masteriyo_zapier_get_lesson_sample() {
	$lesson_query = new LessonQuery(
		array(
			'posts_per_page' => 1,
		)
	);
	$lesson       = current( $lesson_query->get_lessons() );

	return $lesson ? LessonResource::to_array( $lesson ) : false;
}

/**
 * Get quiz sample for zapier.
 *
 * @since 2.12.0
 * @return array|false
 */
function masteriyo_zapier_get_quiz_sample() {
	$quiz_query = new QuizQuery(
		array(
			'posts_per_page' => 1,
		)
	);
	$quiz       = current( $quiz_query->get_quizes() );

	return $quiz ? QuizResource::to_array( $quiz ) : false;
}

/**
 * Get course review sample for zapier.
 *
 * @since 2.12.0
 * @return array|false
 */
function masteriyo_zapier_get_course_review_sample() {
	$course_review_query = new CourseReviewQuery();
	$course_review       = current( $course_review_query->get_courses_reviews() );
	return $course_review ? CourseReviewResource::to_array( $course_review ) : false;
}

/**
 * Get user sample for zapier.
 *
 * @since 2.12.0
 * @return array|false
 */
function masteriyo_zapier_get_user_sample( $type = 'instructor' ) {
	$user_query = new WPUserQuery(
		array(
			'number'   => 1,
			'role__in' => 'instructor' === $type ? array( 'masteriyo_instructor' ) : array( 'masteriyo_student' ),
		)
	);
	$user       = current( $user_query->get_results() );
	return $user ? UserResource::to_array( masteriyo_get_user( $user->ID ) ) : false;
}

/**
 * Masteriyo zapier get user course sample.
 *
 * @since 2.12.0
 * @return array|false
 */
function masteriyo_zapier_get_user_course_sample() {
	global $wpdb;
	$result      = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}masteriyo_user_items WHERE item_type = 'user_course' LIMIT 1;", ARRAY_A );
	$user_course = masteriyo_get_user_course( $result['id'] ?? 0 );

	if ( ! $user_course ) {
		return false;
	}

	$sample = UserCourseResource::to_array( $user_course );
	$user   = masteriyo_get_user( $user_course->get_user_id() );
	$course = masteriyo_get_course( $user_course->get_course_id() );

	if ( $user ) {
		$sample['user'] = UserResource::to_array( $user );
	}

	if ( $course ) {
		$sample['course'] = CourseResource::to_array( $course );
	}

	return $sample;
}

/**
 * Get quiz attempt sample for zapier.
 *
 * @since 2.12.0
 * @return array|false
 */
function masteriyo_zapier_get_quiz_attempt_sample() {
	global $wpdb;
	$result       = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}masteriyo_quiz_attempts LIMIT 1;", ARRAY_A );
	$quiz_attempt = masteriyo_get_quiz_attempt( $result['id'] ?? 0 );

	if ( ! $quiz_attempt ) {
		return false;
	}

	$sample = QuizAttemptResource::to_array( $quiz_attempt );
	$course = masteriyo_get_course( $quiz_attempt->get_course_id() );
	$quiz   = masteriyo_get_quiz( $quiz_attempt->get_quiz_id() );
	$user   = masteriyo_get_user( $quiz_attempt->get_user_id() );

	if ( $quiz ) {
		$sample['quiz'] = QuizResource::to_array( $quiz );
	}

	if ( $user ) {
		$sample['user'] = UserResource::to_array( $user );
	}

	if ( $course ) {
		$sample['course'] = CourseResource::to_array( $course );
	}

	return $sample;
}

/**
 * Get course qa sample for zapier.
 *
 * @since 2.12.0
 * @param string $type question or answer.
 * @return array|false
 */
function masteriyo_zapier_get_course_qa_sample( $type = 'question' ) {
	global $wpdb;

	$sql = "SELECT * FROM {$wpdb->comments} WHERE comment_type = %s";
	if ( 'answer' === $type ) {
		$sql .= ' and comment_parent > 0';
	}
	$sql .= ' ORDER BY comment_date ASC LIMIT 1';

	$result = $wpdb->get_row( $wpdb->prepare( $sql, 'mto_course_qa' ), ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared

	if ( empty( $result ) ) {
		return false;
	}

	$course_qa_obj = masteriyo_get_course_qa( absint( $result['comment_ID'] ) );
	$sample        = CourseQuestionAnswerResource::to_array( $course_qa_obj );
	$course        = masteriyo_get_course( $course_qa_obj->get_course_id() );
	if ( 'answer' === $type ) {
		$question_qa = masteriyo_get_course_qa( $course_qa_obj->get_parent() );
		if ( $question_qa ) {
			$sample['question'] = CourseQuestionAnswerResource::to_array( $question_qa );
		}
	}
	if ( $course ) {
		$sample['course'] = CourseResource::to_array( $course );
	}
	return $sample;
}
