<?php

namespace EmailKing;

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

class App {

	use Internal;

	public static function init() {
		return new self();
	}

	public function __construct() {
		add_action( 'emailking_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'emailking_head', array( $this, 'emailking_head' ) );
		add_action( 'wp_ajax_emailking-app', array( $this, 'page' ) );
		add_action( 'wp_ajax_nopriv_emailking-app', array( $this, 'page' ) );
	}

	public function page() {
		if ( current_user_can( EMAILKING_ACCESS_USER_CAP ) ) {
			include EMAILKING_PLUGIN_DIR . DIRECTORY_SEPARATOR . implode( DIRECTORY_SEPARATOR, array( 'templates', 'app.php' ) );
		}
	}

	public function enqueue_assets() {
		wp_enqueue_style( 'dashicons' );
		wp_enqueue_script( 'emailking-bundle', EMAILKING_PLUGIN_URL . '/assets/bundle.js', array(), EMAILKING_VERSION, true );
		wp_enqueue_style( 'emailking-bundle', EMAILKING_PLUGIN_URL . '/assets/bundle.css', array(), EMAILKING_VERSION );

		// Inline scripts.
		wp_add_inline_script(
			'emailking-bundle',
			sprintf(
				'window.VARS = %s;',
				wp_json_encode(
					array(
						'ajaxurl'  => esc_url( admin_url( 'admin-ajax.php' ) ),
						'_wpnonce' => wp_create_nonce( 'emailking-api' ),
						'url'      => esc_url( EMAILKING_PLUGIN_URL ),
						'siteurl'  => esc_url( site_url() ),
						'cburl'    => get_admin_url(),
					)
				)
			),
			'before'
		);
	}

	public function emailking_head() {
		do_action( 'emailking_enqueue_scripts' );

		wp_styles()->do_items();
		wp_scripts()->do_items();
	}
}
