<?php
/**
 * Integration Tests for HVAC Trainer Dashboard Display
 *
 * @package    HVAC Community Events
 * @subpackage Tests
 */

/**
 * Class Test_HVAC_Dashboard_Display
 *
 * Tests the display and basic functionality of the Trainer Dashboard template.
 */
class Test_HVAC_Dashboard_Display extends WP_UnitTestCase {

	protected static $trainer_user_id;
	protected static $subscriber_user_id;
	protected static $dashboard_page_id;
	protected static $event_ids = [];

	public static function wpSetUpBeforeClass(): void {
		// Create users
		self::$trainer_user_id = self::factory()->user->create( array( 'role' => 'hvac_trainer' ) );
		self::$subscriber_user_id = self::factory()->user->create( array( 'role' => 'subscriber' ) );

		// Create the dashboard page (assuming activation hook might not run in tests)
		self::$dashboard_page_id = self::factory()->post->create( array(
			'post_type' => 'page',
			'post_title' => 'Trainer Dashboard',
			'post_name' => 'hvac-dashboard', // Use the slug defined in activation hook
			'post_status' => 'publish',
		) );

		// Create test events assigned to the trainer
		$now = time();
		$one_day = DAY_IN_SECONDS;

		// Published Past
		$event1_id = self::factory()->post->create( array(
			'post_type'   => Tribe__Events__Main::POSTTYPE,
			'post_title'  => 'Past Published Event',
			'post_status' => 'publish',
			'meta_input'  => array(
				'_EventStartDate'      => date( 'Y-m-d H:i:s', $now - ( 7 * $one_day ) ),
				'_EventEndDate'        => date( 'Y-m-d H:i:s', $now - ( 7 * $one_day ) + HOUR_IN_SECONDS ),
				'_EventOrganizerID'    => self::$trainer_user_id,
			),
		) );
		update_post_meta( $event1_id, '_EventOrganizerID', self::$trainer_user_id );
		self::$event_ids[] = $event1_id;

		// Published Future
		$event2_id = self::factory()->post->create( array(
			'post_type'   => Tribe__Events__Main::POSTTYPE,
			'post_title'  => 'Future Published Event',
			'post_status' => 'publish',
			'meta_input'  => array(
				'_EventStartDate'      => date( 'Y-m-d H:i:s', $now + ( 7 * $one_day ) ),
				'_EventEndDate'        => date( 'Y-m-d H:i:s', $now + ( 7 * $one_day ) + HOUR_IN_SECONDS ),
				'_EventOrganizerID'    => self::$trainer_user_id,
			),
		) );
		update_post_meta( $event2_id, '_EventOrganizerID', self::$trainer_user_id );
		self::$event_ids[] = $event2_id;

		// Draft Future
		$event3_id = self::factory()->post->create( array(
			'post_type'   => Tribe__Events__Main::POSTTYPE,
			'post_title'  => 'Future Draft Event',
			'post_status' => 'draft',
			'meta_input'  => array(
				'_EventStartDate'      => date( 'Y-m-d H:i:s', $now + ( 14 * $one_day ) ),
				'_EventEndDate'        => date( 'Y-m-d H:i:s', $now + ( 14 * $one_day ) + HOUR_IN_SECONDS ),
				'_EventOrganizerID'    => self::$trainer_user_id,
			),
		) );
		update_post_meta( $event3_id, '_EventOrganizerID', self::$trainer_user_id );
		self::$event_ids[] = $event3_id;
	}

	public static function tearDownAfterClass(): void {
		wp_delete_post( self::$dashboard_page_id, true );
		wp_delete_user( self::$trainer_user_id );
		wp_delete_user( self::$subscriber_user_id );
		foreach ( self::$event_ids as $event_id ) {
			wp_delete_post( $event_id, true );
		}
		self::$event_ids = [];
		parent::tearDownAfterClass();
	}

	/**
	 * Test dashboard access for logged-out users.
	 * Should redirect to login.
	 */
	public function test_dashboard_access_logged_out() {
	 $this->markTestSkipped('Redirect verification is unreliable in integration tests; covered by E2E.');
	 $this->go_to( get_permalink( self::$dashboard_page_id ) );
	 // Asserting redirects is difficult here. Rely on E2E tests.
	 // We can check that the queried object is not the dashboard page ID.
		$queried_object_id = get_queried_object_id();
		$this->assertNotEquals( self::$dashboard_page_id, $queried_object_id, 'Logged-out user should be redirected away from dashboard.' );
	}

	/**
	 * Test dashboard access for users with incorrect role (e.g., subscriber).
	 * Should redirect or show an error (currently redirects).
	 */
	public function test_dashboard_access_wrong_role() {
	 $this->markTestSkipped('Redirect verification is unreliable in integration tests; covered by E2E.');
	 wp_set_current_user( self::$subscriber_user_id );
	 $this->go_to( get_permalink( self::$dashboard_page_id ) );
	 // Asserting redirects is difficult here. Rely on E2E tests.
		// We can check that the queried object is not the dashboard page ID.
		$queried_object_id = get_queried_object_id();
		$this->assertNotEquals( self::$dashboard_page_id, $queried_object_id, 'User with wrong role should be redirected away from dashboard.' );
	}

