<?php

namespace Clonable\Traits;

/**
 * Contains helper functions for dealing with WooCommerceView stuff
 */
trait PluginCheck {
    /**
     * Checks if WooCommerce is installed.
     * @return bool true if WooCommerce is installed
     */
    public function woocommerce_is_installed() {
        // Test to see if WooCommerceView is active (including network activated).
        // We also check if the class exists, bacause it's possible to rename the root plugin folder name, which would cause the first check to fail.
        return $this->check_plugin_by_file('woocommerce/woocommerce.php') || class_exists('WooCommerce');   
    }

    /**
     * Check if the Buckaroo payment provider is installed
     * @return bool
     */
    public function buckaroo_installed() {
        return $this->check_plugin_by_file('wc-buckaroo-bpe-gateway/index.php');
    }

    /** 
    * Check if Select PDF Invoices & Packing Slips for WooCommerce is installed
    * @return bool
    */
    public function pdf_invoices_installed() {
        // Check for both the plugin file and the class, as the class might still be available even if the plugin folder name has been changed
        return $this->check_plugin_by_file('woocommerce-pdf-invoices-packing-slips/woocommerce-pdf-invoices-packingslips.php') || class_exists('WPO_WCPDF');
    }   

    /** 
     * Check if the Clonable Advanced plugin is installed
     * @return bool
     */
    public function clonable_advanced_installed() {
        return $this->check_plugin_by_file('clonable-advanced/clonable-advanced.php');
    }

    /**
     * Check if the WooCommerce Multi Currency plugin is installed
     * Check only CURCY
     * @return bool
     */
    public function curcy_multicurreny_installed() {
        return $this->check_plugin_by_file("woocommerce-multi-currency/woocommerce-multi-currency.php");
    }

	/**
	 * Check if the WooCommerce Multi Currency plugin is installed
	 * Checks only Aelia
	 * @return bool
	 */
	public function aelia_currency_installed() {
		return $this->check_plugin_by_file("woocommerce-aelia-currencyswitcher/woocommerce-aelia-currencyswitcher.php");
	}

    private function check_plugin_by_file($plugin) {
        $plugin_path = trailingslashit(WP_PLUGIN_DIR) . $plugin;

        // A customer reported an error, so we built this failsafe
        $active_array = [];
        $network_array = [];
        if (function_exists('wp_get_active_and_valid_plugins')) {
            $active_array = wp_get_active_and_valid_plugins();
        }
        if (function_exists('wp_get_active_network_plugins')) {
            $network_array = wp_get_active_network_plugins();
        }

        return (in_array($plugin_path, $active_array) || in_array($plugin_path, $network_array));
    }
}