<?php
namespace DaftPlug\Generatify\Helpers;

final class Utils
{
  private function __construct() {} // prevent instantiation

  public static function isPluginActive($pluginSlug)
  {
    $wp_plugin_lib = path_join(ABSPATH, 'wp-admin/includes/plugin.php');
    if (file_exists($wp_plugin_lib)) {
      include_once $wp_plugin_lib;
    }

    $paths = [
      'woocommerce' => 'woocommerce/woocommerce.php',
      'buddypress' => 'buddypress/bp-loader.php',
      'peepso' => 'peepso-core/peepso.php',
      'yoastseo' => 'wordpress-seo/wp-seo.php',
      'rankmathseo' => 'seo-by-rank-math/rank-math.php',
      'allinoneseo' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
      'ultimatemember' => 'ultimate-member/ultimate-member.php',
      'wprocket' => 'wp-rocket/wp-rocket.php',
      'lightspeed' => 'lightspeed-cache/lightspeed-cache.php',
    ];

    return is_plugin_active($paths[strtolower($pluginSlug)] ?? "{$pluginSlug}/{$pluginSlug}.php");
  }

  public static function getCurrentUrl($clean = false)
  {
    $http = 'http';
    if (isset($_SERVER['HTTPS'])) {
      $http = 'https';
    }
    $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
    $requestUri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';

    if ($clean == true) {
      return trim(strtok($http . '://' . htmlentities($host) . htmlentities($requestUri), '?'));
    } else {
      return $http . '://' . htmlentities($host) . htmlentities($requestUri);
    }
  }

  public static function getHomeUrl($path = '/', $trailingSlash = true)
  {
    return $trailingSlash ? trailingslashit(home_url($path, 'https')) : untrailingslashit(home_url($path, 'https'));
  }

  public static function getUpgradeUrl()
  {
    return admin_url('admin.php?page=generatify&upgradeToPro=true');
  }

  public static function getSetting($key)
  {
    $keys = preg_split('/\]\[|\[|\]/', $key, -1, PREG_SPLIT_NO_EMPTY);
    $settings = get_option('generatify_settings', []);

    foreach ($keys as $k) {
      if (isset($settings[$k])) {
        $settings = $settings[$k];
      } else {
        return false;
      }
    }

    return $settings;
  }

  public static function enqueueTensorFlow()
  {
    if (!wp_script_is('generatify-tensorflow', 'registered')) {
      wp_register_script('generatify-tensorflow', plugins_url('assets/vendor/js/tf.min.js', GENERATIFY_FILE), [], GENERATIFY_VERSION, true);
    }

    wp_enqueue_script('generatify-tensorflow');
  }
}