<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>Send Complimentary Codes</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
    <?php echo app('Illuminate\Foundation\Vite')(['resources/css/app.css', 'resources/js/app.js']); ?>
    <style>
        :root {
            --primary-color: rgb(77, 11, 139);
            --secondary-color: rgb(117, 13, 143);
            --primary-light: rgba(77, 11, 139, 0.1);
            --text-color: #333;
            --light-gray: #f8f9fa;
            --medium-gray: #e9ecef;
            --dark-gray: #6c757d;
            --white: #fff;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            width: 100%;
            box-sizing: border-box;
        }
        
        .card {
            background: var(--white);
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .card-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e5e5e5;
        }
        
        .card-header.bg-primary {
            background-color: var(--primary-color);
            color: var(--white);
        }
        
        .card-body {
            padding: 20px;
        }
        
        .nav-tabs {
            display: flex;
            flex-wrap: nowrap;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            border-bottom: 1px solid #dee2e6;
            margin-bottom: 20px;
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        
        .nav-tabs::-webkit-scrollbar {
            display: none;
        }
        
        .nav-tabs .nav-item {
            margin-bottom: -1px;
            flex-shrink: 0;
        }
        
        .nav-tabs .nav-link {
            border: 1px solid transparent;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            padding: 12px 20px;
            color: var(--dark-gray);
            font-weight: 500;
            text-decoration: none;
            transition: all 0.2s ease;
            background-color: var(--light-gray);
            margin-right: 5px;
            white-space: nowrap;
        }
        
        .nav-tabs .nav-link:hover {
            border-color: var(--medium-gray) var(--medium-gray) #dee2e6;
            background-color: var(--medium-gray);
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary-color);
            background-color: var(--white);
            border-color: #dee2e6 #dee2e6 var(--white);
            border-bottom: 2px solid var(--primary-color);
        }
        
        .tab-content {
            position: relative;
        }
        
        .tab-pane {
            display: none;
        }
        
        .tab-pane.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-control {
            display: block;
            width: 100%;
            padding: 8px 12px;
            font-size: 16px;
            line-height: 1.5;
            color: #495057;
            background-color: var(--white);
            border: 1px solid #ced4da;
            border-radius: 4px;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
            box-sizing: border-box;
        }
        
        .form-control:focus {
            border-color: rgba(77, 11, 139, 0.5);
            outline: 0;
            box-shadow: 0 0 0 0.2rem rgba(77, 11, 139, 0.25);
        }
        
        .form-text {
            color: var(--dark-gray);
            font-size: 14px;
        }
        
        .btn {
            display: inline-block;
            padding: 8px 16px;
            font-size: 16px;
            font-weight: 500;
            line-height: 1.5;
            text-align: center;
            white-space: nowrap;
            border: 1px solid transparent;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease-in-out;
        }
        
        .btn-primary {
            color: var(--white);
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: rgb(57, 8, 104);
            border-color: rgb(47, 7, 87);
        }
        
        .form-check {
            margin-bottom: 10px;
        }
        
        .form-check-input {
            margin-top: 4px;
        }
        
        .form-check-label {
            margin-left: 5px;
        }
        
        .bg-light {
            background-color: var(--light-gray) !important;
        }
        
        .rounded {
            border-radius: 4px;
        }
        
        .p-3 {
            padding: 15px !important;
        }

        .py-4 {
            padding-top: 1rem !important;
            padding-bottom: 1rem !important;
        }

        .mt-3 {
            margin-top: 0.75rem !important;
        }

        .mt-2 {
            margin-top: 0.5rem !important;
        }

        .mb-0 {
            margin-bottom: 0 !important;
        }

        .mr-1 {
            margin-right: 0.25rem !important;
        }

        .text-white {
            color: var(--white) !important;
        }

        .form-control-file {
            display: block;
            width: 100%;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .card-body {
                padding: 15px;
            }
            
            .nav-tabs .nav-link {
                padding: 10px 15px;
                font-size: 14px;
            }
            
            .form-control {
                font-size: 15px;
            }
            
            .btn {
                width: 100%;
                padding: 10px;
            }
        }

        @media (max-width: 480px) {
            .container {
                padding: 10px;
            }
            
            .card-header {
                padding: 12px 15px;
            }
            
            .card-body {
                padding: 12px;
            }
            
            .nav-tabs .nav-link {
                padding: 8px 12px;
                font-size: 13px;
            }
            
            .form-group {
                margin-bottom: 15px;
            }
        }
    </style>
