<?php

// GET

if ( ! function_exists( 'wpj_get_post' ) ) {
	function wpj_get_post( $fields = '*', $where = '', $return = 'row', $order = '' ) {
		$args = [
			'table'  => 'posts',
			'fields' => $fields,
			'where'  => $where,
			'return' => $return
		];

		if ( $order ) {
			$args['order'] = $order;
		}

		return wpj_get_query_results( $args );
	}
}

if ( ! function_exists( 'wpj_get_post_meta' ) ) {
	function wpj_get_post_meta( $fields = '*', $where = '', $return = 'row' ) {
		$where['fields_not_strings']['p.ID'] = 'pm.post_id';

		$args = [
			'table'  => ['posts p', 'postmeta pm'],
			'fields' => $fields,
			'where'  => $where,
			'return' => $return
		];

		return wpj_get_query_results( $args );
	}
}

if ( ! function_exists( 'wpj_get_tags_by_post_type' ) ) {
	function wpj_get_tags_by_post_type( $post_type = '' ) {
		global $wpdb;

		if ( empty( $post_type ) ) {
			$post_type = get_post_type();
		}

		return $wpdb->get_results(
			$wpdb->prepare(
				"
				SELECT COUNT( DISTINCT tr.object_id )
					AS count, tt.taxonomy, tt.description, tt.term_taxonomy_id, t.name, t.slug, t.term_id
				FROM {$wpdb->posts} p
				INNER JOIN {$wpdb->term_relationships} tr
					ON p.ID = tr.object_id
				INNER JOIN {$wpdb->term_taxonomy} tt
					ON tt.term_taxonomy_id = tr.term_taxonomy_id
				INNER JOIN {$wpdb->terms} t
					ON t.term_id = tt.term_taxonomy_id
				WHERE p.post_type = %s
					AND tt.taxonomy = 'post_tag'
				GROUP BY tt.term_taxonomy_id
				ORDER BY count DESC
				",
				$post_type
			)
		);
	}
}

if ( ! function_exists( 'wpj_get_posts_count_by_post_type' ) ) {
	function wpj_get_posts_count_by_post_type( $post_type = '', $active = '' ) {
		global $wpdb;

		return $wpdb->get_var(
			"
			SELECT count(DISTINCT pm.post_id)
			FROM {$wpdb->postmeta} pm
			JOIN {$wpdb->posts} p ON (p.ID = pm.post_id)
			WHERE pm.meta_key = 'active'
			AND pm.meta_value = {$active}
			AND p.post_type = '{$post_type}'
			AND p.post_status IN ( 'publish', 'pending', 'draft' );
			"
		);
	}
}