<?php
/**
 * Integration tests for the Email Attendees functionality
 */

class Test_Email_Attendees_Integration extends WP_UnitTestCase {
    /**
     * @var int Test event ID
     */
    private $event_id;

    /**
     * @var int Test user ID
     */
    private $user_id;

    /**
     * @var WP_REST_Server
     */
    private $server;

    /**
     * Set up test data before each test
     */
    public function setUp(): void {
        parent::setUp();

        // Initialize REST API server
        global $wp_rest_server;
        $this->server = $wp_rest_server = new WP_REST_Server;
        do_action('rest_api_init');

        // Create a test user with trainer role
        $this->user_id = $this->factory->user->create(array(
            'role' => 'hvac_trainer',
            'user_login' => 'test_trainer',
            'user_pass' => 'password',
            'user_email' => 'trainer@example.com',
            'display_name' => 'Test Trainer',
        ));

        // Set current user for permission testing
        wp_set_current_user($this->user_id);

        // Make sure the classes exist
        require_once HVAC_CE_PLUGIN_DIR . 'includes/community/class-email-attendees-data.php';
        require_once HVAC_CE_PLUGIN_DIR . 'includes/community/class-event-summary-data.php';

        // Create a test event
        $event_data = array(
            'post_title'   => 'Test Event for Email Attendees Integration',
            'post_content' => 'Test event integration test content',
            'post_status'  => 'publish',
            'post_type'    => Tribe__Events__Main::POSTTYPE,
            'post_author'  => $this->user_id,
        );
        $this->event_id = wp_insert_post($event_data);

        // Set up mock attendees if needed using Event Tickets functions
        // This is more complex and would depend on the actual implementation
    }

    /**
     * Clean up test data after each test
     */
    public function tearDown(): void {
        // Delete test event
        wp_delete_post($this->event_id, true);

        // Delete test user
        wp_delete_user($this->user_id);

        parent::tearDown();
    }

    /**
     * Test that the email attendees shortcode exists and renders
     */
    public function test_email_attendees_shortcode_exists() {
        // Verify the shortcode is registered
        global $shortcode_tags;
        $this->assertArrayHasKey('hvac_email_attendees', $shortcode_tags);

        // Test shortcode output with no parameters
        $output = do_shortcode('[hvac_email_attendees]');
        $this->assertStringContainsString('Please log in to email event attendees', $output);
    }

    /**
     * Test the integration between Event Summary and Email Attendees
     */
    public function test_event_summary_links_to_email_attendees() {
        // Get event summary output
        ob_start();
        include HVAC_CE_PLUGIN_DIR . 'templates/event-summary/template-event-summary.php';
        $output = ob_get_clean();

        // Check that the email attendees link is included
        $expected_url = add_query_arg('event_id', $this->event_id, home_url('/email-attendees/'));
        $this->assertStringContainsString($expected_url, $output);
        $this->assertStringContainsString('Email Attendees', $output);
    }

    /**
     * Test that the email attendees template loads correctly
     */
    public function test_email_attendees_template_loads() {
        // Set up $_GET parameter
        $_GET['event_id'] = $this->event_id;

        // Capture template output
        ob_start();
        include HVAC_CE_PLUGIN_DIR . 'templates/email-attendees/template-email-attendees.php';
        $output = ob_get_clean();

        // Verify template elements
        $this->assertStringContainsString('Email Attendees', $output);
        $this->assertStringContainsString('Subject:', $output);
        $this->assertStringContainsString('CC:', $output);
        $this->assertStringContainsString('Message:', $output);
        $this->assertStringContainsString('Recipients', $output);
        $this->assertStringContainsString('Send Email', $output);

        // Unset $_GET parameter
        unset($_GET['event_id']);
    }

    /**
     * Test the authentication check for email attendees page
     */
    public function test_email_attendees_auth_check() {
        // Create an instance of the main plugin class
        $plugin = new HVAC_Community_Events();

        // Log out to test the redirect
        wp_set_current_user(0);

        // Mock WordPress is_page function
        global $wp_query;
        $wp_query->is_page = true;
        $wp_query->queried_object = (object) array('post_name' => 'email-attendees');

        // Capture redirect
        ob_start();
        $plugin->check_email_attendees_auth();
        $output = ob_get_clean();

        // Since we're not in a real page request, the function will try to redirect
        // but won't exit, so we don't expect any output
        $this->assertEmpty($output);

        // Reset current user
        wp_set_current_user($this->user_id);
    }

    /**
     * Test form submission handling
     */
    public function test_form_submission_handling() {
        // This test is more complex as it involves form submission
        // We would need to mock the $_POST data and possibly override wp_mail
        
        // Set up $_GET and $_POST data
        $_GET['event_id'] = $this->event_id;
        $_POST['hvac_send_email'] = 1;
        $_POST['email_subject'] = 'Integration Test Subject';
        $_POST['email_message'] = 'Integration test message content';
        $_POST['email_attendees'] = array('test@example.com');
        
        // Create nonce
        $_POST['_wpnonce'] = wp_create_nonce('hvac_email_attendees_' . $this->event_id);

        // Override wp_mail for testing
        add_filter('wp_mail', function($args) {
            // Capture email arguments for validation
            $this->assertEquals('Integration Test Subject', $args['subject']);
            $this->assertEquals('test@example.com', $args['to']);
            return false; // Prevent actual email sending
        });

        // Capture template output
        ob_start();
        include HVAC_CE_PLUGIN_DIR . 'templates/email-attendees/template-email-attendees.php';
        $output = ob_get_clean();

        // Verify success message appears in output
        $this->assertStringContainsString('Email successfully sent', $output);

        // Clean up
        unset($_GET['event_id']);
        unset($_POST['hvac_send_email']);
        unset($_POST['email_subject']);
        unset($_POST['email_message']);
        unset($_POST['email_attendees']);
        unset($_POST['_wpnonce']);
        remove_all_filters('wp_mail');
    }
}