<style>
.form-header-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.form-card-modern {
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    margin-bottom: 1.5rem;
    border: none;
    overflow: hidden;
}

.form-card-modern .card-header {
    background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
    border-bottom: 2px solid #e2e8f0;
    padding: 1.25rem 1.5rem;
    font-weight: 600;
    color: #2d3748;
}

.form-card-modern .card-body {
    padding: 2rem;
}

.form-label-modern {
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.form-control-modern {
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
    font-size: 1rem;
}

.form-control-modern:focus {
    border-color: #72A565;
    box-shadow: 0 0 0 3px rgba(114, 165, 101, 0.1);
    outline: none;
}

.form-group-modern {
    margin-bottom: 1.5rem;
}

.btn-submit-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(114, 165, 101, 0.3);
}

.btn-submit-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(114, 165, 101, 0.4);
    color: white;
}

.btn-modern {
    border-radius: 10px;
    padding: 0.6rem 1.5rem;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.info-box {
    background: #f7fafc;
    border-left: 4px solid #72A565;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
}

.info-box i {
    color: #72A565;
    margin-right: 0.5rem;
}

.market-checkbox:checked + label {
    color: #72A565;
    font-weight: 600;
}

.market-selector .form-check {
    transition: all 0.3s ease;
    cursor: pointer;
}

.market-selector .form-check:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(114, 165, 101, 0.15);
}

.market-selector .form-check input[type="checkbox"]:checked ~ label,
.market-selector .form-check:has(input[type="checkbox"]:checked) {
    border-color: #72A565;
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}

