<?php
namespace AcademyProAdvancedAnalytics;

use Academy\Classes\Sanitizer;
use AcademyProAdvancedAnalytics\Admin\Settings as Settings;

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

class Analytics {
	public static function init() {
		$self = new self();
		add_filter( 'academy/get_analytics', array( $self, 'set_advanced_analytics' ) );
		add_action( 'wp_ajax_academy_pro_analytics/update_analytics_settings', array( $self, 'update_analytics_settings' ) );
		add_filter( 'academy/api/settings/get_settings', array( $self, 'add_settings' ) );
		add_action( 'wp_ajax_academy_pro_advanced_analytics/course_view_count', array( $self, 'course_view_analytics' ) );
		add_filter( 'academy/assets/frontend_scripts_data', array( $self, 'academy_courses_track' ) );
	}

	public function add_settings( $settings ) {
		if ( ! isset( $settings['analytics'] ) ) {
			$settings['analytics'] = Settings::get_saved_data();
		}
		return $settings;
	}

	public function set_advanced_analytics( $analytics ) {
		if ( \Academy\Helper::get_addon_active_status( 'quizzes' ) ) {
			$analytics['total_quizzes'] = Helper::get_total_number_of_quizzes();
		}
		$analytics['total_completed_course'] = Helper::get_total_number_of_completed_course();
		return $analytics;
	}

	public function update_analytics_settings() {
		check_ajax_referer( 'academy_nonce', 'security' );
		$payload_data = sanitize_text_field( wp_unslash( $_POST ) );
		$payload = Sanitizer::sanitize_payload([
			// course track
			'is_enable_academy_courses_track'       => 'boolean',
		], $_POST );// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$default = Settings::get_default_data();

		$is_update = Settings::save_settings( [
			'is_enable_academy_courses_track'   => $payload['is_enable_academy_courses_track'] ?? $default['is_enable_academy_courses_track'],
		]);

		if ( ! get_option( 'is_academy_courses_view_analytics' ) && $is_update && ! empty( $payload['is_enable_academy_courses_track'] ) ) {
			Database::init();
			add_option( 'is_academy_courses_view_analytics', $payload );
		}

		do_action( 'academy_pro/admin/after_save_settings', $is_update, 'analytics', $payload_data );
		wp_send_json_success( $is_update );
	}

	public function course_view_analytics() {
		check_ajax_referer( 'academy_nonce', 'security' );
		$course_id = (int) ( isset( $_POST['course_id'] ) ? sanitize_text_field( wp_unslash( $_POST['course_id'] ) ) : 0 );
		if ( $course_id ) {
			$save_settings = Settings::get_saved_data();
			if ( ! isset( $save_settings['is_enable_academy_courses_track'] ) || empty( $save_settings['is_enable_academy_courses_track'] ) ) {
				return false;
			}
			$visitor_ip   = Helper::get_user_ip() ?? '';
			$browser_name = Helper::get_browser_name();
			$deviceType   = Helper::get_device_type();
			$location     = Helper::get_location( $visitor_ip );
			$platform     = Helper::get_platform() ?? '';

			$cookie_name  = 'academy_lms_course_view_' . $course_id;
			$cookie_value = $course_id;
			$cookie_expiry = time() + ( 6 * 60 * 60 );
			if ( ! isset( $_COOKIE[ $cookie_name ] ) ) {
				setcookie( $cookie_name, $cookie_value, $cookie_expiry, '/' );
				$data = array(
					'course_id'  => $course_id,
					'visitor_ip' => $visitor_ip,
					'country'    => $location['country'] ?? '',
					'cities'     => $location['city'] ?? '',
					'platform'   => $platform,
					'browser'    => $browser_name,
					'device'     => $deviceType,
				);
				Helper::insert_analytics_data_into_table( $data );
			}
		}//end if
	}

	public function academy_courses_track( $args ) {
		$save_settings = Settings::get_saved_data();
		$args['is_enable_academy_courses_track'] = (bool) isset( $save_settings['is_enable_academy_courses_track'] ) ? $save_settings['is_enable_academy_courses_track'] : false;
		return $args;
	}
}
