<?php
/**
 * HVAC Community Events - Email Attendees Template
 *
 * Template for the Email Attendees page.
 *
 * @package HVAC_Community_Events
 * @subpackage Templates
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Check if user is logged in
if ( ! is_user_logged_in() ) {
    wp_redirect( site_url( '/community-login/' ) );
    exit;
}

// Get the event ID from the URL
$event_id = isset( $_GET['event_id'] ) ? intval( $_GET['event_id'] ) : 0;

// Load the email attendees data class
require_once HVAC_PLUGIN_DIR . 'includes/community/class-email-attendees-data.php';
$email_data = new HVAC_Email_Attendees_Data( $event_id );

// Check if event is valid and user has permission
if ( ! $email_data->is_valid_event() ) {
    wp_redirect( site_url( '/hvac-dashboard/' ) );
    exit;
}

if ( ! $email_data->user_can_email_attendees() ) {
    wp_die( __( 'You do not have permission to email attendees for this event.', 'hvac-community-events' ) );
}

// Get event details and attendees
$event_details = $email_data->get_event_details();
$attendees = $email_data->get_attendees();
$ticket_types = $email_data->get_ticket_types();

// Handle form submission
$email_sent = false;
$email_error = '';
$email_success = '';

if ( isset( $_POST['hvac_send_email'] ) && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( $_POST['_wpnonce'], 'hvac_email_attendees_' . $event_id ) ) {
    
    $subject = isset( $_POST['email_subject'] ) ? sanitize_text_field( $_POST['email_subject'] ) : '';
    $message = isset( $_POST['email_message'] ) ? wp_kses_post( $_POST['email_message'] ) : '';
    $cc = isset( $_POST['email_cc'] ) ? sanitize_text_field( $_POST['email_cc'] ) : '';
    
    // Get selected recipients
    $recipients = array();
    if ( isset( $_POST['email_attendees'] ) && is_array( $_POST['email_attendees'] ) ) {
        $recipients = array_map( 'sanitize_text_field', $_POST['email_attendees'] );
    }
    
    // Validate and send email
    if ( empty( $subject ) || empty( $message ) || empty( $recipients ) ) {
        $email_error = __( 'Please fill in all required fields (subject, message, and select at least one recipient).', 'hvac-community-events' );
    } else {
        $result = $email_data->send_email( $recipients, $subject, $message, $cc );
        
        if ( $result['success'] ) {
            $email_sent = true;
            $email_success = $result['message'];
        } else {
            $email_error = $result['message'];
        }
    }
}

// Get filtered attendees if a ticket type is selected
$selected_ticket_type = isset( $_GET['ticket_type'] ) ? sanitize_text_field( $_GET['ticket_type'] ) : '';
if ( ! empty( $selected_ticket_type ) ) {
    $attendees = $email_data->get_attendees_by_ticket_type( $selected_ticket_type );
}

// Get the site title for the page title
$site_title = get_bloginfo( 'name' );
?>

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo esc_html( $site_title ); ?> - <?php _e( 'Email Attendees', 'hvac-community-events' ); ?></title>
    <?php wp_head(); ?>
    <style>
        .hvac-email-attendees-wrapper {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .hvac-email-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .hvac-email-title h1 {
            margin: 0 0 10px 0;
        }
        .hvac-email-navigation {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .hvac-email-form {
            margin-top: 20px;
        }
        .hvac-email-info {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .hvac-email-form-row {
            margin-bottom: 15px;
        }
        .hvac-email-form-row label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
        }
        .hvac-email-form-row input[type="text"], 
        .hvac-email-form-row textarea {
            width: 100%;
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .hvac-email-recipients {
            margin-top: 20px;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
        }
        .hvac-email-filter {
            margin-bottom: 15px;
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        .hvac-attendee-list {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #eee;
            padding: 10px;
        }
        .hvac-attendee-item {
            margin-bottom: 10px;
            padding: 5px;
            background-color: #f9f9f9;
            border-radius: 3px;
        }
        .hvac-attendee-checkbox {
            margin-right: 10px;
        }
        .hvac-attendee-item a {
            color: #0073aa;
            text-decoration: none;
        }
        .hvac-attendee-item a:hover {
            text-decoration: underline;
        }
        .hvac-email-sent {
            background-color: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .hvac-email-error {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .hvac-count-badge {
            background-color: #007cba;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 0.8em;
            margin-left: 5px;
        }
        .hvac-select-all-container {
            margin-bottom: 10px;
        }
    </style>
</head>

<body <?php body_class(); ?>>
    <?php wp_body_open(); ?>

    <div class="hvac-email-attendees-wrapper">
        <div class="hvac-email-header">
            <div class="hvac-email-title">
                <h1><?php _e( 'Email Attendees', 'hvac-community-events' ); ?></h1>
                <h2><?php echo esc_html( $event_details['title'] ); ?></h2>
                <p>
                    <?php echo esc_html( $event_details['start_date'] ); ?> 
                    <?php echo esc_html( $event_details['start_time'] ); ?> - 
                    <?php 
                    if ( $event_details['start_date'] !== $event_details['end_date'] ) {
                        echo esc_html( $event_details['end_date'] ) . ' ';
                    }
                    echo esc_html( $event_details['end_time'] );
                    ?>
                </p>
            </div>
            
            <div class="hvac-email-navigation">
                <a href="<?php echo esc_url( site_url( '/event-summary/?event_id=' . $event_id ) ); ?>" class="ast-button ast-button-secondary">
                    <?php _e( 'View Event Summary', 'hvac-community-events' ); ?>
                </a>
                <a href="<?php echo esc_url( site_url( '/hvac-dashboard/' ) ); ?>" class="ast-button ast-button-secondary">
                    <?php _e( 'Return to Dashboard', 'hvac-community-events' ); ?>
                </a>
            </div>
        </div>
        
        <?php if ( $email_sent ) : ?>
            <div class="hvac-email-sent">
                <?php echo esc_html( $email_success ); ?>
            </div>
        <?php endif; ?>
        
        <?php if ( $email_error ) : ?>
            <div class="hvac-email-error">
                <?php echo esc_html( $email_error ); ?>
            </div>
        <?php endif; ?>
        
        <?php if ( empty( $attendees ) ) : ?>
            <div class="hvac-email-info">
                <?php _e( 'This event has no attendees registered yet.', 'hvac-community-events' ); ?>
            </div>
        <?php else : ?>
            <!-- Include Template Manager Widget -->
            <?php include HVAC_PLUGIN_DIR . 'templates/communication/template-manager-widget.php'; ?>
            
            <form method="post" class="hvac-email-form">
                <?php wp_nonce_field( 'hvac_email_attendees_' . $event_id ); ?>
                
                <div class="hvac-email-form-row">
                    <label for="email_subject"><?php _e( 'Subject:', 'hvac-community-events' ); ?> <span class="required">*</span></label>
                    <input type="text" name="email_subject" id="email_subject" required value="<?php echo isset( $_POST['email_subject'] ) ? esc_attr( $_POST['email_subject'] ) : ''; ?>">
                </div>
                
                <div class="hvac-email-form-row">
                    <label for="email_cc"><?php _e( 'CC:', 'hvac-community-events' ); ?></label>
                    <input type="text" name="email_cc" id="email_cc" value="<?php echo isset( $_POST['email_cc'] ) ? esc_attr( $_POST['email_cc'] ) : ''; ?>" placeholder="<?php _e( 'Separate multiple emails with commas', 'hvac-community-events' ); ?>">
                </div>
                
                <?php
                // Get sender information for display
                $current_user = wp_get_current_user();
                $sender_name = $current_user->display_name;
                $sender_email = $current_user->user_email;
                
                // Get trainer profile data if available
                if (in_array('hvac_trainer', $current_user->roles)) {
                    $business_name = get_user_meta($current_user->ID, 'business_name', true);
                    if (!empty($business_name)) {
                        $sender_name = $business_name;
                    }
                    
                    $contact_email = get_user_meta($current_user->ID, 'contact_email', true);
                    if (!empty($contact_email) && is_email($contact_email)) {
                        $sender_email = $contact_email;
                    }
                }
                ?>
                
                <div class="hvac-email-info" style="background-color: #e7f5ff; margin-bottom: 20px; padding: 15px; border-radius: 5px; border: 1px solid #a3c4e1;">
                    <p><?php _e( 'Email will be sent from:', 'hvac-community-events' ); ?> <strong><?php echo esc_html($sender_name); ?> &lt;<?php echo esc_html($sender_email); ?>&gt;</strong></p>
                    <p style="margin-bottom: 5px;"><small><?php _e('Having email issues? Try these steps:', 'hvac-community-events'); ?></small></p>
                    <ul style="margin-top: 0; font-size: 13px;">
                        <li><?php _e('Make sure your trainer profile has a valid email address', 'hvac-community-events'); ?></li>
                        <li><?php _e('Check that recipients have valid email addresses', 'hvac-community-events'); ?></li>
                        <li><?php _e('Use the "Debug Email System" button at the bottom right corner for more details', 'hvac-community-events'); ?></li>
                        <li><?php _e('Contact support if emails are still not being delivered', 'hvac-community-events'); ?></li>
                    </ul>
                </div>
                
                <div class="hvac-email-form-row">
                    <label for="email_message"><?php _e( 'Message:', 'hvac-community-events' ); ?> <span class="required">*</span></label>
                    <?php
                    // Use WordPress editor if available
                    if ( function_exists( 'wp_editor' ) ) {
                        $content = isset( $_POST['email_message'] ) ? wp_kses_post( $_POST['email_message'] ) : '';
                        $editor_settings = array(
                            'textarea_name' => 'email_message',
                            'textarea_rows' => 10,
                            'media_buttons' => false,
                            'teeny' => true,
                        );
                        wp_editor( $content, 'email_message', $editor_settings );
                    } else {
                        // Fallback to textarea
                        echo '<textarea name="email_message" id="email_message" rows="10" required>' . 
                            ( isset( $_POST['email_message'] ) ? esc_textarea( $_POST['email_message'] ) : '' ) . 
                            '</textarea>';
                    }
                    ?>
                </div>
                
                <div class="hvac-email-recipients">
                    <h3><?php _e( 'Recipients', 'hvac-community-events' ); ?> <span class="hvac-count-badge"><?php echo count( $attendees ); ?></span></h3>
                    
                    <?php if ( ! empty( $ticket_types ) && count( $ticket_types ) > 1 ) : ?>
                        <div class="hvac-email-filter">
                            <label for="ticket_type_filter"><?php _e( 'Filter by ticket type:', 'hvac-community-events' ); ?></label>
                            <select id="ticket_type_filter" onchange="window.location.href='<?php echo esc_url( add_query_arg( array( 'event_id' => $event_id ), site_url( '/email-attendees/' ) ) ); ?>&ticket_type=' + this.value">
                                <option value=""><?php _e( 'All Tickets', 'hvac-community-events' ); ?></option>
                                <?php foreach ( $ticket_types as $ticket_type ) : ?>
                                    <option value="<?php echo esc_attr( $ticket_type ); ?>" <?php selected( $selected_ticket_type, $ticket_type ); ?>>
                                        <?php echo esc_html( $ticket_type ); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>
                    
                    <div class="hvac-select-all-container">
                        <label>
                            <input type="checkbox" id="select_all_attendees" onclick="toggleAllAttendees(this)">
                            <?php _e( 'Select All', 'hvac-community-events' ); ?>
                        </label>
                    </div>
                    
                    <div class="hvac-attendee-list">
                        <?php foreach ( $attendees as $attendee ) : ?>
                            <div class="hvac-attendee-item">
                                <label>
                                    <input type="checkbox" class="hvac-attendee-checkbox" name="email_attendees[]" value="<?php echo esc_attr( $attendee['email'] ); ?>">
                                    <strong>
                                        <?php if ( ! empty( $attendee['attendee_id'] ) ) : ?>
                                            <a href="<?php echo esc_url( add_query_arg( 'attendee_id', $attendee['attendee_id'], home_url( '/attendee-profile/' ) ) ); ?>" target="_blank" title="View attendee profile">
                                                <?php echo esc_html( $attendee['name'] ); ?>
                                            </a>
                                        <?php else : ?>
                                            <?php echo esc_html( $attendee['name'] ); ?>
                                        <?php endif; ?>
                                    </strong>
                                    (<?php echo esc_html( $attendee['email'] ); ?>)
                                    <?php if ( ! empty( $attendee['ticket_name'] ) ) : ?>
                                        - <?php echo esc_html( $attendee['ticket_name'] ); ?>
                                    <?php endif; ?>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <div class="hvac-email-form-row" style="margin-top: 20px;">
                    <button type="submit" name="hvac_send_email" class="ast-button ast-button-primary">
                        <?php _e( 'Send Email', 'hvac-community-events' ); ?>
                    </button>
                </div>
            </form>
            
            <script>
                function toggleAllAttendees(checkbox) {
                    var attendeeCheckboxes = document.querySelectorAll('.hvac-attendee-checkbox');
                    for (var i = 0; i < attendeeCheckboxes.length; i++) {
                        attendeeCheckboxes[i].checked = checkbox.checked;
                    }
                }
            </script>
        <?php endif; ?>
    </div>

    <?php wp_footer(); ?>
</body>
</html>