<?php
// global $dragblock_queries;
// global $dragblock_current_query_list_id;
// global $dragblock_current_query_list_item_id;
// $dragblock_queries = null;
// $dragblock_current_query_list_id = null;
// $dragblock_current_query_list_item_id = null;

/**
 * 
 */
function dragblock_get_current_list_query_id()
{
	global $dragblock_queries;
	global $dragblock_current_query_list_id;
	global $dragblock_current_query_list_item_id;
	// var_dump($dragblock_current_query_list_id, $dragblock_queries[$dragblock_current_query_list_id], $dragblock_current_query_list_item_id);

	if (null === $dragblock_current_query_list_item_id) {
		$dragblock_current_query_list_item_id = 0;
	}

	$item_id = null;

	if (
		null !== $dragblock_current_query_list_id &&
		!empty($dragblock_queries) &&
		!empty($dragblock_queries[$dragblock_current_query_list_id]) &&
		!empty($dragblock_queries[$dragblock_current_query_list_id][$dragblock_current_query_list_item_id])
	) {
		$item_id = $dragblock_queries[$dragblock_current_query_list_id][$dragblock_current_query_list_item_id];
	}

	return $item_id;
}



/**
 * 
 */
add_shortcode('dragblock.post.snippet', 'dragblock_shortcode_post_snippet');
function dragblock_shortcode_post_snippet($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}

	// Get the post excerpt if it exists, or the first paragraph of the post content
	$snippet = '';
	$def_len = '125';

	$len = !empty($attrs['len']) ? sanitize_text_field($attrs['len']) : $def_len;
	if (empty($len) || !is_numeric($len)) {
		$len = $def_len;
	}
	$len = (int) $len;

	if (has_excerpt($post_id)) {
		$snippet = get_the_excerpt($post_id);
	} else {
		$snippet = get_the_content(null, false, $post_id);
	}
	if (strlen($snippet) > $len) {
		$word_count = count(explode(' ', $snippet));
		$word_len = strlen($snippet)  / $word_count;
		$max_word_count = (int) ($len / $word_len);

		$snippet = wp_trim_words($snippet, $max_word_count, '...');
	}
	// var_dump($len, strlen($snippet));
	// die();
	return $snippet;
}


/**
 * 
 */
add_shortcode('dragblock.post.content', 'dragblock_shortcode_post_content');
function dragblock_shortcode_post_content($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}

	return get_the_content(null, false, $post_id);;
}


add_shortcode('dragblock.post.title', 'dragblock_shortcode_post_title');
function dragblock_shortcode_post_title($attrs, $post_id = null)
{

	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}
	return get_the_title($post_id);
}

add_shortcode('dragblock.post.url', 'dragblock_shortcode_post_url');
function dragblock_shortcode_post_url($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return 'javascript:void(0)';
	}
	return get_the_permalink($post_id);
}

add_shortcode('dragblock.post.comment.number', 'dragblock_shortcode_post_comment_number');
function dragblock_shortcode_post_comment_number($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}

	return get_comments_number($post_id);
}

add_shortcode('dragblock.post.view.count', 'dragblock_shortcode_post_view_count');
function dragblock_shortcode_post_view_count($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}

	return (int) get_post_meta($post_id, DRAGBLOCK_POST_VIEWS_KEY, true);
}

// add_shortcode('dragblock.post.meta', 'dragblock_shortcode_post_meta');
// function dragblock_shortcode_post_meta($attrs, $post_id = null)
// {
// 	if (!$post_id) {
// 		$post_id = dragblock_get_current_list_query_id();
// 	}
// 	if (!$post_id) {
// 		return '';
// 	}
// 	if (!$attrs || empty($attrs['key'])) {
// 		return '';
// 	}
// 	$key = sanitize_text_field($attrs['key']);

// 	return get_post_meta($post_id, $key, true);
// }


