<?php

/**
 * Customizer Integrator Class.
 *
 * @package Kubelio\Customizer
 * @since 1.0.0
 */

namespace Kubelio\Customizer;

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

/**
 * Main Customizer Class
 */
class Setup {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action('customize_register', array($this, 'register_config'));
		add_action('customize_register', array($this, 'update_sections'));
		add_action('customize_controls_enqueue_scripts', array($this, 'control_scripts'), 999);
		add_action('customize_preview_init', array($this, 'preview_scripts'));
		add_action('customize_save_after', array($this, 'invalidate_theme_cache'));
	}

	/**
	 * Register Kirki config
	 */
	public function register_config() {
		if (class_exists('\Kirki')) {
			\Kirki::add_config(
				'kubelio_customizer',
				array(
					'capability'  => 'edit_theme_options',
					'option_type' => 'theme_mod',
				)
			);
		}
	}

	/**
	 * Customize default sections
	 *
	 * @param \WP_Customize_Manager $wp_customize Customize manager.
	 */
	public function update_sections($wp_customize) {
		$wp_customize->remove_section('static_front_page');

		// Rename Site Identity
		if ($wp_customize->get_section('title_tagline')) {
			$wp_customize->get_section('title_tagline')->title = esc_html__('Logo & Identity', 'kubelio');
		}
	}

	/**
	 * Register customizer control scripts
	 */
	public function control_scripts() {
		wp_enqueue_style('kubelio-customizer-panel', get_template_directory_uri() . '/assets/css/admin/customizer-panel.min.css', false, KUBELIO_THEME_VERSION);

		// The bundled Kirki controls.min.js carries a local patch that fixes its
		// field-dependency (active_callback) init timing: upstream wires
		// dependencies on DOMContentLoaded, before the control objects exist, so
		// `params.required` is never set and dependents never hide. The patch
		// re-runs the init on the customizer `ready` event instead. Kirki versions
		// the script with KIRKI_VERSION, which does not change when we patch the
		// file, so bump the registered version to bust stale browser caches.
		$scripts = wp_scripts();
		if (isset($scripts->registered['kirki-customizer'])) {
			$scripts->registered['kirki-customizer']->ver .= '-kubelio-dep1';
		}
	}

	/**
	 * Register customizer preview scripts
	 */
	public function preview_scripts() {
		wp_enqueue_style('kubelio-customizer-preview', get_template_directory_uri() . '/assets/css/admin/customizer-preview.min.css', false, KUBELIO_THEME_VERSION);
	}

	/**
	 * Invalidate theme data cache when customizer is saved
	 */
	public function invalidate_theme_cache() {
		wp_cache_delete('kubelio_theme_data', 'themes');
	}
}
