<?php

namespace QuizPress\Ajax;

use QuizPress\Classes\AbstractAjaxHandler;
use QuizPress\Helper;
use Spatie\Ray\Support\RateLimiter;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Addons extends AbstractAjaxHandler {
    public function __construct() {
        $this->actions = [
            'get_all_addons' => [
				'callback' => [ $this, 'get_all_addons' ],
				'capability' => 'manage_options' 
			],
            'saved_addon_status' => [
                'callback' => [ $this, 'saved_addon_status' ],
				'capability' => 'manage_options' 
            ],
        ];
    }

	public function get_all_addons() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die();
		}
		$quizpress_addons = json_decode( get_option( QUIZPRESS_ADDONS_SETTINGS_NAME, '{}' ) );
		wp_send_json_success( $quizpress_addons );
	}

	public function saved_addon_status( $payload ) {
		$addon_name = $payload['addon_name'] ?? '';
		$addon_slug = $payload['addon_slug'] ?? '';
		$status = filter_var( $payload['status'] ?? false, FILTER_VALIDATE_BOOLEAN );

		if ( empty( $addon_slug ) ) {
			wp_send_json_error( __( 'Addon Name missing', 'quizpress' ) );
		}

		if ( $status ) {
			$required_plugin = json_decode( $payload['required_plugin'] ?? '' , true);
			do_action( 'quizpress/before_active_addon', $addon_slug, $required_plugin );
			if ( $required_plugin && is_array( $required_plugin ) ) {
				foreach ( $required_plugin as $plugin ) {
					if ( ! Helper::is_plugin_active( sanitize_text_field( $plugin['plugin_dir_path'] ) ) ) {
						$error_message = sprintf( '%s Plugin is required to activate %s addon.', sanitize_text_field( $plugin['plugin_name'] ), $addon_name );
						wp_send_json_error( $error_message );
					}
				}
			}
		}

		$saved_addons = (array) json_decode( get_option( QUIZPRESS_ADDONS_SETTINGS_NAME ), true );
		$saved_addons[ $addon_slug ] = ( $status === "false" || $status === false ) ? false : true;
		update_option( QUIZPRESS_ADDONS_SETTINGS_NAME, wp_json_encode( $saved_addons ) );
		// Fire Addon Action
		if ( $status ) {
			do_action( "quizpress/addons/activated_{$addon_slug}", $status );
		} else {
			do_action( "quizpress/addons/deactivated_{$addon_slug}", $status );
		}
		// response
		wp_send_json_success( $saved_addons );
	}

}