<?php

defined('ABSPATH') or die("You can't access this file directly.");

define('QCPND_TPL_DIR', qcpnd_DIR . "/templates");
define('OCPD_TPL_URL', qcpnd_URL . "templates");

/*Custom Item Sort Logic*/
function pcpnd_custom_sort_by_tpl_upvotes($a, $b)
{
	// return $a['qcpnd_upvote_count'] * 1 < $b['qcpnd_upvote_count'] * 1;
	$aTime = isset($a['qcpnd_upvote_count']) && !empty($a['qcpnd_upvote_count']) ? (int) $a['qcpnd_upvote_count'] : 0;
	$bTime = isset($b['qcpnd_upvote_count']) && !empty($b['qcpnd_upvote_count']) ? (int) $b['qcpnd_upvote_count'] : 0;

	if ($aTime === $bTime) {
		return 0;
	}

	return $aTime < $bTime ? 1 : -1;
}

function pcpnd_custom_sort_by_tpl_title($a, $b)
{
	//return $a['qcpnd_item_title'] > $b['qcpnd_item_title'];
	return strnatcasecmp($a['qcpnd_item_title'], $b['qcpnd_item_title']);
}

//For all list elements
add_shortcode('qcpnd-directory', 'qcpnd_directory_full_shortcode');

function qcpnd_directory_full_shortcode($atts = array())
{
	ob_start();
	show_qcpnd_full_list($atts);
	$content = ob_get_clean();
	return $content;
}

