<?php
/**
 * Event Submission Flow Integration Test
 *
 * @package    HVAC_Community_Events
 * @subpackage Tests\Integration
 */

/**
 * Test the complete event submission flow
 */
class Test_Event_Submission_Flow extends WP_UnitTestCase {

	/**
	 * Test user
	 *
	 * @var int
	 */
	private $test_user_id;

	/**
	 * Set up before each test
	 */
	public function setUp(): void {
		parent::setUp();
		
		// Create test user with trainer role
		$this->test_user_id = $this->factory->user->create( array(
			'role' => 'contributor',
			'display_name' => 'Test Trainer',
		) );
		
		// Set current user
		wp_set_current_user( $this->test_user_id );
		
		// Enable debug logging
		add_filter( 'hvac_ce_debug_mode', '__return_true' );
		HVAC_Logger::init();
	}

	/**
	 * Test complete event submission flow
	 */
	public function test_event_submission_flow() {
		// Step 1: Initialize form
		$form_builder = new HVAC_Form_Builder();
		$form_builder->init( array(
			'id' => 'event-submission-form',
			'nonce_action' => 'submit_event',
		) );
		
		// Step 2: Add form fields
		$form_builder->add_field( 'text', array(
			'name' => 'event_title',
			'label' => 'Event Title',
			'required' => true,
		) );
		
		$form_builder->add_field( 'textarea', array(
			'name' => 'event_description',
			'label' => 'Event Description',
			'required' => true,
		) );
		
		$form_builder->add_field( 'date', array(
			'name' => 'event_start_date',
			'label' => 'Start Date',
			'required' => true,
		) );
		
		$form_builder->add_field( 'time', array(
			'name' => 'event_start_time',
			'label' => 'Start Time',
			'required' => true,
		) );
		
		// Step 3: Simulate form data
		$form_data = array(
			'event_title' => 'Test HVAC Training Event',
			'event_description' => 'This is a test event description',
			'event_start_date' => date( 'Y-m-d', strtotime( '+1 week' ) ),
			'event_start_time' => '14:00',
			'_wpnonce' => wp_create_nonce( 'submit_event' ),
		);
		
		$form_builder->set_data( $form_data );
		
		// Step 4: Validate form
		$is_valid = $form_builder->validate();
		$this->assertTrue( $is_valid );
		
		// Step 5: Process submission
		if ( $is_valid ) {
			// Simulate event creation
			$event_data = array(
				'post_title' => $form_data['event_title'],
				'post_content' => $form_data['event_description'],
				'post_type' => 'tribe_events',
				'post_status' => 'draft', // Community events start as draft
				'post_author' => $this->test_user_id,
			);
			
			$event_id = wp_insert_post( $event_data );
			$this->assertNotWPError( $event_id );
			$this->assertGreaterThan( 0, $event_id );
			
			// Add event meta
			$start_datetime = $form_data['event_start_date'] . ' ' . $form_data['event_start_time'] . ':00';
			update_post_meta( $event_id, '_EventStartDate', $start_datetime );
			update_post_meta( $event_id, '_EventEndDate', date( 'Y-m-d H:i:s', strtotime( $start_datetime . ' +2 hours' ) ) );
			
			// Log the submission
			HVAC_Logger::info( 'Event submitted', 'Event Submission', array(
				'event_id' => $event_id,
				'user_id' => $this->test_user_id,
			) );
		}
		
		// Step 6: Verify event was created
		$event = get_post( $event_id );
		$this->assertNotNull( $event );
		$this->assertEquals( 'Test HVAC Training Event', $event->post_title );
		$this->assertEquals( 'draft', $event->post_status );
		$this->assertEquals( $this->test_user_id, $event->post_author );
		
		// Step 7: Check logs
		$logs = HVAC_Logger::get_logs();
		$this->assertNotEmpty( $logs );
		
		$submission_log = array_filter( $logs, function( $log ) {
			return $log['message'] === 'Event submitted';
		} );
		$this->assertCount( 1, $submission_log );
	}

