<?php
require_once 'config/database.php';
require_once 'config/auth_enhanced.php';

requireAdmin();

// Check if event ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Location: events.php');
    exit;
}

$eventId = (int)$_GET['id'];

require_once 'templates/header.php';
require_once 'templates/navbar.php';
require_once 'templates/sidebar.php';
?>

<!-- Content Wrapper -->
<div class="content-wrapper">
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Edit Event</h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="events.php">Events</a></li>
                        <li class="breadcrumb-item active">Edit Event</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title" id="eventTitle">Edit Event</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-info" id="viewEventBtn">
                                    <i class="fas fa-eye"></i> View Event
                                </button>
                                <button type="button" class="btn btn-danger" id="cancelBtn">
                                    <i class="fas fa-times"></i> Cancel
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <!-- Event form will be loaded here -->
                            <div class="overlay" id="eventLoader">
                                <i class="fas fa-sync fa-spin"></i>
                            </div>
                            <form id="editEventForm" style="display:none;" enctype="multipart/form-data">
                                <input type="hidden" name="id" id="eventId" value="<?php echo $eventId; ?>">
                                
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="form-group">
                                            <label>Event Title *</label>
                                            <input type="text" class="form-control" name="event_title" id="eventTitleInput" required>
                                        </div>
                                        <div class="form-group">
                                            <label>Event Description</label>
                                            <textarea class="form-control" name="event_description" id="eventDescriptionInput" rows="5"></textarea>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label>Current Banner</label>
                                            <div class="text-center">
                                                <img id="currentBanner" class="img-fluid mb-2" src="dist/img/default-event.jpg" alt="Event Banner">
                                            </div>
                                            <div class="custom-file">
                                                <input type="file" class="custom-file-input" id="eventBannerInput" name="event_banner" accept="image/*">
                                                <label class="custom-file-label" for="eventBannerInput">Choose new banner</label>
                                            </div>
                                            <small class="form-text text-muted">Leave empty to keep current banner</small>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label>Event Date *</label>
                                            <input type="date" class="form-control" name="event_date" id="eventDateInput" required>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label>Event Time</label>
                                            <input type="time" class="form-control" name="event_time" id="eventTimeInput">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label>Location</label>
                                            <input type="text" class="form-control" name="event_location" id="eventLocationInput">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Event Type *</label>
                                            <select class="form-control" name="event_type" id="eventTypeInput" required>
                                                <option value="">Select Type</option>
                                                <option value="meeting">Meeting</option>
                                                <option value="cultural">Cultural</option>
                                                <option value="sports">Sports</option>
                                                <option value="educational">Educational</option>
                                                <option value="social">Social</option>
                                                <option value="other">Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Max Participants</label>
                                            <input type="number" class="form-control" name="max_participants" id="maxParticipantsInput">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Registration Fee (₹)</label>
                                            <input type="number" step="0.01" class="form-control" name="registration_fee" id="registrationFeeInput">
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Status</label>
                                            <select class="form-control" name="status" id="statusInput">
                                                <option value="upcoming">Upcoming</option>
                                                <option value="ongoing">Ongoing</option>
                                                <option value="completed">Completed</option>
                                                <option value="cancelled">Cancelled</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="form-group text-center mt-4">
                                    <button type="submit" class="btn btn-primary btn-lg">
                                        <i class="fas fa-save"></i> Save Changes
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script>
$(document).ready(function() {
    const eventId = <?php echo $eventId; ?>;
    
    // Load event details
    $.ajax({
        url: 'api/get_event.php',
        type: 'GET',
        data: { id: eventId },
        success: function(response) {
            if (response.success) {
                const event = response.data;
                
                // Populate form fields
                $('#eventTitleInput').val(event.event_title);
                $('#eventDescriptionInput').val(event.event_description);
                $('#eventDateInput').val(event.event_date);
                $('#eventTimeInput').val(event.event_time);
                $('#eventLocationInput').val(event.event_location);
                $('#eventTypeInput').val(event.event_type);
                $('#maxParticipantsInput').val(event.max_participants);
                $('#registrationFeeInput').val(event.registration_fee);
                $('#statusInput').val(event.status);
                
                // Set banner if available
                if (event.event_banner_url) {
                    $('#currentBanner').attr('src', event.event_banner_url);
                }
                
                // Setup file input
                $('#eventBannerInput').on('change', function() {
                    const fileName = $(this).val().split('\\').pop();
                    $(this).next('.custom-file-label').addClass("selected").html(fileName);
                    
                    // Preview image
                    if (this.files && this.files[0]) {
                        const reader = new FileReader();
                        reader.onload = function(e) {
                            $('#currentBanner').attr('src', e.target.result);
                        }
                        reader.readAsDataURL(this.files[0]);
                    }
                });
                
                // Setup buttons
                $('#viewEventBtn').click(function() {
                    window.location.href = 'event-details.php?id=' + eventId;
                });
                
                $('#cancelBtn').click(function() {
                    window.location.href = 'events.php';
                });
                
                // Show form and hide loader
                $('#eventLoader').hide();
                $('#editEventForm').show();
            } else {
                toastr.error(response.message || 'Failed to load event details');
                $('#eventLoader').html('<div class="text-center"><h4>Event not found</h4><p>The requested event could not be loaded.</p></div>');
            }
        },
        error: function() {
            toastr.error('Error loading event details');
            $('#eventLoader').html('<div class="text-center"><h4>Error</h4><p>Failed to load event details. Please try again.</p></div>');
        }
    });
    
    // Handle form submission
    $('#editEventForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        $.ajax({
            url: 'api/update_event.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    toastr.success('Event updated successfully');
                    setTimeout(function() {
                        window.location.href = 'event-details.php?id=' + eventId;
                    }, 1500);
                } else {
                    toastr.error(response.message || 'Failed to update event');
                }
            },
            error: function() {
                toastr.error('Error updating event');
            }
        });
    });
});
</script>

<?php require_once 'templates/footer.php'; ?>
