<?php

function inoby_assets_version()
{
  if (WP_DEBUG) {
    return time();
  }

  $theme = wp_get_theme();
  return $theme->get("Version");
}

function inoby_enqueue_parted_style($name, $path = "", $deps = null)
{
  $handle = $path ? "{$path}-{$name}" : $name;
  $folder = $path ? "{$path}/{$name}" : $name;
  wp_enqueue_style(
    $handle,
    get_theme_file_uri("/build/css/{$folder}.css"),
    $deps,
    inoby_assets_version(),
  );
}

/**
 * Enqueue a script with a handle that is prefixed with the path
 * @param string $name name of the script
 * @param string $path path to the script
 * @param array $deps dependencies of the script
 * @param bool $in_footer whether to enqueue the script in the footer
 */
function inoby_enqueue_parted_script(
  $name,
  $path = "",
  $deps = ["jquery"],
  $in_footer = false
) {
  $handle = $path ? "{$path}-{$name}" : $name;
  $folder = $path ? "{$path}/{$name}" : $name;
  wp_register_script(
    $handle,
    get_theme_file_uri("/build/js/{$folder}.js"),
    $deps,
    inoby_assets_version(),
    $in_footer,
  );
  array_unshift(wp_scripts()->queue, $handle);
}

function inoby_localize_parted_script($name, $path, $variable, $data)
{
  $handle = $path ? "{$path}-{$name}" : $name;
  wp_localize_script($handle, $variable, $data);
}

if (!is_admin()) {
  function inoby_script_async_defer($tag, $handle, $src)
  {
    $assets = Inoby_Config::assets();
    $all_theme = Inoby_Config::defer_all_theme_scripts();
    $all_plugins = Inoby_Config::defer_all_plugins_scripts();

    $asset = $assets["js"][$handle] ?? null;
    if ($asset && in_array("async", explode("|", $asset))) {
      $tag = str_starts_with(" src", " async src", $tag);
    }

    if (
      ($asset && in_array("defer", explode("|", $asset))) ||
      ($all_theme && str_contains($src, INOBY_CHILD_URI)) ||
      ($all_plugins && str_contains($src, "/wp-content/plugins/"))
    ) {
      $tag = str_replace(" src", " defer src", $tag);
    }

    return $tag;
  }
  add_filter("script_loader_tag", "inoby_script_async_defer", 10, 3);
}

function inoby_theme_enqueue()
{
  $core_deps = ["jquery"];
  // react
  if (Inoby_Config::use_react()) {
    $core_deps[] = "react-dom";
  }

  // default app script
  inoby_enqueue_parted_script("core", "", $core_deps);
  inoby_localize_parted_script(
    "core",
    "",
    "inoby_vars",
    apply_filters("inoby_localize_core_script", [
      "ajax" => [
        "url" => admin_url("admin-ajax.php"),
        "nonce" => wp_create_nonce(),
      ],
      "rest" => [
        "url" => rest_url(),
        "nonce" => wp_create_nonce("wp_rest"),
      ],
      "currency" => [
        "symbol" => function_exists('get_woocommerce_currency_symbol') ? html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8') : '',
      ],
      "recaptcha" => [
        "site_key" => const_or_default("RECAPTCHA_SITE_KEY", ""),
      ],
    ]),
  );

  inoby_enqueue_parted_style("core", "", ["glightbox"]);

  // Enqueue reCAPTCHA v3 script if site key is configured
  $recaptcha_site_key = const_or_default("RECAPTCHA_SITE_KEY", "");
  if (!empty($recaptcha_site_key)) {
    wp_enqueue_script(
      "google-recaptcha",
      "https://www.google.com/recaptcha/api.js?render=" . esc_attr($recaptcha_site_key),
      [],
      null,
      true
    );
  }

  if (ESHOP_ENABLED && is_checkout()) {
    inoby_enqueue_parted_style("checkout", "");
    inoby_enqueue_parted_script("checkout", "");
  }
  if (ESHOP_ENABLED && is_account_page()) {
    inoby_enqueue_parted_style("myaccount", "");
    inoby_enqueue_parted_script("myaccount");
  }
}

add_action("wp_enqueue_scripts", "inoby_theme_enqueue", 0);