add_shortcode('dragblock.post.image.src', 'dragblock_shortcode_post_image_src');
function dragblock_shortcode_post_image_src($attrs, $post_id = null)
{
	// $blank_src = ($post_id === 0 || !!$post_id ? DRAGBLOCK_IMAGES_URL . 'demos/blank.png' : 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=');
	$blank_src = '';
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		// when loaded all post, leave this space empty (not show anything)
		return $blank_src;
	}


	// Step 1: Check if post has a featured image
	if (has_post_thumbnail($post_id)) {
		if (isset($attrs['size'])) {
			return get_the_post_thumbnail_url($post_id, $attrs['size']);
		}

		// select the smallest image in file size
		$image_id = get_post_thumbnail_id($post_id);
		$image_meta = wp_get_attachment_metadata($image_id);
		if (isset($image_meta['file']) && isset($image_meta['filesize'])) {
			$smallest_file_name = '';
			$smallest_file_size = $image_meta['filesize'];
			
			if (!empty($image_meta['sources'])) {
				foreach ($image_meta['sources'] as $source) {
					if (empty($source['file']) || empty($source['filesize']) || $source['filesize'] > $smallest_file_size) {
						continue;
					}
					$smallest_file_name = $source['file'];
					$smallest_file_size = $source['filesize'];
				}
			}
			if (empty($smallest_file_name)) {
				return get_the_post_thumbnail_url($post_id, 'full');
			}
			
			$upload_dir = wp_get_upload_dir();
			$original_file = $image_meta['file']; // e.g., "2025/01/myra-jpg.jpg"
			$file_dir = pathinfo($original_file, PATHINFO_DIRNAME); // "2025/01"			
			if ($file_dir === '.') { // if there is no directory in filename, you will get '.'
				$file_dir = ''; // Avoid incorrect paths
			} else {
				$file_dir .= '/';
			}
			$smallest_image_src = trailingslashit($upload_dir['baseurl']) . $file_dir . $smallest_file_name;
			return $smallest_image_src;
		}

		return get_the_post_thumbnail_url($post_id, 'full');

		// $image_url = get_the_post_thumbnail_url($post_id, $size);
		// return $image_url;
	}

	// Step 2: Check if post has an image in the content
	$content = get_post_field('post_content', $post_id);
	if ($content) {
		$doc = new DOMDocument();
		@$doc->loadHTML($content);
		$img_tags = $doc->getElementsByTagName('img');
		if (count($img_tags) > 0) {

			$image_url = $img_tags[0]->getAttribute('src');

			return $image_url;
		}


		// Step 3: Check if post has any embedded video
		$pattern = '/<iframe.*?src="(https?:\/\/www\.youtube\.com\/embed\/([\w-]+))".*?><\/iframe>/i';
		preg_match($pattern, $content, $matches);
		if (count($matches) > 0) {
			$video_id = $matches[2];
			$image_url = 'https://img.youtube.com/vi/' . $video_id . '/hqdefault.jpg';

			return $image_url;
		}
	}



	// Step 4: Return placeholder image
	// No thumbnail found, return default placeholder image
	return $blank_src;

	// $images_dir = array(
	//     'AI', 'cypto', 'cuisine', 'decor', 'travel'
	// );
	// // $images = glob($images_dir . '*.jpg'); // assuming images are in jpg format
	// $images = array();
	// foreach ($images_dir as $dir) {
	//     for ($i = 1; $i <= 10; $i++) {
	//         array_push($images, $dir . '/' . substr('00' . $i, 0, 3));
	//     }
	// }

	// $rand_index = array_rand($images);
	// $image_url = plugins_url('assets/images/demo/' . $images[$rand_index], __FILE__);

	// return $image_url;
}


/**
 * For testing purposes
 */
// add_action('after_setup_theme', 'dragblock_custom_image_sizes');
// function dragblock_custom_image_sizes()
// {
// 	add_image_size('portrait-768', 500, 768, true); // (hard crop)
// 	add_image_size('portrait-450', 300, 450, true); // (hard crop)
// 	$image_id = 4946;
// 	$image_meta = wp_get_attachment_metadata($image_id);
// 	$upload_dir = wp_get_upload_dir();

// 	// Get the directory structure (e.g., "2025/01")
// 	$file_dir = pathinfo($image_meta['file'], PATHINFO_DIRNAME);

// 	// Collect all image sizes and URLs
// 	foreach ($image_meta['sizes'] as $size => $data) {
// 		$image_url = trailingslashit($upload_dir['baseurl']) . $file_dir . '/' . $data['file'];
// 		// var_dump($size, $image_url);
// 	}
// }


/**
 * Force adding custom image sizes 
 * if the image sizes are not satisfying the wordpress image ratio
 * We keep this code just to guide developers, instead of adding
 * to our plugins that can lead to unexpected srcsets
 */
// add_filter('wp_calculate_image_srcset', 'dragblock_wp_calculate_image_srcset', 10, 5);
// function dragblock_wp_calculate_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id)
// {

// 	if (!$sources || !$image_meta || !isset($image_meta['sizes'])) {
// 		return $sources;
// 	}

// 	$upload_dir = wp_get_upload_dir();
// 	$file_dir = pathinfo($image_meta['file'], PATHINFO_DIRNAME);

// 	foreach ($image_meta['sizes'] as $size => $data) {
// 		if (!isset($data['file']) || isset($sources[$data['width']])) {
// 			continue; // Skip if already included
// 		}

// 		// Construct the full image URL
// 		$image_url = trailingslashit($upload_dir['baseurl']) . $file_dir . '/' . $data['file'];

// 		// Add the missing size manually
// 		$sources[$data['width']] = [
// 			'url' => $image_url,
// 			'descriptor' => 'w',
// 			'value' => $data['width'],
// 		];
// 	}
// 	return $sources;
// }