.market-preview {
    background: #f7fafc;
    border: 2px dashed #72A565;
    border-radius: 10px;
    padding: 1rem;
    margin-top: 1rem;
    min-height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.market-preview.has-selection {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border-style: solid;
}

.market-badge {
    display: inline-block;
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    margin: 0.25rem;
    font-size: 0.875rem;
    font-weight: 500;
}

.market-preview-text {
    color: #64748b;
    font-style: italic;
}

.form-check-input:checked {
    background-color: #72A565;
    border-color: #72A565;
}

.form-check-input:focus {
    border-color: #72A565;
    box-shadow: 0 0 0 0.25rem rgba(114, 165, 101, 0.25);
}

.user-type-card {
    transition: all 0.3s ease;
}

.user-type-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.user-type-card:has(.user-type-checkbox:checked) {
    border-color: #72A565;
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    box-shadow: 0 2px 8px rgba(114, 165, 101, 0.15);
}

.user-type-card label {
    width: 100%;
}
</style>

<div class="form-header-modern">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h2 class="mb-2">
                <i class="fa-solid fa-<?php echo (isset($promotions)) ? 'edit' : 'plus-circle'; ?>"></i> 
                <?php echo (isset($promotions)) ? 'Edit Notification' : 'Send New Notification'; ?>
            </h2>
            <p class="mb-0 opacity-75"><?php echo (isset($promotions)) ? 'Update notification details' : 'Send push notification to all users'; ?></p>
        </div>
        <div>
            <a href="<?php echo base_url('Promotion/notification'); ?>" class="btn btn-light btn-modern">
                <i class="fa-solid fa-arrow-left"></i> Back to Notifications
            </a>
        </div>
    </div>
</div>

<?php
$endpoint = isset($promotions) ? 'updatenotificationdata' : 'addnotificationdata';
$notifId = isset($id) ? $id : '';
$notifTitle = '';
$notifMessage = '';
$selectedUserTypes = array();
if (isset($promotions) && !empty($promotions)) {
    $notifTitle = isset($promotions['title']) ? $promotions['title'] : '';
    $notifMessage = isset($promotions['message']) ? $promotions['message'] : '';
    $selectedUserTypes = isset($promotions['selectedUserTypes']) && is_array($promotions['selectedUserTypes']) ? $promotions['selectedUserTypes'] : array('user', 'vendor', 'driver');
}
// If editing and no user types stored, default to all types
if (isset($promotions) && empty($selectedUserTypes)) {
    $selectedUserTypes = array('user', 'vendor', 'driver');
}
?>

<form method="post" id="notificationForm" action="<?php echo base_url('Promotion/' . $endpoint); ?>">
    <input type="hidden" name="id" id="id" value="<?php echo $notifId; ?>">
    
    <!-- Notification Information -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-bell text-primary"></i> Notification Details
            </h5>
        </div>
        <div class="card-body">
            <?php if (!isset($promotions)): ?>
            <div class="info-box" style="border-left-color: #72A565; background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);">
                <div class="d-flex align-items-start">
                    <i class="fa-solid fa-broadcast-tower" style="color: #72A565; font-size: 1.5rem; margin-right: 1rem; margin-top: 0.25rem;"></i>
                    <div class="flex-grow-1">
                        <strong style="color: #72A565; font-size: 1.1rem;">Admin Broadcast Notification</strong>
                        <p class="mb-2 mt-2">This notification will be sent to the <strong>selected user types</strong> (customers, vendors, and/or drivers) in the <strong>selected markets</strong>.</p>
                        <p class="mb-2 small text-muted"><i class="fa-solid fa-info-circle"></i> You can target specific user types (e.g., only vendors, only drivers) or select all types. If no user types are selected, all types will receive the notification.</p>
                        <div class="alert alert-warning mb-0" style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px; padding: 0.75rem; font-size: 0.875rem;">
                            <i class="fa-solid fa-exclamation-triangle text-warning"></i>
                            <strong>Operational Note:</strong> Order-related driver alerts remain strictly city-scoped and are not affected by this broadcast. They use separate routing logic.
                        </div>
                    </div>
                </div>
            </div>
            <?php else: ?>
            <div class="info-box" style="border-left-color: #72A565;">
                <i class="fa-solid fa-info-circle" style="color: #72A565;"></i>
                <strong>Update Notification:</strong> Modify the notification details and market selection. The notification will be updated in the system.
            </div>
            <?php endif; ?>
            
            <div class="form-group-modern">
                <label for="title" class="form-label-modern">Notification Title <span class="text-danger">*</span></label>
                <input type="text" 
                    class="form-control form-control-modern" 
                    id="title" 
                    name="title" 
                    placeholder="Enter notification title" 
                    value="<?php echo htmlspecialchars($notifTitle); ?>" 
                    required
                    maxlength="100">
                <small class="text-muted">Short, attention-grabbing title (max 100 characters)</small>
            </div>
            
            <div class="form-group-modern">
                <label for="message" class="form-label-modern">Notification Message <span class="text-danger">*</span></label>
                <textarea class="form-control form-control-modern" 
                    id="message" 
                    name="message" 
                    rows="5" 
                    placeholder="Enter notification message" 
                    required
                    maxlength="500"><?php echo htmlspecialchars($notifMessage); ?></textarea>
                <small class="text-muted">Clear and concise message (max 500 characters)</small>
                <div class="mt-2">
                    <span id="charCount" class="text-muted">0 / 500 characters</span>
                </div>
            </div>
        </div>
    </div>

    <!-- User Type Selection -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-users text-primary"></i> Recipient Type Selection
            </h5>
        </div>
        <div class="card-body">
            <div class="info-box" style="border-left-color: #72A565;">
                <i class="fa-solid fa-info-circle" style="color: #72A565;"></i>
                <strong>Select Recipient Types:</strong> Choose which user types should receive this notification in the selected markets.
                <br><small class="text-muted">You can select one or more user types. If none are selected, all user types will receive the notification.</small>
            </div>

                    <div class="row">
                <div class="col-md-4 mb-3">
                    <div class="form-check user-type-card" style="padding: 1.25rem; border: 2px solid #e2e8f0; border-radius: 10px; transition: all 0.3s ease; background: #fff; cursor: pointer; height: 100%;">
                        <input class="form-check-input user-type-checkbox" 
                            type="checkbox" 
                            name="userTypes[]" 
                            value="user" 
                            id="userType_customers"
                            <?php echo (empty($selectedUserTypes) || in_array('user', $selectedUserTypes)) ? 'checked' : ''; ?>
                            style="width: 22px; height: 22px; cursor: pointer; margin-top: 0;">
                        <label class="form-check-label ms-3" 
                            for="userType_customers"
                            style="cursor: pointer; margin: 0; width: 100%;">
                            <div class="d-flex align-items-center">
                                <i class="fa-solid fa-user text-primary me-2" style="font-size: 1.5rem;"></i>
                                <div>
                                    <strong style="font-size: 1rem; color: #2d3748;">All Customers</strong>
                                    <br><small class="text-muted">All customer accounts in selected markets</small>
                                </div>
                            </div>
                        </label>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="form-check user-type-card" style="padding: 1.25rem; border: 2px solid #e2e8f0; border-radius: 10px; transition: all 0.3s ease; background: #fff; cursor: pointer; height: 100%;">
                        <input class="form-check-input user-type-checkbox" 
                            type="checkbox" 
                            name="userTypes[]" 
                            value="vendor" 
                            id="userType_vendors"
                            <?php echo (empty($selectedUserTypes) || in_array('vendor', $selectedUserTypes)) ? 'checked' : ''; ?>
                            style="width: 22px; height: 22px; cursor: pointer; margin-top: 0;">
                        <label class="form-check-label ms-3" 
                            for="userType_vendors"
                            style="cursor: pointer; margin: 0; width: 100%;">
                            <div class="d-flex align-items-center">
                                <i class="fa-solid fa-store text-success me-2" style="font-size: 1.5rem;"></i>
                                <div>
                                    <strong style="font-size: 1rem; color: #2d3748;">All Vendors</strong>
                                    <br><small class="text-muted">All vendor accounts in selected markets</small>
                                </div>
                            </div>
                        </label>
                    </div>
                </div>
                <div class="col-md-4 mb-3">
                    <div class="form-check user-type-card" style="padding: 1.25rem; border: 2px solid #e2e8f0; border-radius: 10px; transition: all 0.3s ease; background: #fff; cursor: pointer; height: 100%;">
                        <input class="form-check-input user-type-checkbox" 
                            type="checkbox" 
                            name="userTypes[]" 
                            value="driver" 
                            id="userType_drivers"
                            <?php echo (empty($selectedUserTypes) || in_array('driver', $selectedUserTypes)) ? 'checked' : ''; ?>
                            style="width: 22px; height: 22px; cursor: pointer; margin-top: 0;">
                        <label class="form-check-label ms-3" 
                            for="userType_drivers"
                            style="cursor: pointer; margin: 0; width: 100%;">
                            <div class="d-flex align-items-center">
                                <i class="fa-solid fa-truck text-warning me-2" style="font-size: 1.5rem;"></i>
                                <div>
                                    <strong style="font-size: 1rem; color: #2d3748;">All Drivers</strong>
                                    <br><small class="text-muted">All driver accounts in selected markets</small>
                                </div>
                            </div>
                        </label>
                    </div>
                </div>
            </div>
            
            <div class="alert alert-info mb-0 mt-3" style="background: #e0f2fe; border: 1px solid #0ea5e9; border-radius: 8px; padding: 0.75rem;">
                <i class="fa-solid fa-info-circle text-info"></i>
                <strong>Note:</strong> If no user types are selected, the notification will be sent to all user types. 
                Order-related driver notifications remain strictly city-scoped and are not affected by this broadcast.
            </div>
        </div>
    </div>

    <!-- Market Selection -->
    <div class="form-card-modern">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fa-solid fa-map-marker-alt text-primary"></i> Market Selection
            </h5>
        </div>
        <div class="card-body">
            <div class="info-box" style="border-left-color: #72A565;">
                <i class="fa-solid fa-info-circle" style="color: #72A565;"></i>
                <strong>Market-Based Notification Routing:</strong>
                <br><br>
                <strong>How it works:</strong>
                <ul class="mb-2" style="padding-left: 1.5rem;">
                    <li><strong>Select Houston only</strong> → Notification sent to selected user types in Houston</li>
                    <li><strong>Select Austin only</strong> → Notification sent to selected user types in Austin</li>
                    <li><strong>Select both</strong> → Notification sent to selected user types in both markets</li>
                </ul>
                <div class="alert alert-warning mb-0 mt-2" style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px; padding: 0.75rem;">
                    <i class="fa-solid fa-exclamation-triangle text-warning"></i>
                    <strong>Important:</strong> Order-related driver notifications remain strictly city-scoped and are not affected by this broadcast.
                </div>
                <div class="mt-2">
                    <small class="text-muted">
                        <i class="fa-solid fa-check-circle text-success"></i> <strong>Future-proof:</strong> New markets automatically appear in this list without code changes.
                    </small>
                </div>
            </div>
            
            <!-- Market Selection Preview -->
            <div class="market-preview" id="marketPreview">
                <span class="market-preview-text">
                    <i class="fa-solid fa-hand-pointer"></i> Select one or more markets above to see preview
                </span>
                            </div>
                                          
            <div class="form-group-modern">
                <label class="form-label-modern">Select Markets <span class="text-danger">*</span></label>
                <div class="market-selector" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1rem; margin-top: 0.5rem;">
                    <?php 
                    $selectedMarkets = isset($promotions['selectedMarkets']) && is_array($promotions['selectedMarkets']) ? $promotions['selectedMarkets'] : array();
                    if (isset($cities) && !empty($cities)): 
                        // Sort cities by name for better UX
                        uasort($cities, function($a, $b) {
                            $nameA = isset($a['cityName']) ? $a['cityName'] : '';
                            $nameB = isset($b['cityName']) ? $b['cityName'] : '';
                            return strcmp($nameA, $nameB);
                        });
                        
                        foreach ($cities as $cityId => $city): 
                            $cityName = isset($city['cityName']) ? $city['cityName'] : $cityId;
                            $isChecked = in_array($cityId, $selectedMarkets);
                    ?>
                        <div class="form-check market-card" 
                             style="padding: 1rem; border: 2px solid <?php echo $isChecked ? '#72A565' : '#e2e8f0'; ?>; border-radius: 10px; transition: all 0.3s ease; background: <?php echo $isChecked ? 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)' : '#fff'; ?>; <?php echo $isChecked ? 'box-shadow: 0 2px 8px rgba(114, 165, 101, 0.15);' : ''; ?>">
                            <div class="d-flex align-items-center">
                                <input class="form-check-input market-checkbox" 
                                    type="checkbox" 
                                    name="markets[]" 
                                    value="<?php echo htmlspecialchars($cityId); ?>" 
                                    id="market_<?php echo htmlspecialchars($cityId); ?>"
                                    <?php echo $isChecked ? 'checked' : ''; ?>
                                    style="width: 22px; height: 22px; cursor: pointer; margin-top: 0; flex-shrink: 0;">
                                <label class="form-check-label ms-3 flex-grow-1" 
                                    for="market_<?php echo htmlspecialchars($cityId); ?>"
                                    style="cursor: pointer; font-weight: <?php echo $isChecked ? '600' : '500'; ?>; color: <?php echo $isChecked ? '#72A565' : '#2d3748'; ?>; margin: 0;">
                                    <div class="d-flex align-items-center">
                                        <i class="fa-solid fa-city me-2" style="color: <?php echo $isChecked ? '#72A565' : '#64748b'; ?>;"></i>
                                        <div>
                                            <div style="font-size: 1rem;">
                                                <?php echo htmlspecialchars($cityName); ?>
                                            </div>
                                            <?php if (isset($city['state'])): ?>
                                                <small class="text-muted" style="font-size: 0.75rem;">
                                                    <i class="fa-solid fa-map-pin"></i> <?php echo htmlspecialchars($city['state']); ?>
                                                </small>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </label>
                                <?php if ($isChecked): ?>
                                    <i class="fa-solid fa-check-circle text-success" style="font-size: 1.25rem; margin-left: 0.5rem;"></i>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php 
                        endforeach; 
                    else: 
                    ?>
                        <div class="alert alert-warning">
                            <i class="fa-solid fa-exclamation-triangle"></i> No cities found. Please add cities first.
                        </div>
                    <?php endif; ?>
                </div>
                <div class="mt-3 p-3" style="background: #f7fafc; border-radius: 8px; border-left: 4px solid #72A565;">
                    <small class="text-muted">
                        <i class="fa-solid fa-lightbulb text-warning"></i> <strong>Tip:</strong> This list dynamically loads all cities in the system. 
                        Select at least one market. All user types (customers, vendors, drivers) in selected markets will receive this notification.
                    </small>
                </div>
            </div>
        </div>
    </div>

    <!-- Notification Summary -->
    <div class="form-card-modern" id="notificationSummary" style="display: none;">
        <div class="card-header" style="background: linear-gradient(135deg, #72A565 0%, #91A134 100%); color: white;">
            <h5 class="mb-0">
                <i class="fa-solid fa-clipboard-check"></i> Notification Summary
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <h6 class="text-muted mb-3"><i class="fa-solid fa-map-marked-alt"></i> Target Markets</h6>
                    <div id="summaryMarkets" class="mb-3"></div>
                </div>
                <div class="col-md-6">
                    <h6 class="text-muted mb-3"><i class="fa-solid fa-users"></i> Recipient Types</h6>
                    <div id="summaryRecipients">
                        <p class="text-muted">Selected user types:</p>
                        <div id="summaryUserTypes">
                            <ul class="list-unstyled">
                                <li><i class="fa-solid fa-user text-primary"></i> Customers</li>
                                <li><i class="fa-solid fa-store text-success"></i> Vendors</li>
                                <li><i class="fa-solid fa-truck text-warning"></i> Drivers</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="alert alert-info mb-0" style="background: #e0f2fe; border: 1px solid #0ea5e9; border-radius: 8px;">
                <i class="fa-solid fa-info-circle text-info"></i>
                <strong>Routing Logic:</strong> Notifications are sent to all users whose <code>cityId</code> matches the selected markets. 
                This ensures proper market separation while allowing multi-market broadcasts.
            </div>
        </div>
                        </div>

    <!-- Submit Button -->
    <div class="text-end mb-4">
        <button type="submit" class="btn btn-submit-modern">
            <i class="fa-solid fa-<?php echo (isset($promotions)) ? 'save' : 'paper-plane'; ?>"></i> 
            <?php echo (isset($promotions)) ? 'Update Notification' : 'Send Notification'; ?>
        </button>
                      </div>
</form>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
$(document).ready(function() {
    // Character counter
    $('#message').on('input', function() {
        var length = $(this).val().length;
        $('#charCount').text(length + ' / 500 characters');
        if (length > 500) {
            $('#charCount').addClass('text-danger');
        } else {
            $('#charCount').removeClass('text-danger');
        }
    });
    
    // Initialize character count
    $('#message').trigger('input');
    
    // Market checkbox styling and preview
    function updateMarketPreview() {
        var selectedMarkets = [];
        $('.market-checkbox:checked').each(function() {
            var marketName = $(this).closest('.form-check').find('label').text().trim();
            selectedMarkets.push(marketName);
        });
        
        var preview = $('#marketPreview');
        if (selectedMarkets.length > 0) {
            preview.removeClass('market-preview-text').addClass('has-selection');
            var badgesHtml = '<div class="d-flex flex-wrap align-items-center gap-2"><strong class="me-2">Selected Markets:</strong>';
            selectedMarkets.forEach(function(market) {
                badgesHtml += '<span class="market-badge"><i class="fa-solid fa-check-circle me-1"></i>' + market + '</span>';
            });
            badgesHtml += '</div>';
            preview.html(badgesHtml);
        } else {
            preview.removeClass('has-selection');
            preview.html('<span class="market-preview-text"><i class="fa-solid fa-hand-pointer"></i> Select one or more markets above to see preview</span>');
        }
    }
    
    $('.market-checkbox').on('change', function() {
        var checkbox = $(this);
        var container = checkbox.closest('.form-check');
        if (checkbox.is(':checked')) {
            container.css({
                'background': 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                'border-color': '#72A565',
                'box-shadow': '0 2px 8px rgba(114, 165, 101, 0.15)'
            });
        } else {
            container.css({
                'background': '#fff',
                'border-color': '#e2e8f0',
                'box-shadow': 'none'
            });
        }
        updateMarketPreview();
    });
    
    // Initialize preview on page load
    updateMarketPreview();
    
    // User type card styling
    $('.user-type-checkbox').on('change', function() {
        var checkbox = $(this);
        var card = checkbox.closest('.user-type-card');
        if (checkbox.is(':checked')) {
            card.css({
                'border-color': '#72A565',
                'background': 'linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)',
                'box-shadow': '0 2px 8px rgba(114, 165, 101, 0.15)'
            });
        } else {
            card.css({
                'border-color': '#e2e8f0',
                'background': '#fff',
                'box-shadow': 'none'
            });
        }
        updateNotificationSummary();
    });
    
    // Initialize user type card styling
    $('.user-type-checkbox:checked').each(function() {
        $(this).trigger('change');
    });
    
    // Update notification summary
    function updateNotificationSummary() {
        var selectedMarkets = [];
        $('.market-checkbox:checked').each(function() {
            var marketName = $(this).closest('.form-check').find('label').text().trim();
            selectedMarkets.push(marketName);
        });
        
        var selectedUserTypes = [];
        var userTypeLabels = {
            'user': { icon: 'fa-user', text: 'Customers', color: 'text-primary' },
            'vendor': { icon: 'fa-store', text: 'Vendors', color: 'text-success' },
            'driver': { icon: 'fa-truck', text: 'Drivers', color: 'text-warning' }
        };
        
        $('.user-type-checkbox:checked').each(function() {
            var userType = $(this).val();
            if (userTypeLabels[userType]) {
                selectedUserTypes.push(userTypeLabels[userType]);
            }
        });
        
        if (selectedMarkets.length > 0) {
            $('#notificationSummary').slideDown();
            var marketsHtml = '';
            selectedMarkets.forEach(function(market) {
                marketsHtml += '<span class="market-badge me-2 mb-2"><i class="fa-solid fa-check-circle me-1"></i>' + market + '</span>';
            });
            $('#summaryMarkets').html(marketsHtml);
            
            // Update user types
            if (selectedUserTypes.length > 0) {
                var userTypesHtml = '<ul class="list-unstyled">';
                selectedUserTypes.forEach(function(type) {
                    userTypesHtml += '<li><i class="fa-solid ' + type.icon + ' ' + type.color + ' me-2"></i>' + type.text + '</li>';
                });
                userTypesHtml += '</ul>';
                $('#summaryUserTypes').html(userTypesHtml);
            } else {
                $('#summaryUserTypes').html('<p class="text-muted"><em>All user types (no filter applied)</em></p>');
            }
        } else {
            $('#notificationSummary').slideUp();
        }
    }
    
    // Update summary when markets or user types change
    $('.market-checkbox, .user-type-checkbox').on('change', function() {
        updateNotificationSummary();
    });
    
    // Initialize summary
    updateNotificationSummary();
    
    // Form submission
    $('#notificationForm').on('submit', function(e) {
        var form = $(this);
        
        // Validate market selection
        var selectedMarkets = $('.market-checkbox:checked').length;
        if (selectedMarkets === 0) {
            Swal.fire({
                icon: 'warning',
                title: 'Market Selection Required',
                html: '<p>Please select at least one market to send the notification.</p>' +
                      '<p class="text-muted small mt-2">Notifications are routed based on selected markets:<br>' +
                      '• Houston selected → sends to selected user types in Houston<br>' +
                      '• Austin selected → sends to selected user types in Austin<br>' +
                      '• Both selected → sends to selected user types in both markets</p>',
                confirmButtonText: 'OK',
                confirmButtonColor: '#72A565'
            });
            e.preventDefault();
            return false;
        }
        
        // Note: User types are optional - if none selected, all types will receive notification
        
        var formData = form.serialize();
        var url = form.attr('action');
        var submitBtn = form.find('button[type="submit"]');
        var originalText = submitBtn.html();
        var isEdit = <?php echo (isset($promotions)) ? 'true' : 'false'; ?>;
        
        submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Processing...');
        
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            success: function(response) {
                submitBtn.prop('disabled', false).html(originalText);
                
                var responseData;
                try {
                    responseData = typeof response === 'string' ? JSON.parse(response) : response;
                } catch (e) {
                    responseData = { success: true, message: 'Notification sent successfully!' };
                }
                
                if (responseData.success) {
                    if (responseData.stats && !isEdit) {
                        // Show detailed breakdown for new notifications
                        var stats = responseData.stats;
                        var statsText = '<strong>Total:</strong> ' + stats.totalUsers + ' users<br>';
                        if (stats.byType.customers > 0) statsText += '• <strong>' + stats.byType.customers + '</strong> customer' + (stats.byType.customers > 1 ? 's' : '') + '<br>';
                        if (stats.byType.vendors > 0) statsText += '• <strong>' + stats.byType.vendors + '</strong> vendor' + (stats.byType.vendors > 1 ? 's' : '') + '<br>';
                        if (stats.byType.drivers > 0) statsText += '• <strong>' + stats.byType.drivers + '</strong> driver' + (stats.byType.drivers > 1 ? 's' : '') + '<br>';
                        statsText += '<br><strong>Markets:</strong> ' + stats.markets.join(', ');
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Notification Sent!',
                            html: '<div style="text-align: left; font-size: 0.9rem;">' + 
                                  '<p><strong>' + responseData.message + '</strong></p>' +
                                  '<div style="background: #f7fafc; padding: 1rem; border-radius: 8px; margin-top: 1rem;">' + 
                                  statsText + 
                                  '</div></div>',
                            confirmButtonText: 'OK',
                            width: '500px',
                            timer: 5000,
                            timerProgressBar: true
                        }).then(function() {
                            window.location.href = '<?php echo base_url("Promotion/notification"); ?>';
                        });
                    } else {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: isEdit ? 'Notification updated successfully!' : (responseData.message || 'Notification sent successfully!'),
                            confirmButtonText: 'OK',
                            timer: 2000,
                            timerProgressBar: true
                        }).then(function() {
                            window.location.href = '<?php echo base_url("Promotion/notification"); ?>';
                        });
                    }
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: responseData.message || 'Something went wrong. Please try again.',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function() {
                submitBtn.prop('disabled', false).html(originalText);
                // Fallback to regular form submission
                form.off('submit').submit();
            }
        });
        
        e.preventDefault();
    });
});
</script>
