<?php
/**
 * Integration tests for TEC CE error conditions
 *
 * @package Hvac_Community_Events
 */

/**
 * Class Event_Management_Integration_Test
 */
class Event_Management_Integration_Test extends WP_UnitTestCase {
    
    protected $plugin_slug = 'hvac-community-events/hvac-community-events.php';
    protected $trainer_role = 'hvac_trainer';
    
    /**
     * Set up test environment
     */
    public function set_up() {
        parent::set_up();
        
        // Ensure clean state
        if (is_plugin_active($this->plugin_slug)) {
            deactivate_plugins($this->plugin_slug);
        }
        
        // Activate plugin for testing
        activate_plugin($this->plugin_slug);
        
        // Clear any existing test data
        $_POST = [];
    }
    
    /**
     * Clean up after tests
     */
    public function tear_down() {
        $_POST = [];
        if (is_plugin_active($this->plugin_slug)) {
            deactivate_plugins($this->plugin_slug);
        }
        parent::tear_down();
    }
    
    /**
     * Test event creation with missing required fields
     */
    public function test_event_creation_missing_required_fields() {
        // Create test user with trainer role
        $user_id = $this->factory->user->create(['role' => $this->trainer_role]);
        wp_set_current_user($user_id);
        
        // Test missing title
        $event_data = [
            'post_content' => 'Test event description',
            'EventStartDate' => date('Y-m-d', strtotime('+1 week')),
            'EventEndDate' => date('Y-m-d', strtotime('+1 week'))
        ];
        
        $result = $this->create_test_event($event_data);
        $this->assertFalse($result['success']);
        $this->assertContains('title is required', $result['errors']);
    }
    
    /**
     * Test event creation with invalid dates
     */
    public function test_event_creation_invalid_dates() {
        $user_id = $this->factory->user->create(['role' => $this->trainer_role]);
        wp_set_current_user($user_id);
        
        $event_data = [
            'post_title' => 'Test Event',
            'post_content' => 'Description',
            'EventStartDate' => 'invalid-date',
            'EventEndDate' => '2025/13/45'
        ];
        
        $result = $this->create_test_event($event_data);
        $this->assertFalse($result['success']);
        $this->assertContains('invalid date format', $result['errors']);
    }
    
    /**
     * Test event creation with insufficient permissions
     */
    public function test_event_creation_insufficient_permissions() {
        // Create user with insufficient permissions
        $user_id = $this->factory->user->create(['role' => 'subscriber']);
        wp_set_current_user($user_id);
        
        $event_data = [
            'post_title' => 'Test Event',
            'post_content' => 'Description',
            'EventStartDate' => date('Y-m-d', strtotime('+1 week')),
            'EventEndDate' => date('Y-m-d', strtotime('+1 week'))
        ];
        
        $result = $this->create_test_event($event_data);
        $this->assertFalse($result['success']);
        $this->assertContains('insufficient permissions', $result['errors']);
    }

    /**
     * Test malformed shortcode parameters
     */
    public function test_malformed_shortcode_parameters() {
        $user_id = $this->factory->user->create(['role' => $this->trainer_role]);
        wp_set_current_user($user_id);
        
        $event_data = [
            'post_title' => 'Test Event',
            'post_content' => 'Description',
            'EventStartDate' => date('Y-m-d', strtotime('+1 week')),
            'EventEndDate' => date('Y-m-d', strtotime('+1 week')),
            'venue' => 'malformed-venue-data', // Should be an array
            'organizer' => 'invalid-organizer' // Should be an array
        ];
        
        $result = $this->create_test_event($event_data);
        $this->assertTrue($result['success'], 'Event should be created despite malformed venue/organizer data');
        
        // Verify venue and organizer data were not set
        $event_id = $result['event_id'];
        $venue_id = get_post_meta($event_id, '_EventVenueID', true);
        $organizer_id = get_post_meta($event_id, '_EventOrganizerID', true);
        
        $this->assertEmpty($venue_id, 'Venue should not be set with malformed data');
        $this->assertEmpty($organizer_id, 'Organizer should not be set with malformed data');
    }

    /**
     * Test concurrent event submissions
     */
    public function test_concurrent_event_submissions() {
        $user_id = $this->factory->user->create(['role' => $this->trainer_role]);
        wp_set_current_user($user_id);

        $base_event_data = [
            'post_title' => 'Concurrent Test Event',
            'post_content' => 'Description',
            'EventStartDate' => date('Y-m-d', strtotime('+1 week')),
            'EventEndDate' => date('Y-m-d', strtotime('+1 week'))
        ];

        // Simulate concurrent submissions
        $results = [];
        for ($i = 0; $i < 3; $i++) {
            $event_data = $base_event_data;
            $event_data['post_title'] .= " {$i}";
            $results[] = $this->create_test_event($event_data);
        }

        // Verify each submission was handled properly
        foreach ($results as $index => $result) {
            $this->assertTrue($result['success'], "Concurrent event {$index} should be created successfully");
            $event = get_post($result['event_id']);
            $this->assertEquals("Concurrent Test Event {$index}", $event->post_title);
        }
    }

    /**
     * Test event creation with boundary conditions
     */
    public function test_event_boundary_conditions() {
        $user_id = $this->factory->user->create(['role' => $this->trainer_role]);
        wp_set_current_user($user_id);

        // Test extremely long title
        $long_title = str_repeat('a', 200);
        $event_data = [
            'post_title' => $long_title,
            'post_content' => 'Description',
            'EventStartDate' => date('Y-m-d', strtotime('+1 week')),
            'EventEndDate' => date('Y-m-d', strtotime('+1 week'))
        ];
        
        $result = $this->create_test_event($event_data);
        $this->assertTrue($result['success'], 'Event should be created with long title');
        $this->assertLessThanOrEqual(190, strlen(get_post($result['event_id'])->post_title), 'Title should be truncated');

        // Test past dates
        $event_data = [
            'post_title' => 'Past Event Test',
            'post_content' => 'Description',
            'EventStartDate' => date('Y-m-d', strtotime('-1 week')),
            'EventEndDate' => date('Y-m-d', strtotime('-1 week'))
        ];
        
        $result = $this->create_test_event($event_data);
        $this->assertFalse($result['success'], 'Event should not be created with past dates');
        $this->assertContains('event dates must be in the future', $result['errors']);
    }
    
    /**
     * Helper function to create test events
     */
    private function create_test_event($event_data) {
        try {
            $event_id = tribe_community_events()->insertEvent($event_data, true);
            
            if (is_wp_error($event_id)) {
                return [
                    'success' => false,
                    'errors' => $event_id->get_error_messages()
                ];
            }
            
            return [
                'success' => true,
                'event_id' => $event_id
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'errors' => [$e->getMessage()]
            ];
        }
    }
}