# 7. Create Event JavaScript — `public/assets/custom/js/createEvent.js` (NEW)

## Pattern Reference

Follows patterns from existing JS files:
- `public/assets/custom/js/custom.js` — form validation and dynamic rows
- `resources/views/users/addClient.blade.php` — inline SweetAlert2 validation
- `public/assets/custom/js/events.js` — jQuery AJAX patterns

## Full File

```javascript
/**
 * Create Event form handler
 * Used on: /rm/create-event/{rmUuid}
 */

var serviceRowIndex = 1; // Start from 1 since row 0 exists in Blade

$(document).ready(function () {

    // Toggle remove button visibility
    toggleRemoveButtons();

    // Filter categories based on initial type selection
    filterCategories();
});

/**
 * Cascading dropdown: State → City
 * When state changes, fetch cities via AJAX and repopulate city dropdown.
 */
$('#state_id').on('change', function () {
    var stateId = $(this).val();
    var cityDropdown = $('#cities_id');

    cityDropdown.html('<option value="">Loading...</option>');

    if (!stateId) {
        cityDropdown.html('<option value="">Select City</option>');
        return;
    }

    $.ajax({
        type: 'GET',
        url: '/location/get-cities-by-state/' + stateId,
        success: function (cities) {
            var options = '<option value="">Select City</option>';
            cities.forEach(function (city) {
                options += '<option value="' + city.id + '">' + city.name + '</option>';
            });
            cityDropdown.html(options);
        },
        error: function () {
            cityDropdown.html('<option value="">Error loading cities</option>');
        }
    });
});

/**
 * Filter category dropdown based on event type selection.
 * Categories have a `type` field (personal/corporate).
 * Maps: event type "personal" → category type "personal"
 *        event type "professional" → category type "corporate"
 */
$('#type').on('change', function () {
    filterCategories();
});

function filterCategories() {
    var selectedType = $('#type').val();
    var categoryDropdown = $('#category');
    var currentVal = categoryDropdown.val();

    // Map event type to category type
    var categoryType = '';
    if (selectedType === 'personal') categoryType = 'personal';
    if (selectedType === 'professional') categoryType = 'corporate';

    // Show/hide options based on type
    categoryDropdown.find('option').each(function () {
        var optionType = $(this).data('type');
        if (!optionType || optionType === categoryType || !categoryType) {
            $(this).show();
        } else {
            $(this).hide();
            // Deselect if currently selected but now hidden
            if ($(this).val() === currentVal) {
                categoryDropdown.val('');
            }
        }
    });
}

/**
 * Add new service row
 */
$('#addServiceBtn').on('click', function () {
    var options = '<option value="">Select Service</option>';
    servicesOptions.forEach(function (service) {
        options += '<option value="' + service.id + '">' + service.name + '</option>';
    });

    var row = '<div class="row service-row mb-2">' +
        '<div class="col-md-5">' +
            '<div class="form-group">' +
                '<label>Service <span style="color:red;">*</span></label>' +
                '<select name="services[' + serviceRowIndex + '][id]" class="form-control service-select" required>' +
                    options +
                '</select>' +
            '</div>' +
        '</div>' +
        '<div class="col-md-4">' +
            '<div class="form-group">' +
                '<label>Budget</label>' +
                '<input type="number" name="services[' + serviceRowIndex + '][budget]" class="form-control" min="0" value="0" placeholder="Budget">' +
            '</div>' +
        '</div>' +
        '<div class="col-md-3 d-flex align-items-end">' +
            '<div class="form-group">' +
                '<button type="button" class="btn btn-danger btn-sm remove-service">' +
                    '<i class="fa fa-trash"></i> Remove' +
                '</button>' +
            '</div>' +
        '</div>' +
    '</div>';

    $('#servicesContainer').append(row);
    serviceRowIndex++;
    toggleRemoveButtons();
});

/**
 * Remove service row
 */
$(document).on('click', '.remove-service', function () {
    $(this).closest('.service-row').remove();
    toggleRemoveButtons();
});

/**
 * Show/hide remove buttons based on row count.
 * Hide when only 1 row (at least 1 service required).
 */
function toggleRemoveButtons() {
    var rows = $('.service-row');
    if (rows.length <= 1) {
        $('.remove-service').hide();
    } else {
        $('.remove-service').show();
    }
}

/**
 * Validate and submit the create event form.
 * Uses SweetAlert2 for validation messages (same pattern as addClient.blade.php).
 */
function submitCreateEvent() {
    var eventName = $('#event_name').val();
    var eventDate = $('#event_date').val();
    var eventTime = $('#event_start_time').val();
    var guestCount = $('#guest_count').val();
    var description = $('#description').val();
    var type = $('#type').val();
    var category = $('#category').val();
    var countryId = $('#country_id').val();
    var stateId = $('#state_id').val();
    var cityId = $('#cities_id').val();

    // Validate required fields
    if (!type) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select an event type.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!category) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select a category.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!eventName || eventName.length < 2) {
        Swal.fire({ title: 'Validation Error!', text: 'Please enter a valid event name.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!eventDate) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select an event date.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!eventTime) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select an event time.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!guestCount || guestCount < 1) {
        Swal.fire({ title: 'Validation Error!', text: 'Please enter the number of guests.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!countryId) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select a country.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!stateId) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select a state.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!cityId) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select a city.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }
    if (!description || description.length < 2) {
        Swal.fire({ title: 'Validation Error!', text: 'Please enter a description.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }

    // Validate at least one service is selected
    var serviceSelects = $('.service-select');
    var hasService = false;
    serviceSelects.each(function () {
        if ($(this).val()) {
            hasService = true;
        }
    });

    if (!hasService) {
        Swal.fire({ title: 'Validation Error!', text: 'Please select at least one service.', icon: 'error', confirmButtonText: 'OK' });
        return;
    }

    // Confirm and submit
    Swal.fire({
        title: 'Create Event?',
        text: 'This will create an event on behalf of the client.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Create Event',
        cancelButtonText: 'Cancel',
    }).then(function (result) {
        if (result.isConfirmed) {
            $('#createEventForm').submit();
        }
    });
}
```

## Behavior Summary

| Feature | How It Works |
|---------|-------------|
| **State → City cascade** | `$('#state_id').on('change')` → AJAX `GET /location/get-cities-by-state/{id}` → repopulate `#cities_id` |
| **Type → Category filter** | `$('#type').on('change')` → show/hide `<option>` tags based on `data-type` attribute |
| **Add service row** | `#addServiceBtn` click → append new row HTML with incremented index |
| **Remove service row** | `.remove-service` click → remove closest `.service-row`, toggle buttons |
| **Form validation** | `submitCreateEvent()` → field-by-field checks with SweetAlert2 |
| **Form submission** | After SweetAlert2 confirmation → standard `$('#createEventForm').submit()` (POST) |

## How the JS File Gets Loaded

The `layouts.dashboard` layout loads the `$js_file` variable at the bottom of the page:

```html
<script src="{{ asset('assets/custom/js/' . $js_file) }}"></script>
```

This is already the pattern used by `rm.js`, `events.js`, `dashboard.js`, etc. The controller passes `$js_file = 'createEvent.js'`.
