<?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/src/Frontend
 * @author      ThemeAtelier<themeatelierbd@gmail.com>
 */

namespace ThemeAtelier\DomainForSale\Frontend;

use ThemeAtelier\DomainForSale\Admin\Offers;
use ThemeAtelier\DomainForSale\Frontend\Helpers\DomainListingLoopHtml;
use ThemeAtelier\DomainForSale\Frontend\Templates\Template_01;
use ThemeAtelier\DomainForSale\Frontend\Helpers\Helpers;

/**
 * The Frontend class to manage all public facing stuffs.
 *
 * @since 1.0.0
 */
class Frontend
{
    /**
     * The slug of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_slug   The slug of this plugin.
     */
    private $plugin_slug;

    /**
     * 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';

        $this->domain_for_sale_public_action();
        add_action('template_redirect', [$this, 'domina_domain_for_sale']);
        add_action('wp_ajax_dfs_form_submit', array($this, 'dfs_form_submit'));
        add_action('wp_ajax_nopriv_dfs_form_submit', array($this, 'dfs_form_submit'));

        add_action('phpmailer_init', function ($phpmailer) {
            if ($phpmailer->Mailer === 'smtp') {
                error_log('✅ SMTP is enabled: ' . $phpmailer->Host);
            } else {
                error_log('❌ SMTP is not enabled. Using: ' . $phpmailer->Mailer);
            }
        });

        add_action('wp_footer', [$this, 'load_font_family']);
    }

    public function load_font_family()
    {
        global $dfs_pro_google_fonts;

        if (empty($dfs_pro_google_fonts)) {
            return;
        }

        // Remove duplicates.
        $fonts = array_unique($dfs_pro_google_fonts);

        // Build the Google Fonts URL.
        $google_fonts_url = add_query_arg(
            array(
                'family'  => implode('|', $fonts),
                'display' => 'swap', // optional, but recommended.
            ),
            'https://fonts.googleapis.com/css'
        );

        wp_enqueue_style(
            'domain-for-sale-google-fonts',
            esc_url($google_fonts_url),
            array(),
            DOMAIN_FOR_SALE_VERSION
        );
    }

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public static function enqueue_styles() {}

    /**
     * Register the stylesheets for the public-facing side of the site.
     *
     * @since    1.0.0
     */
    public static function enqueue_scripts()
    {
        $args = array(
            'post_type'         => 'dfs_template',
            'posts_per_page'    => -1,
        );

        $dfs_posts = new \WP_Query($args);
        $post_ids  = wp_list_pluck($dfs_posts->posts, 'ID');

        foreach ($post_ids as $dfs_id) {
            $options = get_post_meta($dfs_id, 'dfs_template_options', true);
            $dfs_apply_on = isset($options['dfs_apply_on']) ? $options['dfs_apply_on'] : '';

            if ($dfs_apply_on === 'replace_theme') {
                // Remove theme styles & scripts
                add_action('wp_enqueue_scripts', function () {
                    $wp_scripts = wp_scripts();
                    $wp_styles  = wp_styles();
                    $themes_uri = get_theme_root_uri();

                    foreach ($wp_scripts->registered as $wp_script) {
                        if (strpos($wp_script->src, $themes_uri) !== false) {
                            wp_dequeue_script($wp_script->handle);
                        }
                    }

                    foreach ($wp_styles->registered as $wp_style) {
                        if (strpos($wp_style->src, $themes_uri) !== false) {
                            wp_dequeue_style($wp_style->handle);
                        }
                    }
                }, 999);

                $custom_css = 'body{margin:0px;padding:0px}';
                wp_add_inline_style('domain-for-sale-style', $custom_css);
            }
        }

        $settings = get_option('dfs-opt');
        $dfsCustomCss = isset($settings['dfs-custom-css']) ? $settings['dfs-custom-css'] : '';
        $dfsCustomJs = isset($settings['dfs-custom-js']) ? $settings['dfs-custom-js'] : '';

        wp_enqueue_style('ico-font');
        wp_enqueue_style('ta-grid');
        wp_enqueue_style('domain-for-sale-style');
        if (!empty($dfsCustomCss)) {
            wp_add_inline_style('domain-for-sale-style', $dfsCustomCss);
        }

        wp_enqueue_script('sweetalert2');
        wp_enqueue_script('jquery_validate');
        wp_enqueue_script('domain-for-sale-script');
        wp_localize_script('domain-for-sale-script', 'confirmation', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('domain_for_sale_email_nonce'),
            'ip'   => esc_sql(sanitize_text_field($_SERVER['REMOTE_ADDR'])),
        ));
        if (!empty($dfsCustomJs)) {
            wp_add_inline_script('domain-for-sale-script', $dfsCustomJs);
        }
    }

    private function domain_for_sale_public_action()
    {
        add_shortcode('domain_for_sale', array($this, 'domain_for_sale_shortcode_render'));
        add_shortcode('domain_listing', array($this, 'domain_for_sale_listing'));
    }

    /********************
	    - Front end -
     ********************/
    function domina_domain_for_sale()
    {
        if (is_feed() || is_preview() || is_customize_preview()) {
            return;
        }

        $args = array(
            'post_type'         => 'dfs_template',
            'posts_per_page'    => -1,
        );

        $dfs_posts  = new \WP_Query($args);
        $dfs_ids    = wp_list_pluck($dfs_posts->posts, 'ID');

        foreach ($dfs_ids as $dfs_id) {

            $template_options   = get_post_meta($dfs_id, 'dfs_template_options', true);
            $layout             = get_post_meta($dfs_id, 'dfs_layouts', true);
            $dfs_apply_on       = isset($template_options['dfs_apply_on']) ? $template_options['dfs_apply_on'] : '';

            if ($dfs_apply_on === 'replace_theme') {
                include(DOMAIN_FOR_SALE_DIR_PATH . 'src/Frontend/Templates/index.php');
                die();
            }
        }
    }

    /**
     * Function get layout from atts and create class depending on it.
     *
     * @since 2.0
     * @param array $attribute attribute of this shortcode.
     */
    public function domain_for_sale_shortcode_render($attribute)
    {
        if (empty($attribute['id'])) {
            return;
        }
        $shortcode_id = $attribute['id'];

        do_action('dfs_shortcode_rendered', (int) $shortcode_id);
        // Preset Layouts.
        $template_options   = get_post_meta($shortcode_id, 'dfs_template_options', true);
        $layout             = get_post_meta($shortcode_id, 'dfs_layouts', true);
        $dfs_layout_preset  = isset($layout['dfs_layout_preset']) ? $layout['dfs_layout_preset'] : '';

        ob_start();
        if ($dfs_layout_preset === 'layout_01') {
            Template_01::content($template_options);
        }
        return ob_get_clean();
    }

    /**
     * Function get layout from atts and create class depending on it.
     *
     * @since 2.0
     * @param array $attribute attribute of this shortcode.
     */
    public function domain_for_sale_listing($attribute)
    {
        if (empty($attribute['id'])) {
            return;
        }
        $domain_listing_gl_id = $attribute['id'];
        $section_title     = get_the_title($domain_listing_gl_id);
        $listing_template_options = get_post_meta($domain_listing_gl_id, 'listing_template_options', true);
        $listing_layouts = get_post_meta($domain_listing_gl_id, 'listing_layouts', true);
        $listing_layout_preset = isset($listing_layouts['listing_layout_preset']) ? $listing_layouts['listing_layout_preset'] : 'grid_layout';

        if (empty($listing_template_options)) {
            return;
        }

        ob_start();
        DomainListingLoopHtml::domain_listing_html_show($domain_listing_gl_id, $listing_template_options, $section_title, $listing_layout_preset);
        return ob_get_clean();
    }

    /**
     * Handles the email sending process for the "Domain For Sale" form.
     *
     * This function verifies the nonce, sanitizes and processes form data,
     * and sends an email to the specified target email address.
     * Returns a JSON response indicating success or error status.
     *
     * @return void
     */
    public function dfs_form_submit()
    {
        if (! isset($_POST['nonce']) || ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'domain_for_sale_email_nonce')) {
            wp_send_json_error(
                array(
                    'type'        => 'error',
                    'title'       => __('Security Check Failed', 'domain-for-sale'),
                    'description' => __('Nonce verification failed.', 'domain-for-sale'),
                    'okay'        => __('OK', 'domain-for-sale'),
                )
            );
            wp_die();
        }

        // Parse the serialized form data into an array.
        parse_str($_POST['data'], $formData);
        $name    = sanitize_text_field($formData['name']);
        $email   = sanitize_email($formData['email']);
        $domain   = sanitize_text_field($formData['domain']);

        // Get email template and settings from options.
        $options            = get_option('dfs-opt');

        $bidder_confirmations = !empty($options['bidder_confirmations']) ? $options['bidder_confirmations'] : [];
        $handle_subject = in_array('confirmation', $bidder_confirmations, true);

        $email_notification = isset($options['email_notification']) ? $options['email_notification'] : '';
        $dfs_target_mail    = isset($options['dfs-targetemail']) ? $options['dfs-targetemail'] : get_option('admin_email');
        $email_subject    = isset($options['email_subject']) ? $options['email_subject'] : 'New Offer For' . ' ' . $domain;
        $dfs_email_template = isset($options['email_template']) ? $options['email_template'] : '';

        $dfs_success_title       = isset($options['dfs-success-title']) ? $options['dfs-success-title'] : 'Email Sent!';
        $dfs_success_description = isset($options['dfs-success-description']) ? $options['dfs-success-description'] : 'Your message has been successfully sent.';
        $dfs_error_title         = isset($options['dfs-error-title']) ? $options['dfs-error-title'] : 'Error Sending Email';
        $dfs_error_description   = isset($options['dfs-error-description']) ? $options['dfs-error-description'] : 'There was an issue sending your message. Please try again later.';
        $dfs_error_okay          = isset($options['dfs-error-okay']) ? $options['dfs-error-okay'] : 'Ok';
        $email_body = Helpers::dfs_dynamic_variables($dfs_email_template, $formData);
        $subject = Helpers::dfs_dynamic_variables($email_subject, $formData);
        $dfs_target_mail = Helpers::dfs_dynamic_variables($dfs_target_mail);
        $headers    = array('From: ' . $name . ' <' . $email . '>');
        $userInfo = isset($_POST['userInfo']) && is_array($_POST['userInfo']) ? array_map('sanitize_text_field', $_POST['userInfo']) : [];
        $current_user_id    = get_current_user_id();
        if ($current_user_id) {
            $current_user = get_userdata($current_user_id);
            if ($current_user) {
                $extraUserData = [
                    'wp_user_id'    => $current_user->ID,
                    'wp_username'   => $current_user->user_login,
                    'wp_first_name' => get_user_meta($current_user->ID, 'first_name', true),
                    'wp_last_name'  => get_user_meta($current_user->ID, 'last_name', true),
                    'wp_email'      => $current_user->user_email,
                ];
                $userInfo = array_merge($userInfo, $extraUserData);
            }
        }

        // Send email using wp_mail().
        // Store form data in the database.
        global $wpdb;
        $tableUsers = $wpdb->prefix . 'domain_for_sale_offers';
        $verification_token = wp_generate_password(32, false, false);
        $verify_status = 'pending';

        unset($formData['g-recaptcha-response']);
        unset($formData['token']);

        $wpdb->insert(
            $tableUsers,
            [
                'field'     => maybe_serialize($formData),
                'meta'      => maybe_serialize($userInfo),
                'verify_email' => $verification_token,
                'verify_status' => $verify_status,
            ],
            ['%s', '%s', '%s', '%s']
        );

        Offers::verification_mail($formData, $meta ?? [], $handle_subject);

        // --- Email Sending ---
        $email_result = null;
        if ($email_notification) {
            if (wp_mail($dfs_target_mail, $subject, $email_body, $headers)) {
                $email_result = ['success' => true];
            } else {
                $email_result = [
                    'success' => false,
                    'title' => esc_html($dfs_error_title),
                    'okay' => esc_html($dfs_error_okay),
                    'description' => esc_html($dfs_error_description),
                ];
            }
        }

        // --- Final JSON Response ---
        $response = [
            'type' => 'success',
            'title' => esc_html($dfs_success_title),
            'description' => wp_kses_post($dfs_success_description),
        ];

        if (!empty($email_result) && isset($email_result['success']) && !$email_result['success']) {
            $response['type'] = 'error';
            $response['title'] = $email_result['title'];
            $response['description'] = $email_result['description'];
        }

        wp_send_json($response);
        wp_die();
    }
}
