<?php
/**
 * Template Name: Custom Event Edit
 * Description: Server-side populated event edit form
 */

// Security check
if (!defined('ABSPATH')) {
    exit;
}

// Define constant for page identification
define('HVAC_IN_PAGE_TEMPLATE', true);

// Check if user is logged in first
if (!is_user_logged_in()) {
    // Redirect to training login page
    wp_safe_redirect(home_url('/training-login/?redirect=' . urlencode($_SERVER['REQUEST_URI'])));
    exit;
}

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

// Initialize form handler
$form_handler = HVAC_Event_Manager::instance();

// Check permissions (after login check)
if (!$form_handler->canUserEditEvent($event_id)) {
    wp_die('You do not have permission to edit this event.');
}

// Initialize event data
$event_data = [];
if ($event_id > 0) {
    try {
        // Use generator to efficiently load data
        foreach ($form_handler->getEventData($event_id) as $key => $value) {
            $event_data[$key] = $value;
        }
    } catch (Exception $e) {
        wp_die('Error loading event: ' . esc_html($e->getMessage()));
    }
}

// Set defaults for new events
$defaults = [
    'title' => '',
    'content' => '',
    'excerpt' => '',
    'status' => 'draft',
    '_EventStartDate' => date('Y-m-d'),
    '_EventEndDate' => date('Y-m-d'),
    '_EventAllDay' => '0',
    '_EventCost' => '',
    '_EventCurrencySymbol' => '$',
    '_EventURL' => '',
    '_EventShowMap' => '1',
    '_EventShowMapLink' => '1',
    '_EventTimezone' => get_option('timezone_string'),
    'venue' => new ArrayObject(),
    'organizer' => new ArrayObject(),
    'categories' => [],
];

// Merge with defaults
$event_data = array_merge($defaults, $event_data);

// Parse dates for form display
$start_date = '';
$start_time = '';
if (!empty($event_data['_EventStartDate'])) {
    $start_dt = new DateTime($event_data['_EventStartDate']);
    $start_date = $start_dt->format('Y-m-d');
    $start_time = $start_dt->format('H:i');
}

$end_date = '';
$end_time = '';
if (!empty($event_data['_EventEndDate'])) {
    $end_dt = new DateTime($event_data['_EventEndDate']);
    $end_date = $end_dt->format('Y-m-d');
    $end_time = $end_dt->format('H:i');
}

get_header();
?>