add_action("admin_enqueue_scripts", "inoby_admin_enqueue");
function inoby_admin_enqueue()
{
  inoby_register_deps();

  if (file_exists(get_theme_file_path("/build/css/admin.css"))) {
    inoby_enqueue_parted_style("admin", "");
  }
  if (file_exists(get_theme_file_path("/build/js/admin.js"))) {
    inoby_enqueue_parted_script("admin", "", ["jquery", "jquery-ui-resizable"]);
  }

  inoby_enqueue_parted_script(
    "gutenberg",
    "",
    ["jquery", "react-dom"],
    inoby_assets_version(),
  );
  inoby_enqueue_parted_style(
    "gutenberg",
    "",
    ["mb-blocks", "glightbox"],
    inoby_assets_version(),
  );
}

add_action("login_enqueue_scripts", "inoby_login_enqueue");
function inoby_login_enqueue()
{
  if (file_exists(get_theme_file_path("/build/css/admin.css"))) {
    inoby_enqueue_parted_style("admin");
  }
}

//Remove JQuery migrate
function remove_jquery_migrate($scripts)
{
  if (!is_admin() && isset($scripts->registered["jquery"])) {
    $script = $scripts->registered["jquery"];
    if ($script->deps) {
      // Check whether the script has any dependencies

      $script->deps = array_diff($script->deps, ["jquery-migrate"]);
    }
  }
}
add_action("wp_default_scripts", "remove_jquery_migrate");

//Disable emojis in WordPress
add_action("init", "smartwp_disable_emojis");

function smartwp_disable_emojis()
{
  remove_action("wp_head", "print_emoji_detection_script", 7);
  remove_action("admin_print_scripts", "print_emoji_detection_script");
  remove_action("wp_print_styles", "print_emoji_styles");
  remove_filter("the_content_feed", "wp_staticize_emoji");
  remove_action("admin_print_styles", "print_emoji_styles");
  remove_filter("comment_text_rss", "wp_staticize_emoji");
  remove_filter("wp_mail", "wp_staticize_emoji_for_email");
  add_filter("tiny_mce_plugins", "disable_emojis_tinymce");
}

function disable_emojis_tinymce($plugins)
{
  if (is_array($plugins)) {
    return array_diff($plugins, ["wpemoji"]);
  } else {
    return [];
  }
}

function posts_load_more_scripts()
{
  global $wp_query;
  // register our main script but do not enqueue it yet
  wp_register_script(
    "posts_loadmore",
    get_template_directory_uri() . "/assets/js/postsloadmore.js",
    ["jquery"],
  );
  // we have to pass parameters to postsloadmore.js script but we can get the parameters values only in PHP
  // you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
  wp_localize_script("posts_loadmore", "posts_loadmore_params", [
    "ajaxurl" => site_url() . "/wp-admin/admin-ajax.php", // WordPress AJAX
    "posts" => json_encode($wp_query->query_vars), // everything about your loop is here
    "current_page" => get_query_var("paged") ? get_query_var("paged") : 1,
    "max_page" => $wp_query->max_num_pages,
  ]);
  wp_enqueue_script("posts_loadmore");
}
add_action("wp_enqueue_scripts", "posts_load_more_scripts");

// use cdn for popular third party scripts
add_action("wp_enqueue_scripts", "inoby_register_deps", 9999);
function inoby_register_deps()
{
  $scripts = wp_scripts();
  $js = $scripts->registered ?? [];
  // react
  if(!is_admin()) {
    $react = $js["react"];
    $dom = $js["react-dom"];
    if(Inoby_config::trim_react_version()) {
      if (substr_count($react->ver, '.') == 3) {
        $react->ver = substr($react->ver, 0, strpos($react->ver, '.', strpos($react->ver, '.') + 4));
      }
      if (substr_count($dom->ver, '.') == 3) {
        $dom->ver = substr($dom->ver, 0, strpos($dom->ver, '.', strpos($dom->ver, '.') + 4));
      }
    }
    if ($react && $dom) {
      $prod = const_or_default("WP_DEBUG") ? "development" : "production.min";
      wp_deregister_script("react");
      wp_deregister_script("react-dom");
      wp_register_script(
        "react",
        "https://unpkg.com/react@{$react->ver}/umd/react.{$prod}.js",
        $react->deps,
        null,
      );
      wp_register_script(
        "react-dom",
        "https://unpkg.com/react-dom@{$dom->ver}/umd/react-dom.{$prod}.js",
        $dom->deps,
        null,
      );
    }
  }
  // jquery
  $jquery = $js["jquery-core"];
  $jqueryUi = $js["jquery-ui-core"];
  if ($jqueryUi && $jquery) {
    wp_deregister_script("jquery-core");
    wp_deregister_script("jquery-ui-core");
    wp_register_script(
      "jquery-core",
      "https://ajax.googleapis.com/ajax/libs/jquery/{$jquery->ver}/jquery.min.js",
      $jquery->deps,
      null,
    );
    wp_register_script(
      "jquery-ui-core",
      "https://ajax.googleapis.com/ajax/libs/jqueryui/{$jqueryUi->ver}/jquery-ui.min.js",
      $jqueryUi->deps,
      null,
    );
  }
  // GLightbox
  wp_register_style(
    "glightbox",
    "https://cdn.jsdelivr.net/npm/glightbox@3.2.0/dist/css/glightbox.min.css",
    false,
    null,
  );

  $assets = Inoby_Config::assets();

  foreach ($assets["js"] ?? [] as $handle => $action) {
    if ($action == "dequeue") {
      wp_dequeue_script($handle);
    }
  }

  foreach ($assets["css"] ?? [] as $handle => $action) {
    if ($action == "dequeue") {
      wp_dequeue_style($handle);
    }
  }
}