	/**
	 * Test event submission with validation errors
	 */
	public function test_event_submission_with_errors() {
		$form_builder = new HVAC_Form_Builder();
		$form_builder->init( array(
			'id' => 'event-submission-form',
			'nonce_action' => 'submit_event',
		) );
		
		$form_builder->add_field( 'text', array(
			'name' => 'event_title',
			'label' => 'Event Title',
			'required' => true,
			'validation' => array(
				'min_length' => 5,
			),
		) );
		
		// Submit with invalid data
		$form_data = array(
			'event_title' => 'Test', // Too short
			'_wpnonce' => wp_create_nonce( 'submit_event' ),
		);
		
		$form_builder->set_data( $form_data );
		$is_valid = $form_builder->validate();
		
		$this->assertFalse( $is_valid );
		
		$errors = $form_builder->get_errors();
		$this->assertArrayHasKey( 'event_title', $errors );
		
		// Log validation error
		HVAC_Logger::warning( 'Event submission validation failed', 'Event Submission', array(
			'errors' => $errors,
			'user_id' => $this->test_user_id,
		) );
		
		// Check logs
		$logs = HVAC_Logger::get_logs( 'warning' );
		$this->assertNotEmpty( $logs );
	}

	/**
	 * Test unauthorized event submission
	 */
	public function test_unauthorized_submission() {
		// Log out current user
		wp_set_current_user( 0 );
		
		// Try to submit without being logged in
		$can_submit = current_user_can( 'publish_posts' );
		$this->assertFalse( $can_submit );
		
		// Log security warning
		HVAC_Logger::warning( 'Unauthorized event submission attempt', 'Security', array(
			'ip' => '127.0.0.1',
		) );
		
		// Check security logs
		$logs = HVAC_Logger::get_logs( 'warning' );
		$security_logs = array_filter( $logs, function( $log ) {
			return $log['context'] === 'Security';
		} );
		$this->assertNotEmpty( $security_logs );
	}

	/**
	 * Test event update flow
	 */
	public function test_event_update_flow() {
		// Create an event first
		$event_id = $this->factory->post->create( array(
			'post_title' => 'Original Event Title',
			'post_type' => 'tribe_events',
			'post_status' => 'draft',
			'post_author' => $this->test_user_id,
		) );
		
		// Verify user can edit their own event
		$can_edit = current_user_can( 'edit_post', $event_id );
		$this->assertTrue( $can_edit );
		
		// Update event
		$updated_data = array(
			'ID' => $event_id,
			'post_title' => 'Updated Event Title',
			'post_content' => 'Updated event description',
		);
		
		$result = wp_update_post( $updated_data );
		$this->assertEquals( $event_id, $result );
		
		// Verify update
		$updated_event = get_post( $event_id );
		$this->assertEquals( 'Updated Event Title', $updated_event->post_title );
		$this->assertEquals( 'Updated event description', $updated_event->post_content );
		
		// Log the update
		HVAC_Logger::info( 'Event updated', 'Event Update', array(
			'event_id' => $event_id,
			'user_id' => $this->test_user_id,
		) );
	}

	/**
	 * Test event deletion flow
	 */
	public function test_event_deletion_flow() {
		// Create an event
		$event_id = $this->factory->post->create( array(
			'post_title' => 'Event to Delete',
			'post_type' => 'tribe_events',
			'post_status' => 'draft',
			'post_author' => $this->test_user_id,
		) );
		
		// Verify user can delete their own event
		$can_delete = current_user_can( 'delete_post', $event_id );
		$this->assertTrue( $can_delete );
		
		// Delete event (move to trash)
		$result = wp_trash_post( $event_id );
		$this->assertEquals( $event_id, $result );
		
		// Verify deletion
		$deleted_event = get_post( $event_id );
		$this->assertEquals( 'trash', $deleted_event->post_status );
		
		// Log the deletion
		HVAC_Logger::info( 'Event deleted', 'Event Deletion', array(
			'event_id' => $event_id,
			'user_id' => $this->test_user_id,
		) );
	}

	/**
	 * Test rate limiting for event submissions
	 */
	public function test_submission_rate_limiting() {
		$user_id = $this->test_user_id;
		$action = 'submit_event';
		
		// Test rate limiting (3 submissions per hour)
		for ( $i = 1; $i <= 4; $i++ ) {
			$can_submit = HVAC_Security::check_rate_limit( $user_id, $action, 3, 3600 );
			
			if ( $i <= 3 ) {
				$this->assertTrue( $can_submit, "Submission $i should be allowed" );
			} else {
				$this->assertFalse( $can_submit, "Submission $i should be blocked" );
			}
		}
		
		// Check logs for rate limit warning
		$logs = HVAC_Logger::get_logs( 'warning' );
		$rate_limit_logs = array_filter( $logs, function( $log ) {
			return strpos( $log['message'], 'Rate limit exceeded' ) !== false;
		} );
		$this->assertNotEmpty( $rate_limit_logs );
	}
}