<?php

class test_meta_key_not_exists_query extends WP_UnitTestCase {

	function test_post() {
		$post_ids = $this->factory()->post->create_many( 7 );

		// Give first post nothing.

		// Give second post 1.
		add_post_meta( $post_ids[1], 'test', 1 );

		// Give third post 0.
		add_post_meta( $post_ids[2], 'test', 0 );

		// Give fourth post 200.
		add_post_meta( $post_ids[3], 'test', 200 );

		// Give fifth post 30.
		add_post_meta( $post_ids[4], 'test', 30 );

		// Give sixth post -5.
		add_post_meta( $post_ids[5], 'test', -5 );

		// Give the seventh post nothing.

		$query = new WP_Query(
			array(
				'fields' => 'ids',
				'orderby' => array( 'meta_value_num' => 'DESC', 'date' => 'DESC', 'ID' => 'ASC' ),
				'meta_query' => array(
					array(
						'key' => 'test',
						'default' => 0,
						'compare' => 'NONE',
					),
				),
			)
		);

		$this->assertSame(
			array(
				$post_ids[3], // 200
				$post_ids[4], // 30
				$post_ids[1], // 1
				$post_ids[0], // empty
				$post_ids[2], // 0
				$post_ids[6], // empty
				$post_ids[5], // -5
			)
			, $query->get_posts()
		);
	}

	function test_post_2() {
		$post_ids = $this->factory()->post->create_many( 7 );

		// Give first post nothing.
		add_post_meta( $post_ids[0], 'other', 'a' );

		// Give second post 1.
		add_post_meta( $post_ids[1], 'test', 1 );
		add_post_meta( $post_ids[1], 'other', 'b' );

		// Give third post 0.
		add_post_meta( $post_ids[2], 'test', 0 );
		add_post_meta( $post_ids[2], 'other', 'a' );

		// Give fourth post 200.
		add_post_meta( $post_ids[3], 'test', 200 );
		add_post_meta( $post_ids[3], 'other', 'a' );

		// Give fifth post 30.
		add_post_meta( $post_ids[4], 'test', 30 );

		// Give sixth post -5.
		add_post_meta( $post_ids[5], 'test', -5 );
		add_post_meta( $post_ids[5], 'other', 'a' );

		// Give the seventh post nothing.

		$query = new WP_Query(
			array(
				'fields' => 'ids',
				'orderby' => array( 'meta_value_num' => 'DESC', 'date' => 'DESC' ),
				'meta_query' => array(
					array(
						'key' => 'test',
						'default' => 0,
						'compare' => 'NONE',
					),
					array(
						'key' => 'other',
						'value' => 'a',
					),
				),
			)
		);

		$this->assertSame(
			array(
				$post_ids[3], // 200
//				$post_ids[4], // 30 (empty)
//				$post_ids[1], // 1 (b)
				$post_ids[0], // empty
				$post_ids[2], // 0
//				$post_ids[6], // empty (empty)
				$post_ids[5], // -5
			)
			, $query->get_posts()
		);
	}
}
