<?php

/**
 * Assets management for Lockee plugin
 */
class Lockee_Assets extends Lockee_Singleton
{
  /**
   * Init the assets loading functionnality
   */
  protected function init() {}

  /**
   * Get the file version based on the last modification time
   */
  private function get_file_version()
  {
    return LOCKEE_VERSION;
  }

  /**
   * Enqueue scripts and styles for frontend
   */
  public function enqueue_scripts()
  {
    wp_enqueue_style(
      'lockee_lock_style',
      plugins_url('/build/lock.css', dirname(__FILE__)),
      [],
      $this->get_file_version(),
      'all'
    );
    wp_enqueue_style(
      'lockee_nunito_font',
      plugins_url('/css/nunito.min.css', dirname(__FILE__)),
      [],
      $this->get_file_version(),
      'all'
    );
    wp_enqueue_style(
      'lockee_global_style',
      plugins_url('/css/lockee.min.css', dirname(__FILE__)),
      [],
      $this->get_file_version(),
      'all'
    );
    wp_add_inline_style(
      'lockee_global_style',
      $this->get_custom_css(),
      'after'
    );
    wp_enqueue_script(
      'lockee_lock',
      plugins_url('/build/lock.js', dirname(__FILE__)),
      ['wp-element'],
      $this->get_file_version(),
      true
    );
    wp_enqueue_script(
      'lockee_theme',
      plugins_url('/js/theme.min.js', dirname(__FILE__)),
      [],
      $this->get_file_version(),
      true
    );
    wp_register_script('lockee_inline_script', '');
    wp_enqueue_script('lockee_inline_script');
    wp_add_inline_script('lockee_inline_script', $this->inline_script(), 'before');
  }

  /**
   * Enqueue scripts and styles for admin
   */
  public function enqueue_admin_scripts($hook)
  {
    if ('post.php' === $hook || 'post-new.php' === $hook) {
      $this->enqueue_scripts();
    }
    if ($hook === 'lockee_lock_page_lockee-settings') {
      $this->enqueue_color_picker($hook);
    }
  }

  /**
   * Enqueue block editor styles for the Lockee block
   */
  public function enqueue_block_editor_styles()
  {
    if (is_admin()) {
      wp_enqueue_style(
        'lockee_global_style',
        plugins_url('/css/lockee.min.css', dirname(__FILE__)),
        [],
        $this->get_file_version(),
        'all'
      );
      wp_enqueue_style(
        'lockee_nunito_font',
        plugins_url('/css/nunito.min.css', dirname(__FILE__)),
        [],
        $this->get_file_version(),
        'all'
      );
      wp_register_style('lockee_lock_style', '');
      wp_enqueue_style('lockee_lock_style');
      wp_add_inline_style(
        'lockee_lock_style',
        $this->get_custom_css(true),
        'after'
      );
      wp_enqueue_script(
        'lockee_block_editor_script',
        plugins_url('/js/theme.min.js', dirname(__FILE__)),
        ['wp-element'],
        $this->get_file_version(),
        true
      );
    }
  }

  /**
   * Enqueue color picker scripts and styles for the settings page
   */
  public function enqueue_color_picker($hook_suffix)
  {
    if ($hook_suffix !== 'lockee_lock_page_lockee-settings') {
      return;
    }
    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script(
      'lockee-color-picker',
      plugins_url('/js/colorpicker.min.js', dirname(__FILE__)),
      array('wp-color-picker'),
      false,
      true
    );
  }

  /**
   * Generate the inline script with configuration for Lockee
   */
  private function inline_script()
  {
    $path = plugin_dir_url(dirname(__FILE__));
    $config = [
      'path' => $path,
      'script' => 'fast-ajax.php',
      'lang' => Lockee_Utils::get_language(),
      'theme' => Lockee_Settings::get_instance()->get_theme(),
      'background' => Lockee_Settings::get_instance()->is_transparent_bg() ? 'no-bg' : '',
    ];

    return sprintf(
      'window._lockeeConfig = %s;',
      wp_json_encode($config)
    );
  }

  /**
   * Generate custom CSS based on the theme colors
   */
  private function get_custom_css($withImportant = false)
  {
    $settings = Lockee_Settings::get_instance();
    $default_colors = $settings->get_default_colors();
    $colors = $settings->get_colors();
    $important = $withImportant ? ' !important' : '';
    $css = "";
    $primaryOrBackgroundChanged = false;
    foreach (['light', 'dark'] as $mode) {
      $selector = $mode === 'light' ? ":root,\n[data-theme='light']" : "[data-theme='dark']";
      $lines = [];
      foreach ($colors[$mode] as $key => $value) {
        if (
          isset($default_colors[$mode][$key]) &&
          strtolower($value) !== strtolower($default_colors[$mode][$key])
        ) {
          if ($key === 'primary' || $key === 'background') {
            $primaryOrBackgroundChanged = true;
          }
          $lines[] = "--lck-thm-{$key}: {$value}{$important};";
        }
      }
      if ($lines) {
        $css .= "{$selector} {\n  " . implode("\n  ", $lines) . "\n}\n";
      }
    }
    if ($primaryOrBackgroundChanged) {
      $css .= "
        :root,
        [data-theme='light'],
        [data-theme='dark'] {
          --lck-thm-primary-10: oklch(from var(--lck-thm-primary) l c h / 10%);
          --lck-thm-primary-20: oklch(from var(--lck-thm-primary) l c h / 20%);
          --lck-thm-primary-30: oklch(from var(--lck-thm-primary) l c h / 30%);
          --lck-thm-primary-40: oklch(from var(--lck-thm-primary) l c h / 40%);
          --lck-thm-primary-60: oklch(from var(--lck-thm-primary) l c h / 60%);
          --lck-thm-primary10: color-mix(in oklab, var(--lck-thm-primary), var(--lck-thm-background) 90%);
          --lck-thm-primary40: color-mix(in oklab, var(--lck-thm-primary), var(--lck-thm-background) 40%);
        }
    ";
    }
    return $css;
  }
}