	/**
	 * Test dashboard access for the correct role (hvac_trainer).
	 * Should display the dashboard content.
	 */
	public function test_dashboard_access_correct_role() {
		wp_set_current_user( self::$trainer_user_id );
		$this->go_to( get_permalink( self::$dashboard_page_id ) );

		// Check if the global $post object matches the dashboard page ID
		global $post;
		$this->assertInstanceOf( 'WP_Post', $post, 'Global $post object should be set.' );
		$this->assertEquals( self::$dashboard_page_id, $post->ID, 'Trainer should land on the dashboard page.' );
		// Check title as a basic content verification
		$this->assertEquals( 'Trainer Dashboard', $post->post_title, 'Dashboard page title should be correct.' );
	}
/**
 * Test statistics calculation accuracy for the dashboard.
 */
public function test_dashboard_statistics_calculation() {
	wp_set_current_user(self::$trainer_user_id);
	
	// Get dashboard statistics
	$stats = HVAC_Community_Events::get_trainer_statistics(self::$trainer_user_id);
	
	// Verify total events count
	$this->assertEquals(3, $stats['total_events'], 'Total events count should be 3');
	
	// Verify published events count
	$this->assertEquals(2, $stats['published_events'], 'Published events count should be 2');
	
	// Verify draft events count
	$this->assertEquals(1, $stats['draft_events'], 'Draft events count should be 1');
	
	// Verify upcoming events count
	$this->assertEquals(1, $stats['upcoming_events'], 'Upcoming published events count should be 1');
}

/**
 * Test event data retrieval and display formatting.
 */
public function test_event_data_retrieval_and_display() {
	wp_set_current_user(self::$trainer_user_id);
	
	// Get events list
	$events = HVAC_Community_Events::get_trainer_events(self::$trainer_user_id);
	
	// Verify events array structure
	$this->assertIsArray($events);
	$this->assertCount(3, $events);
	
	// Check first event data structure
	$first_event = reset($events);
	$this->assertArrayHasKey('title', $first_event);
	$this->assertArrayHasKey('status', $first_event);
	$this->assertArrayHasKey('start_date', $first_event);
	$this->assertArrayHasKey('attendees_count', $first_event);
}

/**
 * Test sorting functionality for event listings.
 */
public function test_event_sorting_functionality() {
	wp_set_current_user(self::$trainer_user_id);
	
	// Get events sorted by date (ascending)
	$events_asc = HVAC_Community_Events::get_trainer_events(
		self::$trainer_user_id,
		['orderby' => 'date', 'order' => 'ASC']
	);
	
	// Verify ascending order
	$first_event_asc = reset($events_asc);
	$this->assertEquals('Past Published Event', $first_event_asc['title']);
	
	// Get events sorted by date (descending)
	$events_desc = HVAC_Community_Events::get_trainer_events(
		self::$trainer_user_id,
		['orderby' => 'date', 'order' => 'DESC']
	);
	
	// Verify descending order
	$first_event_desc = reset($events_desc);
	$this->assertEquals('Future Draft Event', $first_event_desc['title']);
}

/**
 * Test if the events table displays the correct events for the 'all' filter.
 */
public function test_events_table_all_filter() {
	wp_set_current_user(self::$trainer_user_id);
	$this->go_to(get_permalink(self::$dashboard_page_id));
	
	ob_start();
	do_action('hvac_display_events_table', 'all');
	$output = ob_get_clean();
	
	// Verify all events are present in the output
	$this->assertStringContainsString('Past Published Event', $output);
	$this->assertStringContainsString('Future Published Event', $output);
	$this->assertStringContainsString('Future Draft Event', $output);
}


	/**
	 * Test if the events table displays the correct events for the 'publish' filter.
	 */
	public function test_events_table_publish_filter() {
		wp_set_current_user( self::$trainer_user_id );
		$url = add_query_arg( 'event_status', 'publish', get_permalink( self::$dashboard_page_id ) );
		$this->go_to( $url );

		// Placeholder assertion:
		$this->assertTrue( true, "Integration test for filtered table content needs implementation or E2E test." );
	}

	/**
	 * Test if the events table displays the correct events for the 'draft' filter.
	 */
	public function test_events_table_draft_filter() {
		wp_set_current_user( self::$trainer_user_id );
		$url = add_query_arg( 'event_status', 'draft', get_permalink( self::$dashboard_page_id ) );
		$this->go_to( $url );

		// Placeholder assertion:
		$this->assertTrue( true, "Integration test for filtered table content needs implementation or E2E test." );
	}

} // End class Test_HVAC_Dashboard_Display