function show_qcpnd_full_list($atts = array())
{

	$template_code = "";

	//Defaults & Set Parameters
	extract(shortcode_atts(
		array(
			'orderby' => 'menu_order',
			'order' => 'ASC',
			'mode' => 'all',
			'min_width' => '',
			'list_id' => '',
			'column' => '1',
			'style' => 'simple',
			'list_img' => 'true',
			'search' => 'true',
			'category' => "",
			'upvote' => "on",
			'item_count' => "on",
			'top_area' => "on",
			'item_orderby' => "",
			'item_order' => "",
			'mask_url' => "off",
			'enable_embedding' => 'false',
			'show_phone_icon' => 1,
			'show_link_icon' => 1,
			'main_click_action' => 1,
			'phone_number' => 1,
			'map' => 'hide',
			'showmaponly' => 'no',
			'dark_mode' => get_option('pd_enable_dark_mode')
		),
		$atts
	));

	//ShortCode Atts
	$shortcodeAtts = array(
		'orderby' => esc_attr($orderby),
		'order' => esc_attr($order),
		'mode' => esc_attr($mode),
		'min_width' => esc_attr($min_width),
		'list_id' => esc_attr($list_id),
		'column' => esc_attr($column),
		'style' => esc_attr($style),
		'list_img' => esc_attr($list_img),
		'search' => esc_attr($search),
		'category' => esc_attr($category),
		'upvote' => esc_attr($upvote),
		'item_count' => esc_attr($item_count),
		'top_area' => esc_attr($top_area),
		'item_orderby' => esc_attr($item_orderby),
		'item_order' => esc_attr($item_order),
		'mask_url' => esc_attr($mask_url),
		'enable_embedding' => esc_attr($enable_embedding),
		'show_phone_icon' => esc_attr($show_phone_icon),
		'show_link_icon' => esc_attr($show_link_icon),
		'main_click_action' => esc_attr($main_click_action),
		'phone_number' => esc_attr($phone_number),
		'map' => esc_attr($map),
		'showmaponly' => esc_attr($showmaponly),
		'dark_mode' => esc_attr($dark_mode)
	);

	wp_enqueue_style('qcpnd-custom-css');
	wp_enqueue_style('qcpnd-custom-rwd-css');
	wp_enqueue_style('qcpnd-fontawesome-rwd-css');
	wp_enqueue_script('qcopd-google-map-script');
	if ($showmaponly == 'no') {
		wp_enqueue_script('qcpnd-grid-packery');
		wp_enqueue_script('qcpnd-custom-script');
	}

	if (isset($min_width) && !empty($min_width)) {
		$css = '.qcpnd-list-wrapper {min-width: ' . esc_attr($min_width) . ' }';
		wp_add_inline_style('qcpnd-custom-css', $css);
	}

	$lan_enable_dark_mode = get_option('pd_lan_enable_dark_mode') ? get_option('pd_lan_enable_dark_mode') : 'Enable Dark Mode';
	$lan_dark_mode_on = get_option('pd_lan_dark_mode_on') ? get_option('pd_lan_dark_mode_on') : 'Dark Mode On';
	$lan_light_mode_on = get_option('pd_lan_light_mode_on') ? get_option('pd_lan_light_mode_on') : 'Light Mode On';

	$custom_js = 'jQuery(document).ready(function($) {

			function qcld_dark_light_mode() {
			    // 1. Target the main wrapper and all its nested children in one selection
			    const $wrapper = $(".qcpnd-list-wrapper ul li");
			    const $allItems = $wrapper.find("div, a, h1, h2, h3, h4, h5, h6,h3 span");

			    // 2. Apply base dark theme to the wrapper
			    $wrapper.css({
			        "background-color": "#121212",
			        "color": "#ffffff",
			        "color-scheme": "dark"
			    });

			    // 3. Force all children to inherit the theme
			    $allItems.css({
			        "background-color": "#121212",
			        "color": "#ffffff",
			        "border-color": "#333"
			    });

			    $wrapper.find("a,h3 span, h1, h2, h3, h4, h5, h6").css("color", "#ffffff");
			}

	        function qcld_remove_dark_mode() {
			    const $affectedElements = $(".qcpnd-list-wrapper, .qcpnd-list-wrapper ul, .qcpnd-list-wrapper li, .qcpnd-list-wrapper div, .qcpnd-list-wrapper a, .qcpnd-list-wrapper h1, .qcpnd-list-wrapper h2, .qcpnd-list-wrapper h3, .qcpnd-list-wrapper h4, .qcpnd-list-wrapper h5, .qcpnd-list-wrapper h6, .qcpnd-list-wrapper span");
			    $affectedElements.removeAttr("style");
			}

            $(".qcpnd-list-wrapper").before(`
                <div class="qcld-qcld-theme-switch-wrapper">
                    <label class="qcld-theme-switch" for="qcld-theme-checkbox">
                        <input type="checkbox" id="qcld-theme-checkbox" />
                        <div class="qcld-theme-slider qcld-theme-round">
                            <span class="qcld-theme-icon sun">☀️</span>
                            <span class="qcld-theme-icon moon">🌙</span>
                        </div>
                    </label>
                    <em id="qcld-theme-status">' . esc_html($lan_enable_dark_mode) . '</em>
                </div>
            `);

            const $toggle = $("#qcld-theme-checkbox");
            const $body = $(".qcld-main-style-simple");
            const $statusText = $("#qcld-theme-status");
            const storageKey = "user-theme-pref";
            const currentTheme = localStorage.getItem(storageKey);

            if (currentTheme) {
                $body.addClass(currentTheme);
                if (currentTheme === "dark-mode") {
                    $toggle.prop("checked", true);
                    qcld_dark_light_mode();
                    $statusText.text("' . esc_js($lan_dark_mode_on) . '");
                }
            } else {
                if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
                    $body.addClass("dark-mode");
                    $toggle.prop("checked", true);
                    qcld_remove_dark_mode();
                    $statusText.text("' . esc_js($lan_light_mode_on) . '");
                }
            }

            // Toggle Theme
            $toggle.on("change", function() {
                if ($(this).is(":checked")) {
                    $body.addClass("dark-mode");
                    localStorage.setItem(storageKey, "dark-mode");
                    qcld_dark_light_mode();
                    $statusText.text("' . esc_js($lan_dark_mode_on) . '");
                } else {
                    $body.removeClass("dark-mode");
                    localStorage.setItem(storageKey, "light-mode");
                    qcld_remove_dark_mode();
                    $statusText.text("' . esc_js($lan_light_mode_on) . '");
                }
            });
            
        });';

	if (isset($dark_mode) && ($dark_mode == 'on' || $dark_mode == 'show' || $dark_mode == 'yes')) {

		wp_add_inline_script('qcpnd-custom-script', $custom_js, 'after');
	}

	$limit = -1;

	if ($mode == 'one') {
		$limit = 1;
	}

	//Query Parameters
	$list_args = array(
		'post_type' => 'pnd',
		'post_status' => 'publish',
		'has_password' => false,
		'posts_per_page' => $limit,
	);
	if ($orderby != 'none' or $order != 'none') {
		$list_args['orderby'] = $orderby;
		$list_args['order'] = $order;
	}

	if ($list_id != "" && $mode == 'one') {
		$list_args = array_merge($list_args, array('p' => $list_id));
	}

	if ($category != "") {
		$taxArray = array(
			array(
				'taxonomy' => 'pnd_cat',
				'field' => 'slug',
				'terms' => $category
			),
		);

		$list_args = array_merge($list_args, array('tax_query' => $taxArray));

	}

	// The Query
	$list_query = new WP_Query($list_args);

	if (isset($atts["style"]) && $atts["style"])
		$template_code = $atts["style"];

	if (!$template_code)
		$template_code = "simple";

	if ($mode == 'one') {
		$column = '1';
	}
	?>


	<?php

	echo '<!--  Starting Simple Business Directory Plugin Output -->';
	if (file_exists(QCPND_TPL_DIR . "/" . $template_code . "/template.php")) {
		$tempath = QCPND_TPL_DIR . "/" . $template_code . "/template.php";
	}
	if ($showmaponly == 'yes') {
		if (file_exists(QCPND_TPL_DIR . "/maponly/template.php")) {
			$tempath = QCPND_TPL_DIR . "/maponly/template.php";
		}
	}
	if (isset($tempath) && !empty($tempath)) {
		require($tempath);
	}
	wp_reset_query();
}


function qcpnd_custom_script_styles()
{
	if (get_option('pd_custom_style') != '') {
		wp_add_inline_style('qcpnd-custom-css', get_option('pd_custom_style'));
	}

	$customjs = get_option('pd_custom_js');
	if (trim($customjs) != '') {
		wp_add_inline_script('qcpnd-custom-script', trim($customjs));
	}
}
add_action('wp_footer', 'qcpnd_custom_script_styles');