<?php
/**
 * Frontend asset loading.
 *
 * @package Vanquish\MultipleAddresses\Frontend
 */

namespace Vanquish\MultipleAddresses\Frontend;

use Vanquish\MultipleAddresses\Com\AddressForm;
use Vanquish\MultipleAddresses\Com\Settings;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Enqueues the frontend styles/scripts on the pages the plugin touches
 * (My Account and checkout).
 */
class Assets {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	/**
	 * Enqueue on the relevant WooCommerce pages only.
	 *
	 * @return void
	 */
	public function enqueue() {
		if ( ! function_exists( 'is_account_page' ) ) {
			return;
		}

		if ( ! is_account_page() && ! is_checkout() ) {
			return;
		}

		wp_enqueue_style(
			'vanmuad-frontend',
			VANMUAD_URL . 'assets/css/vanmuad-frontend.css',
			array(),
			VANMUAD_VERSION
		);

		// The merchant's button colour overrides the stylesheet's neutral default
		// through the same custom property, so no rule has to be duplicated.
		$accent = ( new Settings() )->get( 'accent_color', '' );

		if ( is_string( $accent ) && '' !== $accent ) {
			wp_add_inline_style(
				'vanmuad-frontend',
				':root{--vanmuad-accent:' . esc_attr( $accent ) . ';}'
			);
		}

		wp_enqueue_script(
			'vanmuad-frontend',
			VANMUAD_URL . 'assets/js/vanmuad-frontend.js',
			array( 'jquery' ),
			VANMUAD_VERSION,
			true
		);

		wp_localize_script(
			'vanmuad-frontend',
			'vanmuad',
			array(
				'ajax_url'  => admin_url( 'admin-ajax.php' ),
				'nonce'     => wp_create_nonce( 'vanmuad_frontend' ),
				'countries' => AddressForm::country_states(),
				'i18n'      => array(
					'add_title'      => __( 'Add address', 'vanquish-multiple-addresses-for-woocommerce' ),
					'edit_title'     => __( 'Edit address', 'vanquish-multiple-addresses-for-woocommerce' ),
					'confirm_delete' => __( 'Delete this address?', 'vanquish-multiple-addresses-for-woocommerce' ),
					'generic_error'  => __( 'Something went wrong. Please try again.', 'vanquish-multiple-addresses-for-woocommerce' ),
					'select_state'   => __( 'Select an option…', 'vanquish-multiple-addresses-for-woocommerce' ),
				),
			)
		);
	}
}
