<?php

/**
 * Template Activation and Display Settings Handler.
 *
 * This file contains logic for initializing default templates and handling
 * AJAX requests to activate author bio, archive, and byline templates, as well
 * as toggling their visibility settings from the admin interface.
 *
 * @package Author_Kit
 * @since 1.0.0
 */

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

/**
 * Handles Author Kit Template Activation and Display Toggles via AJAX.
 *
 * This class manages the initialization of default template options,
 * and processes AJAX requests for activating templates, toggling display
 * settings for author bio, archive, and bylines, and fetching toggle states.
 */
class Author_Kit_Template_Activation
{


	/**
	 * Constructor: Hooks AJAX actions and template initialization.
	 *
	 * Registers WordPress actions to initialize template options and handle
	 * AJAX requests related to template activation and visibility toggles.
	 */
	public function __construct()
	{
		add_action('init', array($this, 'author_kit_initialize_template_options'));
		add_action('wp_ajax_author_kit_activate_template', array($this, 'author_kit_activate_template_callback'));
		add_action('wp_ajax_author_kit_fetch_toggle_states', array($this, 'author_kit_fetch_toggle_states_callback'));
		add_action('wp_ajax_author_kit_toggle_author_bio_display', array($this, 'author_kit_toggle_author_bio_display_callback'));
	}
	/**
	 * Initialize default template options.
	 */
	public function author_kit_initialize_template_options()
	{
		$defaults = array(
			'author_kit_author_bio_template'     => 'template-default',
			'author_kit_author_archive_template' => 'archive-template-default',
			'author_kit_custom_byline_template'  => 'byline-default',
		);

		foreach ($defaults as $option => $default_value) {
			if (get_option($option) === false) {
				update_option($option, $default_value);
			}
		}
	}

	/**
	 * Handle AJAX request for activating templates.
	 */
	public function author_kit_activate_template_callback()
	{
		// Verify nonce for security.
		$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
		if (! wp_verify_nonce($nonce, 'author_kit_template_activation')) {
			wp_send_json_error(array('message' => 'Invalid nonce verification.'));
			return;
		}

		// Sanitize inputs.
		$template_id = isset($_POST['template_id']) ? sanitize_text_field(wp_unslash($_POST['template_id'])) : '';
		$category    = isset($_POST['category']) ? sanitize_text_field(wp_unslash($_POST['category'])) : '';

		if (empty($template_id) || empty($category)) {
			wp_send_json_error(array('message' => 'Invalid template ID or category.'));
			return;
		}

		switch ($category) {
			case 'author_bio':
				$update_success = update_option('author_kit_author_bio_template', $template_id);
				break;

			case 'author_archive':
				$update_success = update_option('author_kit_author_archive_template', $template_id);
				break;

			case 'custom_byline':
				$update_success = update_option('author_kit_custom_byline_template', $template_id);
				break;

			default:
				wp_send_json_error(array('message' => 'Invalid category type.'));
				return;
		}

		if ($update_success) {
			wp_send_json_success(
				array(
					'message'            => "Template for '{$category}' activated successfully.",
					'activated_template' => $template_id,
				)
			);
		} else {
			wp_send_json_error(array('message' => 'Failed to update the template option.'));
		}
	}


	/**
	 * Handle AJAX request to fetch toggle states.
	 */
	public function author_kit_fetch_toggle_states_callback()
	{
		check_ajax_referer('author_kit_toggle_bio_display', 'nonce');

		$options = array(
			'bio'     => 'author_kit_bio_display',
			'archive' => 'author_kit_archive_display',
			'byline'  => 'author_kit_byline_display',
		);

		$states = array();
		foreach ($options as $key => $author_kit_option_name) {
			// Update template option.
			// We use validated, prefixed option names stored in $valid_categories.
			// Each option name is hardcoded and prefixed with 'author_kit_' to avoid conflicts.
			// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
			$states[$key] = get_option($author_kit_option_name, false);
		}

		wp_send_json_success($states);
	}

	/**
	 * Handle AJAX request to toggle author bio (and related) display.
	 */
	public function author_kit_toggle_author_bio_display_callback()
	{

		$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
		if (! wp_verify_nonce($nonce, 'author_kit_toggle_bio_display')) {
			wp_send_json_error(array('message' => 'Invalid nonce.'));
			return;
		}

		$new_state    = isset($_POST['state']) ? filter_var(wp_unslash($_POST['state']), FILTER_VALIDATE_BOOLEAN) : false;
		$setting_type = isset($_POST['setting_type']) ? sanitize_text_field(wp_unslash($_POST['setting_type'])) : '';
		check_ajax_referer('author_kit_toggle_bio_display', 'nonce');

		switch ($setting_type) {
			case 'bio':
				$update_success = update_option('author_kit_bio_display', $new_state);
				$option_value   = get_option('author_kit_bio_display');
				break;

			case 'archive':
				$update_success = update_option('author_kit_archive_display', $new_state);
				$option_value   = get_option('author_kit_archive_display');
				break;

			case 'byline':
				$update_success = update_option('author_kit_byline_display', $new_state);
				$option_value   = get_option('author_kit_byline_display');
				break;

			default:
				wp_send_json_error(array('message' => 'Invalid setting type.'));
				return;
		}

		if ($update_success) {
			wp_send_json_success(
				array(
					'message' => ucfirst($setting_type) . ' setting updated successfully.',
					'state'   => $option_value,
				)
			);
		} else {
			wp_send_json_error(array('message' => 'Failed to update the setting.'));
		}
	}
}

// Initialize the class.
new Author_Kit_Template_Activation();
