<?php

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 *
 * @link       https://themeatelier.net
 * @since      1.0.0
 *
 * @package domain-for-sale
 * @subpackage domain-for-sale/Helpers
 * @author     ThemeAtelier<themeatelierbd@gmail.com>
 */

namespace ThemeAtelier\DomainForSale\Frontend\Helpers;

/**
 * The Helpers class to manage all public facing stuffs.
 *
 * @since 1.0.0
 */
class Helpers
{

    /**
     * The min of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $min   The slug of this plugin.
     */
    private $min;
    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string $plugin_name       The name of the plugin.
     * @param      string $version    The version of this plugin.
     */
    public function __construct()
    {
        $this->min = defined('WP_DEBUG') && WP_DEBUG ? '' : '.min';
    }

    /**
     * Register the All scripts for the public-facing side of the site.
     *
     * @since    2.0
     */
    public function register_all_scripts()
    {
        wp_register_style('ico-font', DOMAIN_FOR_SALE_ASSETS . 'css/icofont' . $this->min . '.css', array(), DOMAIN_FOR_SALE_VERSION, 'all');
        wp_register_style('sweetalert2', DOMAIN_FOR_SALE_ASSETS . 'css/sweetalert2' . $this->min . '.css', array(), DOMAIN_FOR_SALE_VERSION, 'all');
        wp_register_style('ta-grid', DOMAIN_FOR_SALE_ASSETS . 'css/ta-grid' . $this->min . '.css', array(), DOMAIN_FOR_SALE_VERSION, 'all');
        if ( is_rtl() ) {
            wp_register_style('domain-for-sale-style', DOMAIN_FOR_SALE_ASSETS . 'css/domain-for-sale-style-rtl' . $this->min . '.css', array(), DOMAIN_FOR_SALE_VERSION, 'all');
        }
        wp_register_style('domain-for-sale-style', DOMAIN_FOR_SALE_ASSETS . 'css/domain-for-sale-style' . $this->min . '.css', array(), DOMAIN_FOR_SALE_VERSION, 'all');
        wp_register_script('sweetalert2', DOMAIN_FOR_SALE_ASSETS . 'js/sweetalert2' . $this->min . '.js', array('jquery'), DOMAIN_FOR_SALE_VERSION, true);
        wp_register_script('jquery_validate', DOMAIN_FOR_SALE_ASSETS . 'js/jquery.validate' . $this->min . '.js', array('jquery'), DOMAIN_FOR_SALE_VERSION, true);
        wp_register_script('domain-for-sale-script', DOMAIN_FOR_SALE_ASSETS . 'js/domain-for-sale-script' . $this->min . '.js', array('jquery'), DOMAIN_FOR_SALE_VERSION, true);
    }

    /**
     * Custom Template locator .
     *
     * @param  mixed $template_name template name .
     * @param  mixed $template_path template path .
     * @param  mixed $default_path default path .
     * @return string
     */
    public static function dfs_locate_template($template_name, $default_path = '')
    {
        if (!$default_path) {
            $default_path = DOMAIN_FOR_SALE_DIR_PATH . 'src/Frontend/Templates/';
        }
        $template = locate_template($template_name);
        // Get default template.
        if (!$template) {
            $template = $default_path . $template_name;
        }
        // Return what we found.
        return $template;
    }

    /**
     * Domain for sale pro dashboard capability.
     *
     * Returns the capability required to access the Domain For Sale Pro dashboard.
     *
     * @return string The required capability for the dashboard.
     */
    public static function domain_for_sale_dashboard_capability()
    {
        return apply_filters('domain_for_sale_dashboard_capability', 'manage_options');
    }