/**
 * Add color styling from theme
 */
function custom_theme_options()
{
  if (Inoby_Config::custom_theme_options()) {
    wp_register_style("custom-theme-options", false);
    wp_enqueue_style("custom-theme-options");
    // fonts
    $font_selection =
      rwmb_meta(
        "theme-fonts-select",
        ["object_type" => "setting"],
        "options",
      ) ?? false
      ? rwmb_meta(
        "theme-fonts-select",
        ["object_type" => "setting"],
        "options",
      )
      : 0;
    $theme_fonts_cfg = Inoby_Config::theme_fonts() ?? 0;
    $fonts = array_slice($theme_fonts_cfg, $font_selection, 1, true) ?? 0;
    $font = reset($fonts);
    $fonts_size =
      rwmb_meta("theme-fonts-size", ["object_type" => "setting"], "options") ??
      false
      ? rwmb_meta("theme-fonts-size", ["object_type" => "setting"], "options")
      : 1;

    // colors
    $scheme_selection =
      rwmb_meta(
        "theme-color-scheme-select",
        ["object_type" => "setting"],
        "options",
      ) ?? false
      ? rwmb_meta(
        "theme-color-scheme-select",
        ["object_type" => "setting"],
        "options",
      )
      : 0;
    $theme_color_schemes_cfg = Inoby_Config::theme_color_schemes();
    $schemes = array_slice(
      $theme_color_schemes_cfg,
      $scheme_selection,
      1,
      true,
    );
    $scheme = reset($schemes);
    // colors
    $theme_css = "body {";
    foreach ($scheme["vars"] as $var => $value) {
      $theme_css .= $var . ":" . $value . ";";
    }
    $theme_css .= "
        --font-family-headings: {$font["ffh"]};
        --font-family: {$font["ff"]};
        --font-size-ratio: {$fonts_size};}";

    wp_add_inline_style("custom-theme-options", $theme_css);
  }
}

function inoby_preload_resources($resources)
{
  $assets = Inoby_Config::assets();

  if (!function_exists('get_url')) {
    function get_url($registred, $handle)
    {
      $url = $registred[$handle]->src;
      $ver = $registred[$handle]->ver;
      if ($ver) {
        $url .= "?ver={$ver}";
      }
      return $url;
    }
  }

  if (!function_exists('get_preload')) {
    function get_preload($assets)
    {
      return array_filter($assets, function ($asset) {
        return in_array("preload", explode("|", $asset));
      });
    }
  }

  foreach (get_preload($assets["css"] ?? []) as $handle => $action) {
    if (wp_style_is($handle, "enqueued")) {
      $url = get_url(wp_styles()->registered, $handle);
      if ($url) {
        $resources[] = [
          "href" => $url,
          "as" => "style",
        ];
      }
    }
  }

  foreach (get_preload($assets["js"] ?? []) as $handle => $action) {
    if (wp_script_is($handle, "enqueued")) {
      $url = get_url(wp_scripts()->registered, $handle);
      if ($url) {
        $resources[] = [
          "href" => $url,
          "as" => "script",
        ];
      }
    }
  }

  return $resources;
}


add_action("admin_enqueue_scripts", "custom_theme_options");
add_action("wp_enqueue_scripts", "custom_theme_options");
add_action("login_enqueue_scripts", "custom_theme_options");
add_action("wp_preload_resources", "inoby_preload_resources");