</head>
<body>
    <?php echo $__env->make('layouts.navigation', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

   <div class="container py-4">
    
        <div class="card">
            <div class="text-white card-header bg-primary">
                <h2 class="mb-0">Send Complimentary Codes via SMS</h2>
            </div>
            
            <div class="card-body">
                <ul class="nav-tabs" id="sendTab" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" id="single-tab" href="#single" role="tab" aria-controls="single" aria-selected="true">Single Recipient</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="bulk-tab" href="#bulk" role="tab" aria-controls="bulk" aria-selected="false">Bulk Send</a>
                    </li>
                </ul>
                
                <div class="tab-content" id="sendTabContent">
                    <!-- Single Recipient Tab -->
                    <div class="tab-pane active" id="single" role="tabpanel" aria-labelledby="single-tab">
                        <form id="singleSendForm" method="POST" action="<?php echo e(route('admin.send-codes.single')); ?>">
                            <?php echo csrf_field(); ?>
                            
                            <div class="form-group">
                                <label for="single_template">Select Template</label>
                                <select name="template" id="single_template" class="form-control" required>
                                    <option value="">-- Select Template --</option>
                                    <?php $__currentLoopData = $templates; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $template): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($key); ?>"><?php echo e($template['name']); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <small class="form-text text-muted">
                                    Preview will be shown below when template is selected
                                </small>
                            </div>
                            
                            <div class="form-group">
                                <label for="single_event_id">Event</label>
                                <select name="event_id" id="single_event_id" class="form-control" required>
                                    <option value="">-- Select Event --</option>
                                    <?php $__currentLoopData = $events; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $event): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($event->id); ?>"><?php echo e($event->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="name">Recipient Name</label>
                                <input type="text" name="name" id="name" class="form-control" placeholder="John Doe" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="phone">Recipient Phone</label>
                                <input type="tel" name="phone" class="form-control" placeholder="254712345678" required>
                                <small class="form-text text-muted">Format: 254712345678</small>
                            </div>
                            
                            <div class="form-group">
                                <label for="single_code_id">Code</label>
                                <select name="code_id" id="single_code_id" class="form-control" required>
                                    <option value="">-- Select Code --</option>
                                    <?php $__currentLoopData = $availableCodes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $code): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($code->id); ?>" data-expiry="<?php echo e($code->expires_at->format('jS F Y')); ?>">
                                            <?php echo e($code->code); ?> (expires <?php echo e($code->expires_at->format('jS F Y')); ?>)
                                        </option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>Message Preview</label>
                                <div id="single_message_preview" class="p-3 rounded bg-light" style="white-space: pre-line;"></div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="mr-1 fas fa-paper-plane"></i> Send SMS
                            </button>
                        </form>
                    </div>
                    
                    <!-- Bulk Send Tab -->
                    <div class="tab-pane" id="bulk" role="tabpanel" aria-labelledby="bulk-tab">
                        <form id="bulkSendForm" method="POST" action="<?php echo e(route('admin.send-codes.bulk')); ?>" enctype="multipart/form-data">
                            <?php echo csrf_field(); ?>
                            
                            <div class="form-group">
                                <label for="bulk_template">Select Template</label>
                                <select name="template" id="bulk_template" class="form-control" required>
                                    <option value="">-- Select Template --</option>
                                    <?php $__currentLoopData = $templates; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $template): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($key); ?>"><?php echo e($template['name']); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                                <small class="form-text text-muted">
                                    Preview will be shown below when template is selected
                                </small>
                            </div>
                            
                            <div class="form-group">
                                <label for="bulk_event_id">Event</label>
                                <select name="event_id" id="bulk_event_id" class="form-control" required>
                                    <option value="">-- Select Event --</option>
                                    <?php $__currentLoopData = $events; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $event): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($event->id); ?>"><?php echo e($event->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>Recipients</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="recipient_type" id="useFile" value="file" checked>
                                    <label class="form-check-label" for="useFile">Upload CSV with Names & Phones</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="recipient_type" id="usePhonesOnly" value="phones_only">
                                    <label class="form-check-label" for="usePhonesOnly">Upload Phone Numbers Only</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="recipient_type" id="useList" value="list">
                                    <label class="form-check-label" for="useList">Enter Manually</label>
                                </div>
                                
                                <div id="fileUpload" class="mt-2">
                                    <input type="file" name="recipient_file" id="recipient_file" class="form-control-file" accept=".csv">
                                    <small class="form-text text-muted">CSV format: phone,name (one per line). Example:<br>
                                    phone,name<br>
                                    254757909044,John Doe<br>
                                    254769394191,Jane Smith</small>
                                </div>
                                
                                <div id="phonesOnlyUpload" class="mt-2" style="display: none;">
                                    <input type="file" name="phones_only_file" id="phones_only_file" class="form-control-file" accept=".csv">
                                    <small class="form-text text-muted">CSV format: phone numbers only (one per line). Example:<br>
                                    254757909044<br>
                                    254769394191</small>
                                </div>
                                
                                <div id="manualList" class="mt-2" style="display: none;">
                                    <textarea name="recipient_list" id="recipient_list" class="form-control" rows="5" placeholder="Format: phone,name (one per line)"></textarea>
                                    <small class="form-text text-muted">Example:<br>254757909044,John Doe<br>254769394191,Jane Smith</small>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label>Message Preview</label>
                                <div id="bulk_message_preview" class="p-3 rounded bg-light" style="white-space: pre-line;"></div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="mr-1 fas fa-paper-plane"></i> Send Bulk SMS
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    // Set up CSRF token for AJAX requests
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $(document).ready(function() {
        // Tab functionality
        $('.nav-tabs a').click(function(e) {
            e.preventDefault();
            $('.tab-pane').removeClass('active');
            $('.nav-tabs a').removeClass('active');
            $(this).addClass('active');
            $($(this).attr('href')).addClass('active');
        });
        
        // Initialize template previews
        function updateTemplatePreview(templateKey, eventId, codeId, isBulk = false) {
            if (!templateKey || !eventId) return;

            const eventName = $(`#${isBulk ? 'bulk' : 'single'}_event_id option:selected`).text();
            const name = isBulk ? '[NAME]' : ($('#name').val() || 'Guest');

            let code;
            let expiryDate;
            if (isBulk) {
                code = '[CODE]';
                expiryDate = '[EXPIRY DATE]';
            } else {
                if (!codeId) return;
                code = $(`#single_code_id option:selected`).text().split(' ')[0];
                expiryDate = $(`#single_code_id option:selected`).data('expiry');
            }

            const redeemUrl = "<?php echo e(route('complimentary.redeem.form')); ?>?code=" + encodeURIComponent(code);
            
            const template = window.templates[templateKey].template
                .replace('{event_name}', eventName)
                .replace('{code}', code)
                .replace('{redeem_url}', redeemUrl)
                .replace('{expiry_date}', expiryDate)
                .replace('{name}', name);
            
            $(`#${isBulk ? 'bulk' : 'single'}_message_preview`).text(template);
        }
        
        // Template selection handler
        $('select[name="template"]').change(function() {
            const isBulk = $(this).attr('id').includes('bulk');
            const eventId = $(`#${isBulk ? 'bulk' : 'single'}_event_id`).val();
            const codeId = $(`#${isBulk ? 'bulk' : 'single'}_code_id`).val();
            updateTemplatePreview($(this).val(), eventId, codeId, isBulk);
        });
        
        // Event and code selection handlers
        $('#single_event_id, #bulk_event_id, #single_code_id').change(function() {
            const isBulk = $(this).attr('id').includes('bulk');
            const templateKey = $(`#${isBulk ? 'bulk' : 'single'}_template`).val();
            const eventId = $(`#${isBulk ? 'bulk' : 'single'}_event_id`).val();
            const codeId = $(`#${isBulk ? 'bulk' : 'single'}_code_id`).val();
            updateTemplatePreview(templateKey, eventId, codeId, isBulk);
        });
        
        // Name field handler for single send
        $('#name').on('input', function() {
            const templateKey = $('#single_template').val();
            const eventId = $('#single_event_id').val();
            const codeId = $('#single_code_id').val();
            updateTemplatePreview(templateKey, eventId, codeId, false);
        });
        
        // Recipient type toggle
        $('input[name="recipient_type"]').change(function() {
            $('#fileUpload, #phonesOnlyUpload, #manualList').hide();
            $('input[name="recipient_file"], input[name="phones_only_file"], textarea[name="recipient_list"]').prop('required', false);
            
            if ($(this).val() === 'file') {
                $('#fileUpload').show();
                $('input[name="recipient_file"]').prop('required', true);
            } else if ($(this).val() === 'phones_only') {
                $('#phonesOnlyUpload').show();
                $('input[name="phones_only_file"]').prop('required', true);
            } else {
                $('#manualList').show();
                $('textarea[name="recipient_list"]').prop('required', true);
            }
        });
        
        // Single send form
        $('#singleSendForm').on('submit', function(e) {
            e.preventDefault();
            const form = $(this);
            
            Swal.fire({
                title: 'Sending SMS...',
                text: 'Please wait while we process your request',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: form.serialize(),
                success: function(data) {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            text: data.message,
                            showConfirmButton: true,
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: data.error || 'Failed to send SMS',
                            showConfirmButton: true,
                        });
                    }
                },
                error: function(xhr) {
                    const error = xhr.responseJSON?.error || 'Network error';
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error,
                        showConfirmButton: true,
                    });
                }
            });
        });

        // Bulk send form
        $('#bulkSendForm').on('submit', function(e) {
            e.preventDefault();
            const form = $(this);
            const formData = new FormData(form[0]);
            const recipientType = $('input[name="recipient_type"]:checked').val();
            
            // Always set the recipient_type in formData
            formData.set('recipient_type', recipientType);
            
            if (recipientType === 'file') {
                const fileInput = $('#recipient_file')[0];
                if (!fileInput.files || !fileInput.files[0]) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Please select a CSV file with names and phones',
                        showConfirmButton: true,
                    });
                    return;
                }
            } else if (recipientType === 'phones_only') {
                const fileInput = $('#phones_only_file')[0];
                if (!fileInput.files || !fileInput.files[0]) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Please select a CSV file with phone numbers',
                        showConfirmButton: true,
                    });
                    return;
                }
            } else {
                let recipientList = $('#recipient_list').val().trim();
                if (!recipientList) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Please enter recipient list',
                        showConfirmButton: true,
                    });
                    return;
                }
                
                const lines = recipientList.split('\n');
                let hasError = false;
                let errorLine = 0;
                
                for (let i = 0; i < lines.length; i++) {
                    let line = lines[i].trim();
                    if (line) {
                        const separator = line.includes('.') ? '.' : ',';
                        const parts = line.split(separator);
                        if (parts.length < 2 || !parts[0].trim()) {
                            hasError = true;
                            errorLine = i + 1;
                            break;
                        }
                        // Convert dot to comma for backend consistency
                        if (separator === '.') {
                            lines[i] = parts.join(',');
                        }
                    }
                }
                
                if (hasError) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: `Invalid format at line ${errorLine}. Please use "phone,name" format.`,
                        showConfirmButton: true,
                    });
                    return;
                }
                
                // Replace textarea value with normalized comma-separated data
                recipientList = lines.join('\n');
                $('#recipient_list').val(recipientList);
            }
            
            Swal.fire({
                title: 'Sending SMS...',
                text: 'Please wait while we process your request',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                    if (data.success) {
                        let message = data.message;
                        
                        if (data.failed_count > 0) {
                            let failedList = '<ul>';
                            data.failed_recipients.forEach(recipient => {
                                failedList += `<li>${recipient.phone} (${recipient.name}): ${recipient.error}</li>`;
                            });
                            failedList += '</ul>';
                            
                            message += `<br><br>Failed recipients (${data.failed_count}): ${failedList}`;
                        }
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Success!',
                            html: message,
                            showConfirmButton: true,
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: data.error || 'Failed to send SMS',
                            showConfirmButton: true,
                        });
                    }
                },
                error: function(xhr) {
                    const error = xhr.responseJSON?.error || 'Network error';
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error,
                        showConfirmButton: true,
                    });
                }
            });
        });
    });

    // Make templates available to JS
    window.templates = <?php echo json_encode($templates, 15, 512) ?>;
</script><?php /**PATH D:\wamp64\www\paceerror\PaceEvents\resources\views\sms\send-codes.blade.php ENDPATH**/ ?>