<?php

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

/**
 * Assets Handler
 */
class DLift_Assets
{
  /**
   * Constructor
   */
  public function __construct()
  {
    add_action('admin_enqueue_scripts', array($this, 'dlift_enqueue_admin_assets'));
  }

  /**
   * Enqueue admin assets
   */
  public function dlift_enqueue_admin_assets($hook)
  {
    if ('toplevel_page_discountlift' !== $hook) {
      return;
    }

    $asset_file = DLift_PLUGIN_PATH . 'build/index.asset.php';
    if (file_exists($asset_file)) {
      $asset = include($asset_file);

      wp_enqueue_script(
        'discountlift-admin',
        DLift_PLUGIN_URL . 'build/index.js',
        $asset['dependencies'],
        $asset['version'],
        true
      );

      wp_enqueue_style(
        'discountlift-admin-style',
        DLift_PLUGIN_URL . 'build/index.css',
        array('wp-components'),
        $asset['version']
      );

      wp_localize_script('discountlift-admin', 'dliftSettings', array(
        'root' => esc_url_raw(rest_url()),
        'nonce' => wp_create_nonce('wp_rest'),
        'pluginUrl' => DLift_PLUGIN_URL
      ));
    }

    // Enqueue the confetti script locally
    wp_enqueue_script(
      'confetti',
      DLift_PLUGIN_URL . 'assets/js/confetti.browser.min.js',
      array(),
      '1.6.0',
      true
    );
  }
}
