<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Sifency_Addons_TB_Assets_Manager {

	private $target_cpts = array(
		'doc',
		'portfolio',
		'service',
		'team',
		'event',
		'career',
		'award',
		'client',
		'digital',
		'testimonial',
		'menu',
		'post',
		'stack',
	);

	public function __construct() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
	}

	public function enqueue_admin_assets( $hook ) {
		$screen = get_current_screen();

		if ( ! $screen ) {
			return;
		}

		$is_sifency_page = ( strpos( $screen->id, 'sifency' ) !== false );
		$is_target_cpt   = in_array( $screen->post_type, $this->target_cpts );

		if ( ! $is_sifency_page && ! $is_target_cpt ) {
			return;
		}

		wp_enqueue_style( 'select2', SIFENCY_TB_URL . 'assets/css/select2.min.css', array(), '4.0.13' );
		wp_enqueue_script( 'select2', SIFENCY_TB_URL . 'assets/js/select2.min.js', array( 'jquery' ), '4.0.13', true );

		wp_enqueue_style( 'sifency-addons-admin-tb', SIFENCY_TB_URL . 'assets/css/admin.css', array(), SIFENCY_TB_VERSION );

		$admin_tb_deps = array( 'jquery', 'select2', 'jquery-ui-sortable' );

		if ( function_exists( 'sifency_addons_enqueue_template_inline_edit_assets' ) ) {
			if ( false !== strpos( $screen->id, 'sifency-theme-builder' ) ) {
				sifency_addons_enqueue_template_inline_edit_assets(
					'sifency_update_template_details',
					'sifency_admin_nonce'
				);
				$admin_tb_deps[] = 'sifency-template-inline-edit';
			} elseif ( $is_target_cpt ) {
				sifency_addons_enqueue_template_inline_edit_assets(
					'sifency_update_cpt_post_details',
					'sifency_meta_nonce'
				);
				$admin_tb_deps[] = 'sifency-template-inline-edit';
			}
		}

		wp_enqueue_script( 'sifency-addons-admin-tb', SIFENCY_TB_URL . 'assets/js/admin.js', $admin_tb_deps, SIFENCY_TB_VERSION, true );

		wp_localize_script(
			'sifency-addons-admin-tb',
			'sifency_tb_admin',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'sifency_admin_nonce' ),
				'i18n'     => array(
					'loading' => __( 'Loading...', 'sifency-addons' ),
					'error'   => __( 'An error occurred.', 'sifency-addons' ),
					'saved'   => __( 'Saved!', 'sifency-addons' ),
				),
			)
		);

		wp_enqueue_script( 'sifency-cpt-select2-update', SIFENCY_TB_URL . 'assets/js/cpt-select2-update.js', array( 'jquery', 'select2' ), SIFENCY_TB_VERSION, true );
		wp_localize_script(
			'sifency-cpt-select2-update',
			'sifency_cpt_select2',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'sifency_term_nonce' ),
			)
		);

		wp_enqueue_script( 'sifency-cpt-meta-modal', SIFENCY_TB_URL . 'assets/js/cpt-meta-modal.js', array( 'jquery' ), SIFENCY_TB_VERSION, true );
		wp_localize_script(
			'sifency-cpt-meta-modal',
			'sifency_cpt_meta',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'sifency_meta_nonce' ),
			)
		);
	}
}