add_shortcode('dragblock.post.image.srcset', 'dragblock_shortcode_post_image_srcset');
function dragblock_shortcode_post_image_srcset($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	// Step 1: Check if post has a featured image
	if (!$post_id || !has_post_thumbnail($post_id)) {
		return '';
	}

	$image_id = get_post_thumbnail_id($post_id);

	$image_srcset = wp_get_attachment_image_srcset($image_id);
	return $image_srcset;
}

add_shortcode('dragblock.post.image.caption', 'dragblock_shortcode_post_image_caption');
function dragblock_shortcode_post_image_caption($attrs, $post_id = null) {
    if (!$post_id) {
        $post_id = dragblock_get_current_list_query_id();
    }

    // Step 1: Check if post has a featured image
    if (!$post_id || !has_post_thumbnail($post_id)) {
        return '';
    }

    $image_id = get_post_thumbnail_id($post_id);

    // Step 2: Retrieve caption from attachment metadata
    $caption = wp_get_attachment_caption($image_id);

    return $caption ? esc_html($caption) : "";
}

add_shortcode('dragblock.post.image.alt', 'dragblock_shortcode_post_image_alt');
function dragblock_shortcode_post_image_alt($attrs, $post_id = null) {
    if (!$post_id) {
        $post_id = dragblock_get_current_list_query_id();
    }

    // Get the post thumbnail ID
    $image_id = get_post_thumbnail_id($post_id);

    if (!$image_id) {
        return '';
    }

    // Retrieve the Alt text
    $alt_text = get_post_meta($image_id, '_wp_attachment_image_alt', true);

    return $alt_text ? esc_html($alt_text) : '';
}

add_shortcode('dragblock.post.image.desc', 'dragblock_shortcode_post_image_desc');
function dragblock_shortcode_post_image_desc($attrs, $post_id = null) {
    if (!$post_id) {
        $post_id = dragblock_get_current_list_query_id();
    }

    // Get the post thumbnail ID
    $image_id = get_post_thumbnail_id($post_id);

    if (!$image_id) {
        return '';
    }

    // Retrieve the Description (content of the attachment post)
    $description = get_post_field('post_content', $image_id);

    return $description ? esc_html($description) : '';
}


/**
 * No longer need too use because user need to input their own sizes
 */
add_shortcode('dragblock.post.image.sizes', 'dragblock_shortcode_post_image_sizes');
function dragblock_shortcode_post_image_sizes($attrs, $post_id)
{
	$size = isset($attrs['size']) ? sanitize_text_field($attrs['size']) : 'full';

	// takes up to 100% of the screen width
	if ('full' === $size) {
		return '';
	}

	// takes up to 75% of the screen width
	if ('large' === $size) {
		return '75vw';
		// return '(min-width: 0px) 80vw, 80vw';
	}
	// takes up to 50% of the screen width
	if ('medium' === $size) {
		return '50vw';
		// return '(min-width: 0px) 60vw, 60vw';
	}
	// takes up to 25% of the screen width
	if ('thumbnail' === $size) {
		return '25vw';
		// return '(min-width: 0px) 40vw, 40vw';
	}
}


add_shortcode('dragblock.post.date', 'dragblock_shortcode_post_date');
function dragblock_shortcode_post_date($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}


	// Get the post date
	$post_date = get_post_field('post_date', $post_id);

	// Get the date format from site settings
	$date_format = get_option('date_format');

	// Change the date format
	$formatted_date = date_i18n($date_format, strtotime($post_date));

	// Output the formatted date
	return $formatted_date;
}

add_shortcode('dragblock.post.author.url', 'dragblock_shortcode_post_author_url');
function dragblock_shortcode_post_author_url($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}
	// Get the author ID of the post
	$author_id = get_post_field('post_author', $post_id);

	// Get the author link
	$author_url = get_author_posts_url($author_id);

	// Output the author link
	return esc_url_raw($author_url);
}

add_shortcode('dragblock.post.author.name', 'dragblock_shortcode_post_author_name');
function dragblock_shortcode_post_author_name($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}
	// Get the author ID of the post
	$author_id = get_post_field('post_author', $post_id);

	// Get the author name
	$author_name = get_the_author_meta('display_name', $author_id);

	// Output the author name
	return $author_name;
}

add_shortcode('dragblock.post.author.avatar.src', 'dragblock_shortcode_post_author_avatar_src');
function dragblock_shortcode_post_author_avatar_src($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}
	// Get the author ID of the post
	$author_id = get_post_field('post_author', $post_id);

	// Get the author avatar source
	$avatar_src = get_avatar_url($author_id, array(
		'scheme' => 'https'
	));

	// Output the author avatar
	return esc_url_raw($avatar_src);
}