<!-- Custom Event Edit Template Loaded Successfully -->
<div class="hvac-page-wrapper hvac-event-edit-page">
    <?php
    // Display navigation menu
    if (class_exists('HVAC_Menu_System')) {
        HVAC_Menu_System::instance()->render_trainer_menu();
    }
    
    // Display breadcrumbs
    if (class_exists('HVAC_Breadcrumbs')) {
        echo HVAC_Breadcrumbs::instance()->render_breadcrumbs();
    }
    ?>
    
    <div class="container">
        <div class="hvac-event-edit-wrapper">
            <h1 class="entry-title">
                <?php echo $event_id > 0 ? 'Edit Event' : 'Create New Event'; ?>
            </h1>
            
            <?php if (isset($_GET['updated']) && $_GET['updated'] === 'true'): ?>
                <div class="hvac-notice hvac-notice-success">
                    <p>Event saved successfully!</p>
                </div>
            <?php endif; ?>
            
            <form method="post" action="" class="hvac-event-form" novalidate>
                <?php wp_nonce_field('hvac_event_action', 'hvac_event_nonce'); ?>
                <input type="hidden" name="event_id" value="<?php echo esc_attr($event_id); ?>">
                
                <!-- Basic Information -->
                <div class="hvac-form-section">
                    <h2>Event Information</h2>
                    
                    <div class="hvac-form-row">
                        <label for="post_title" class="required">Event Title</label>
                        <input type="text" 
                               id="post_title" 
                               name="post_title" 
                               value="<?php echo esc_attr($event_data['title']); ?>" 
                               required>
                    </div>
                    
                    <div class="hvac-form-row">
                        <label for="post_content">Event Description</label>
                        <?php
                        wp_editor($event_data['content'], 'post_content', [
                            'textarea_name' => 'post_content',
                            'textarea_rows' => 10,
                            'media_buttons' => true,
                            'teeny' => false,
                        ]);
                        ?>
                    </div>
                    
                    <div class="hvac-form-row">
                        <label for="post_excerpt">Event Summary</label>
                        <textarea id="post_excerpt" 
                                  name="post_excerpt" 
                                  rows="3"><?php echo esc_textarea($event_data['excerpt']); ?></textarea>
                    </div>
                    
                    <div class="hvac-form-row">
                        <label for="post_status">Event Status</label>
                        <select id="post_status" name="post_status">
                            <option value="draft" <?php selected($event_data['status'], 'draft'); ?>>Draft</option>
                            <option value="publish" <?php selected($event_data['status'], 'publish'); ?>>Published</option>
                        </select>
                    </div>
                </div>
                
                <!-- Date & Time -->
                <div class="hvac-form-section">
                    <h2>Date & Time</h2>
                    
                    <div class="hvac-form-row hvac-row-half">
                        <div class="hvac-col">
                            <label for="EventStartDate" class="required">Start Date</label>
                            <input type="date" 
                                   id="EventStartDate" 
                                   name="EventStartDate" 
                                   value="<?php echo esc_attr($start_date); ?>" 
                                   required>
                        </div>
                        <div class="hvac-col">
                            <label for="EventStartTime">Start Time</label>
                            <input type="time" 
                                   id="EventStartTime" 
                                   name="EventStartTime" 
                                   value="<?php echo esc_attr($start_time); ?>">
                        </div>
                    </div>
                    
                    <div class="hvac-form-row hvac-row-half">
                        <div class="hvac-col">
                            <label for="EventEndDate" class="required">End Date</label>
                            <input type="date" 
                                   id="EventEndDate" 
                                   name="EventEndDate" 
                                   value="<?php echo esc_attr($end_date); ?>" 
                                   required>
                        </div>
                        <div class="hvac-col">
                            <label for="EventEndTime">End Time</label>
                            <input type="time" 
                                   id="EventEndTime" 
                                   name="EventEndTime" 
                                   value="<?php echo esc_attr($end_time); ?>">
                        </div>
                    </div>
                    
                    <div class="hvac-form-row">
                        <label class="hvac-checkbox-label">
                            <input type="checkbox" 
                                   id="EventAllDay" 
                                   name="EventAllDay" 
                                   value="1" 
                                   <?php checked($event_data['_EventAllDay'], '1'); ?>>
                            All Day Event
                        </label>
                    </div>
                    
                    <div class="hvac-form-row">
                        <label for="EventTimezone">Timezone</label>
                        <select id="EventTimezone" name="EventTimezone">
                            <?php
                            $timezones = timezone_identifiers_list();
                            foreach ($timezones as $tz) {
                                echo '<option value="' . esc_attr($tz) . '" ' . 
                                     selected($event_data['_EventTimezone'], $tz, false) . '>' . 
                                     esc_html($tz) . '</option>';
                            }
                            ?>
                        </select>
                    </div>
                </div>
                
                <!-- Event Details -->
                <div class="hvac-form-section">
                    <h2>Event Details</h2>
                    
                    <div class="hvac-form-row hvac-row-half">
                        <div class="hvac-col">
                            <label for="EventCost">Event Cost</label>
                            <div class="hvac-input-group">
                                <span class="hvac-input-prefix">$</span>
                                <input type="text" 
                                       id="EventCost" 
                                       name="EventCost" 
                                       value="<?php echo esc_attr($event_data['_EventCost']); ?>" 
                                       pattern="[0-9]*\.?[0-9]*">
                            </div>
                        </div>
                        <div class="hvac-col">
                            <label for="EventURL">Event Website</label>
                            <input type="url" 
                                   id="EventURL" 
                                   name="EventURL" 
                                   value="<?php echo esc_attr($event_data['_EventURL']); ?>">
                        </div>
                    </div>
                    
                    <div class="hvac-form-row">
                        <label class="hvac-checkbox-label">
                            <input type="checkbox" 
                                   id="EventShowMap" 
                                   name="EventShowMap" 
                                   value="1" 
                                   <?php checked($event_data['_EventShowMap'], '1'); ?>>
                            Show Map
                        </label>
                        <label class="hvac-checkbox-label">
                            <input type="checkbox" 
                                   id="EventShowMapLink" 
                                   name="EventShowMapLink" 
                                   value="1" 
                                   <?php checked($event_data['_EventShowMapLink'], '1'); ?>>
                            Show Map Link
                        </label>
                    </div>
                </div>
                
                <!-- Venue -->
                <div class="hvac-form-section">
                    <h2>Venue</h2>
                    
                    <?php
                    $venues = iterator_to_array($form_handler->getVenuesForDropdown());
                    if (!empty($venues)): ?>
                        <div class="hvac-form-row">
                            <label for="venue_id">Select Existing Venue</label>
                            <select id="venue_id" name="venue_id">
                                <option value="">-- Create New Venue --</option>
                                <?php foreach ($venues as $id => $name): ?>
                                    <option value="<?php echo esc_attr($id); ?>" 
                                            <?php selected($event_data['venue']->id ?? 0, $id); ?>>
                                        <?php echo esc_html($name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>
                    
                    <div class="hvac-venue-fields">
                        <div class="hvac-form-row">
                            <label for="venue_name">Venue Name</label>
                            <input type="text" 
                                   id="venue_name" 
                                   name="venue_name" 
                                   value="<?php echo esc_attr($event_data['venue']->title ?? ''); ?>">
                        </div>
                        
                        <div class="hvac-form-row">
                            <label for="venue_address">Address</label>
                            <input type="text" 
                                   id="venue_address" 
                                   name="venue_address" 
                                   value="<?php echo esc_attr($event_data['venue']->address ?? ''); ?>">
                        </div>
                        
                        <div class="hvac-form-row hvac-row-half">
                            <div class="hvac-col">
                                <label for="venue_city">City</label>
                                <input type="text" 
                                       id="venue_city" 
                                       name="venue_city" 
                                       value="<?php echo esc_attr($event_data['venue']->city ?? ''); ?>">
                            </div>
                            <div class="hvac-col">
                                <label for="venue_state">State/Province</label>
                                <input type="text" 
                                       id="venue_state" 
                                       name="venue_state" 
                                       value="<?php echo esc_attr($event_data['venue']->state ?? ''); ?>">
                            </div>
                        </div>
                        
                        <div class="hvac-form-row hvac-row-half">
                            <div class="hvac-col">
                                <label for="venue_zip">Zip/Postal Code</label>
                                <input type="text" 
                                       id="venue_zip" 
                                       name="venue_zip" 
                                       value="<?php echo esc_attr($event_data['venue']->zip ?? ''); ?>">
                            </div>
                            <div class="hvac-col">
                                <label for="venue_country">Country</label>
                                <input type="text" 
                                       id="venue_country" 
                                       name="venue_country" 
                                       value="<?php echo esc_attr($event_data['venue']->country ?? ''); ?>">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Organizer -->
                <div class="hvac-form-section">
                    <h2>Organizer</h2>
                    
                    <?php
                    $organizers = iterator_to_array($form_handler->getOrganizersForDropdown());
                    if (!empty($organizers)): ?>
                        <div class="hvac-form-row">
                            <label for="organizer_id">Select Existing Organizer</label>
                            <select id="organizer_id" name="organizer_id">
                                <option value="">-- Create New Organizer --</option>
                                <?php foreach ($organizers as $id => $name): ?>
                                    <option value="<?php echo esc_attr($id); ?>" 
                                            <?php selected($event_data['organizer']->id ?? 0, $id); ?>>
                                        <?php echo esc_html($name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>
                    
                    <div class="hvac-organizer-fields">
                        <div class="hvac-form-row">
                            <label for="organizer_name">Organizer Name</label>
                            <input type="text" 
                                   id="organizer_name" 
                                   name="organizer_name" 
                                   value="<?php echo esc_attr($event_data['organizer']->title ?? ''); ?>">
                        </div>
                        
                        <div class="hvac-form-row hvac-row-half">
                            <div class="hvac-col">
                                <label for="organizer_phone">Phone</label>
                                <input type="tel" 
                                       id="organizer_phone" 
                                       name="organizer_phone" 
                                       value="<?php echo esc_attr($event_data['organizer']->phone ?? ''); ?>">
                            </div>
                            <div class="hvac-col">
                                <label for="organizer_email">Email</label>
                                <input type="email" 
                                       id="organizer_email" 
                                       name="organizer_email" 
                                       value="<?php echo esc_attr($event_data['organizer']->email ?? ''); ?>">
                            </div>
                        </div>
                        
                        <div class="hvac-form-row">
                            <label for="organizer_website">Website</label>
                            <input type="url" 
                                   id="organizer_website" 
                                   name="organizer_website" 
                                   value="<?php echo esc_attr($event_data['organizer']->website ?? ''); ?>">
                        </div>
                    </div>
                </div>
                
                <!-- Categories -->
                <div class="hvac-form-section">
                    <h2>Categories</h2>
                    
                    <div class="hvac-form-row">
                        <div class="hvac-checkbox-group">
                            <?php
                            $categories = iterator_to_array($form_handler->getCategoriesForCheckboxes());
                            foreach ($categories as $id => $name): ?>
                                <label class="hvac-checkbox-label">
                                    <input type="checkbox" 
                                           name="event_categories[]" 
                                           value="<?php echo esc_attr($id); ?>" 
                                           <?php checked(in_array($id, $event_data['categories'])); ?>>
                                    <?php echo esc_html($name); ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Submit Buttons -->
                <div class="hvac-form-actions">
                    <button type="submit" class="hvac-button hvac-button-primary">
                        <?php echo $event_id > 0 ? 'Update Event' : 'Create Event'; ?>
                    </button>
                    <a href="<?php echo esc_url(home_url('/trainer/dashboard/')); ?>" 
                       class="hvac-button hvac-button-secondary">
                        Cancel
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Custom styles loaded via hvac-event-edit-custom.css -->

<?php
get_footer();