    /**
     * Generates the HTML form for the Domain For Sale Pro plugin.
     *
     * Outputs the HTML code for the Domain For Sale form, with dynamic labels, placeholders, and reCAPTCHA support if enabled.
     *
     * @return void
     */
    public static function dfs_html_form_code($template_options)
    {
        // Retrieve form options
        $options                 = get_option('dfs-opt');

        // Form field labels and placeholders
        $price_options           = isset($template_options['price_options']) ? $template_options['price_options'] : '';

        $dfs_name_label           = isset($options['dfs-namelabel']) ? $options['dfs-namelabel'] : 'Name*';
        $dfs_name_placeholder     = isset($options['dfs-nameplaceholder']) ? $options['dfs-nameplaceholder'] : 'Your name';
        $dfs_email_label          = isset($options['dfs-emaillabel']) ? $options['dfs-emaillabel'] : 'Email*';
        $dfs_email_placeholder    = isset($options['dfs-emailplaceholder']) ? $options['dfs-emailplaceholder'] : 'Your email address*';
        $dfs_phone_label        = isset($options['dfs-phone_label']) ? $options['dfs-phone_label'] : 'Phone Number*';
        $dfs_phone_placeholder  = isset($options['dfs-phone_placeholder']) ? $options['dfs-phone_placeholder'] : 'Write your phone number';
        $dfs_offer_label          = isset($options['dfs-offerlabel']) ? $options['dfs-offerlabel'] : 'Offer*';
        $dfs_offer_placeholder    = isset($options['dfs-offerplaceholder']) ? $options['dfs-offerplaceholder'] : 'Your Offer';
        $dfs_proposal_label       = isset($options['dfs-proposallabel']) ? $options['dfs-proposallabel'] : 'Proposal*';
        $dfs_proposal_placeholder = isset($options['dfs-proposalplaceholder']) ? $options['dfs-proposalplaceholder'] : 'Write your proposal';
        $dfs_button_label         = isset($options['dfs-buttonlabel']) ? $options['dfs-buttonlabel'] : 'Send Proposal';

        // Form HTML
        $request_uri = isset($_SERVER['REQUEST_URI']) ? wp_unslash($_SERVER['REQUEST_URI']) : '';
        echo '<form class="dfs_form" action="' . esc_attr($request_uri) . '" method="post">';
        echo '<div class="form_field">';
        if ($dfs_name_label) :
            echo '<label  class="form-label" for="name"><span>' . esc_attr($dfs_name_label) . '</span></label>';
        endif;
        echo '<input id="name" class="form-control" required placeholder="' . esc_html($dfs_name_placeholder) . '" type="text" name="name" pattern="[a-zA-Z0-9 ]+"/>';
        echo '</div>';
        echo '<div class="form_field">';
        if ($dfs_email_label) :
            echo '<label  class="form-label" for="email"><span>' . esc_attr($dfs_email_label) . '</span></label>';
        endif;
        echo '<input id="email" class="form-control" required placeholder="' . esc_html($dfs_email_placeholder) . '" type="email" name="email"/>';
        echo '</div>';
        echo '<div class="form_field">';

        if ($dfs_phone_label) :
            echo '<label  class="form-label" for="phone"><span>' . esc_attr($dfs_phone_label) . '</span></label>';
        endif;
        echo '<input id="phone" class="form-control" required placeholder="' . esc_html($dfs_phone_placeholder) . '" type="number" name="phone"/>';
        echo '</div>';
        echo '<div class="form_field">';

        if ($dfs_proposal_label) :
            echo '<label  class="form-label" for="proposal"><span>' . esc_attr($dfs_proposal_label) . '</span></label>';
        endif;
        echo '<textarea id="proposal" name="proposal" rows="4" class="form-control field-message" placeholder="' . esc_html($dfs_proposal_placeholder) . '" required></textarea>';
        echo '</div>';

        echo '<input id="dfs_submit" class="btn btn-block" type="submit" name="dfs-submitted" value="' . esc_html($dfs_button_label) . '">';
        echo '</form>';
    }