add_shortcode('dragblock.post.author.bio', 'dragblock_shortcode_post_author_bio');
function dragblock_shortcode_post_author_bio($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}

	if (!$post_id) {
		return '';
	}

	// Get the author ID of the post
	$author_id = get_post_field('post_author', $post_id);

	// Get the author bio
	$author_bio = get_the_author_meta('description', $author_id);

	// Output the author bio
	return $author_bio;
}



add_shortcode('dragblock.post.cat.name', 'dragblock_shortcode_post_cat_name');
function dragblock_shortcode_post_cat_name($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}


	$categories = get_the_category($post_id);
	$first_cat_name = '';

	if (!empty($categories)) {
		// @var $category WP_Term        
		foreach ($categories as $category) {

			if (0 === $category->category_parent) {
				return $category->name;
			}

			if (empty($first_cat_name)) {
				$first_cat_name = $category->name;
			}
		}
	}

	return $first_cat_name; // Return null if no parent category is found
}
add_shortcode('dragblock.post.cat.url', 'dragblock_shortcode_post_cat_url');
function dragblock_shortcode_post_cat_url($attrs, $post_id)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}


	$categories = get_the_category($post_id);
	$first_cat_url = '';

	if (!empty($categories)) {
		// @var $category WP_Term 
		foreach ($categories as $category) {
			if (0 === $category->category_parent) {
				return esc_url_raw(get_category_link($category->term_id));
			}
			if (empty($first_cat_url)) {
				$first_cat_url = esc_url_raw(get_category_link($category->term_id));
			}
		}
	}

	return $first_cat_url ? $first_cat_url : '#empty_cat_id'; // Return null if no parent category is found
}


add_shortcode('dragblock.post.cat.id', 'dragblock_shortcode_post_cat_id');
function dragblock_shortcode_post_cat_id($attrs, $post_id = null)
{
	if (!$post_id) {
		$post_id = dragblock_get_current_list_query_id();
	}
	if (!$post_id) {
		return '';
	}

	$categories = get_the_category($post_id);
	if (empty($categories) || is_wp_error($categories)) {
		$post_type = get_post_type($post_id);
		if (!$post_type || 'post' === $post_type) {
			return -1;
		}

		$categories = get_the_terms($post_id, $post_type . '-category');
		if (empty($categories) || is_wp_error($categories)) {
			$categories = get_the_terms($post_id, $post_type . '_category');
			if (empty($categories) || is_wp_error($categories)) {
				return -1;
			}
		}
	}

	// if (!empty($categories)) {
	// @var $category WP_Term 
	foreach ($categories as $category) {
		// return the first top level category at default
		if (0 === $category->category_parent || 0 === $category->parent) {
			return $category->term_id;
		}
	}
	// }

	return -1;
}

// add_shortcode('dragblock.query', 'dragblock_shortcode_query');
// function dragblock_shortcode_query($attrs)
// {
//     global $dragblock_queries;
//     global $dragblock_current_query_list_id;
//     global $dragblock_current_query_list_item_id;


//     if (empty($dragblock_queries)) {
//         global $wp_query;
//         $dragblock_current_query_list_id = 'default';

//         $dragblock_queries[$dragblock_current_query_list_id] = array();
//         foreach ($wp_query->posts as $post) {
//             array_push($dragblock_queries[$dragblock_current_query_list_id], $post->ID);
//         }
//     }
//     $slug = $attrs['the_query_slug'];
//     $id = $attrs['the_query_id'];
//     unset($attrs['the_query_slug']);
//     unset($attrs['the_query_id']);

//     // listing queries
//     if (in_array($slug, array('WP_Query'))) {
//         $dragblock_current_query_list_id = $id;
//         $args = array(
//             'fields' => 'ids',
//         );

//         foreach ($attrs as $key => $val) {
//             // array attributes
//             if (strpos($key, '__') !== false) {
//                 $args[$key] = explode(',', $val);
//                 continue;
//             }
//             $args[$key] = $val;
//         }

//         if ($slug === 'WP_Query') {
//             $dragblock_queries[$dragblock_current_query_list_id] = new WP_Query($args);
//             $dragblock_queries[$dragblock_current_query_list_id] = $dragblock_queries[$dragblock_current_query_list_id]->posts;
//         }
//     }

//     // other queries
//     if ($slug === 'parse_item') {
//         if (!empty($attrs['query_id'])) {
//             $dragblock_current_query_list_id = $attrs['query_id'];
//         }
//         if (!empty($attrs['item_index'])) {
//             $dragblock_current_query_list_item_id = intval($attrs['item_index']);
//         } else {
//             if ($dragblock_current_query_list_item_id === null) {
//                 $dragblock_current_query_list_item_id = 0;
//             } else {
//                 $dragblock_current_query_list_item_id++;
//             }
//         }
//     }

//     return '';
// }