    public static function dfs_dynamic_variables($template, $formData = array(), $verification_token = '', $meta = array(), $price = '', $price_currency = '')
    {
        $options = get_option('dfs-opt');
        if(!$price_currency) {
			$price_currency = isset($options['price_currency']) ? $options['price_currency'] : 'usd';
		}
        if ('usd' === $price_currency) {
			$price_currency = '$';
		} else if ('eur' === $price_currency) {
			$price_currency = '€';
		} else if ('aud' === $price_currency) {
			$price_currency = 'A$';
		} else if ('cad' === $price_currency) {
			$price_currency = '$';
		} else if ('gbp' === $price_currency) {
			$price_currency = '£';
		}

        $current_page = !empty($meta['url']) ? $meta['url'] : home_url('/');
        $verifyLink  = $verification_token
            ? add_query_arg(
                [
                    'dfs_verify_email' => $verification_token,
                    'redirect_to'      => $current_page,
                ],
                home_url('/')
            )
            : '';

        $remove = function () {
            return '-';
        };
        add_filter('document_title_separator', $remove);
        $title = wp_get_document_title();
        remove_filter('document_title_separator', $remove);

        $siteTitle     = get_bloginfo('name');
        $adminEmail    = get_option('admin_email');
        $currentTitle  = $title;

        global $wp;
        $currentURL = home_url($wp->request);
        $date       = gmdate('F j, Y, H:i (h:i A) (\G\M\T O)');
        $ip         = esc_sql(sanitize_text_field($_SERVER['REMOTE_ADDR']));

        $currencyPrice  = $price_currency . $price;
        $startingPrice  = $price;
        $currencyStartingPrice  = $price_currency . $price;
        $highestPrice   = $price;
        $currencyHighestPrice  = $price_currency . $price;

        // Form values
        $formValues = is_array($formData) ? array_values($formData) : [];

        // ⚡ Important: put {{price}} BEFORE {price}
        $extraVariables = ['{{price}}', '{price}', '{adminEmail}', '{verifyLink}', '{date}', '{ip}', '{currentURL}', '{siteTitle}', '{currentTitle}', '{{startingPrice}}', '{startingPrice}', '{{highestPrice}}', '{highestPrice}'];

        $extraValues = [$currencyPrice, $price, $adminEmail, $verifyLink, $date, $ip, $currentURL, $siteTitle, $currentTitle, $currencyStartingPrice, $startingPrice, $currencyHighestPrice, $highestPrice];

        $formVariables = array_map(fn($key) => '{' . $key . '}', array_keys($formData));
        $variables = array_merge($extraVariables, $formVariables);
        $values    = array_merge($extraValues, $formValues);

        if (isset($formData['offer'])) {
			array_unshift($variables, '{{offer}}');
			array_unshift($values, $price_currency. $formData['offer']);
		}

        return trim(str_replace($variables, $values, $template));
    }

    public static function ShortCodeScripts($template_options)
	{
		wp_enqueue_style('ico-font');
		wp_enqueue_style('sweetalert2');
		wp_enqueue_style('domain-for-sale-style');

		global $dfs_pro_google_fonts;
		if (! isset($dfs_pro_google_fonts)) {
			$dfs_pro_google_fonts = array();
		}

		$body_typo              = isset($template_options['body_typo']) ? $template_options['body_typo'] : '';
		$domain_name_typo                  = isset($template_options['domain_name_typo']) ? $template_options['domain_name_typo'] : '';
		$sale_title_typo                   = isset($template_options['sale_title_typo']) ? $template_options['sale_title_typo'] : '';
		$dfs_form_title                   = isset($template_options['dfs_form_title']) ? $template_options['dfs_form_title'] : '';
		$recommendation_title_typo         = isset($template_options['recommendation_title_typo']) ? $template_options['recommendation_title_typo'] : '';
		$recommendation_domain_name_typo   = isset($template_options['recommendation_domain_name_typo']) ? $template_options['recommendation_domain_name_typo'] : '';

		$dfs_pro_typography = array(
			$body_typo,
			$domain_name_typo,
			$sale_title_typo,
			$dfs_form_title,
			$recommendation_title_typo,
			$recommendation_domain_name_typo,
		);

		foreach ($dfs_pro_typography as $font) {
			if (isset($font['font-family'], $font['type']) && 'google' === $font['type'] && ! empty($font['font-family'])) {
				$family  = str_replace(' ', '+', $font['font-family']);
				$variant = ! empty($font['font-weight']) ? ':' . $font['font-weight'] : '';
				$dfs_pro_google_fonts[] = $family . $variant;
			}
		}
	}
}
