

<?php $__env->startSection('content'); ?>
<main id="main" class="main">
    <div class="pagetitle">
        <h1>Vouchers</h1>
        <nav>
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?php echo e(route('american.plastic.admin.dashboard')); ?>">Home</a></li>
                <li class="breadcrumb-item active">Vouchers</li>
            </ol>
        </nav>
    </div>

    <section class="section">
        <div class="row">
            <div class="col-lg-12">
                <?php if(session('success')): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo e(session('success')); ?>

                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                <?php if(session('error')): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo e(session('error')); ?>

                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="card-title">Voucher List</h5>
                            <a href="<?php echo e(route('admin.vouchers.create')); ?>" class="btn btn-primary btn-sm">
                                <i class="bi bi-plus-lg"></i> Create Voucher
                            </a>
                        </div>

                        <table class="table datatable">
                            <thead>
                                <tr>
                                    <th>Code</th>
                                    <th>Value</th>
                                    <th>Type</th>
                                    <th>Min Spend</th>
                                    <th>Expiry</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $vouchers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $voucher): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <tr>
                                    <td><strong><?php echo e($voucher->code); ?></strong></td>
                                    <td><?php echo e($voucher->value); ?></td>
                                    <td><span class="badge bg-info text-dark"><?php echo e(ucfirst($voucher->type)); ?></span></td>
                                    <td><?php echo e($voucher->min_spend); ?></td>
                                    <td><?php echo e($voucher->expiry_date->format('Y-m-d')); ?></td>
                                    <td>
                                        <?php if($voucher->status == 'active'): ?>
                                            <span class="badge bg-success">Active</span>
                                        <?php elseif($voucher->status == 'used'): ?>
                                            <span class="badge bg-warning text-dark">Used</span>
                                        <?php else: ?>
                                            <span class="badge bg-danger">Expired</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-2">
                                            <button type="button" class="btn btn-primary btn-sm send-voucher-btn" 
                                                    data-id="<?php echo e($voucher->id); ?>" 
                                                    data-code="<?php echo e($voucher->code); ?>" 
                                                    data-bs-toggle="modal" 
                                                    data-bs-target="#sendVoucherModal" 
                                                    title="Send via Mail">
                                                <i class="bi bi-envelope"></i>
                                            </button>
                                            <a href="<?php echo e(route('admin.vouchers.edit', $voucher->id)); ?>" class="btn btn-info btn-sm text-white">
                                                <i class="bi bi-pencil-square"></i>
                                            </a>
                                            <form action="<?php echo e(route('admin.vouchers.destroy', $voucher->id)); ?>" method="POST" onsubmit="return confirm('Are you sure?')">
                                                <?php echo csrf_field(); ?>
                                                <?php echo method_field('DELETE'); ?>
                                                <button type="submit" class="btn btn-danger btn-sm">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                        
                        <div class="mt-3">
                            <?php echo e($vouchers->links()); ?>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<!-- Send Voucher Modal -->
<div class="modal fade" id="sendVoucherModal" tabindex="-1" aria-labelledby="sendVoucherModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title font-weight-bold" id="sendVoucherModalLabel">Send Voucher</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="sendVoucherForm" method="POST" action="">
                <?php echo csrf_field(); ?>
                <div class="modal-body">
                    <div class="row">
                        <!-- Left column: Recipient Selection -->
                        <div class="col-md-6 border-end">
                            <div class="mb-3">
                                <label for="user_search" class="form-label font-weight-bold">Search Recipient</label>
                                <div class="input-group">
                                    <span class="input-group-text bg-white"><i class="bi bi-search"></i></span>
                                    <input type="text" id="user_search" class="form-control" placeholder="Type name or email to filter...">
                                </div>
                            </div>
                            
                            <div class="mb-2 d-flex justify-content-between align-items-center">
                                <label class="form-label font-weight-bold mb-0">Recipients <span class="text-danger">*</span></label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="select_all_users">
                                    <label class="form-check-label font-weight-bold text-primary" for="select_all_users" style="cursor: pointer;">
                                        Select All
                                    </label>
                                </div>
                            </div>
                            
                            <div class="border rounded p-3 bg-light" style="max-height: 250px; overflow-y: auto;" id="users_list_container">
                                <?php $__currentLoopData = $users; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $user): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <div class="form-check user-item mb-2" data-search="<?php echo e(strtolower($user->name . ' ' . $user->email)); ?>">
                                        <input class="form-check-input user-checkbox" type="checkbox" name="user_ids[]" value="<?php echo e($user->id); ?>" id="user_<?php echo e($user->id); ?>">
                                        <label class="form-check-label w-100" for="user_<?php echo e($user->id); ?>" style="cursor: pointer;">
                                            <div class="font-weight-bold"><?php echo e($user->name); ?></div>
                                            <div class="text-muted small"><?php echo e($user->email); ?></div>
                                        </label>
                                    </div>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </div>
                            <div class="form-text text-muted mt-2">
                                Only active, verified user accounts are shown here.
                            </div>
                        </div>

                        <!-- Right column: Custom Email Message -->
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="custom_message" class="form-label font-weight-bold">Custom Email Message (Optional)</label>
                                <textarea name="custom_message" id="custom_message" class="form-control" rows="11" placeholder="Type a custom greeting, message, or special instructions to include in the email. If left blank, our standard friendly greeting will be used."></textarea>
                                <div class="form-text text-muted mt-2">
                                    <strong>Available placeholders:</strong><br>
                                    <code>{customer_name}</code> - Recipient's name<br>
                                    <code>{voucher_code}</code> - Voucher promo code<br>
                                    <code>{voucher_value}</code> - Value (e.g. LKR 500.00 OFF or 10% OFF)<br>
                                    <code>{expiry_date}</code> - Expiration date
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-send me-1"></i> Send Voucher
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize Summernote editor
    $('#custom_message').summernote({
        placeholder: 'Type a custom greeting, message, or special instructions to include in the email. If left blank, our standard friendly greeting will be used.',
        tabsize: 2,
        height: 240,
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'italic', 'underline', 'clear']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['insert', ['link']],
            ['view', ['codeview']]
        ]
    });

    // Handle Send Button click to prepare modal
    $('.send-voucher-btn').on('click', function() {
        var voucherId = $(this).data('id');
        var voucherCode = $(this).data('code');
        $('#sendVoucherModalLabel').html('<i class="bi bi-ticket-perforated me-2"></i>Send Voucher: ' + voucherCode);
        
        var url = "<?php echo e(route('admin.vouchers.send-mail', ':id')); ?>";
        url = url.replace(':id', voucherId);
        $('#sendVoucherForm').attr('action', url);
        
        // Reset search, checkboxes, and text area
        $('#user_search').val('');
        $('.user-checkbox').prop('checked', false);
        $('#select_all_users').prop('checked', false);
        $('.user-item').show();
        
        // Default premium customer experience email template content
        var defaultTemplate = '<h3><strong>Exclusive Offer from American Plastics!</strong></h3>' +
            '<p>Dear {customer_name},</p>' +
            '<p>We value you as a premium customer. As a token of our appreciation for your loyalty and support, we are excited to offer you an exclusive discount on your next purchase.</p>' +
            '<p>Explore our latest collection of durable, premium-quality household, kitchen, and industrial plasticware products designed to make your everyday organization effortless and eco-friendly.</p>' +
            '<p>Simply use the exclusive promo code <strong>{voucher_code}</strong> during checkout to claim your <strong>{voucher_value}</strong> discount. This offer is valid until <strong>{expiry_date}</strong>.</p>' +
            '<p>We look forward to serving you again! Happy shopping!</p>';
        $('#custom_message').summernote('code', defaultTemplate);
    });

    // Select/Deselect All visible user checkboxes
    $('#select_all_users').on('change', function() {
        var isChecked = $(this).is(':checked');
        $('.user-checkbox').filter(function() {
            return $(this).closest('.user-item').is(':visible');
        }).prop('checked', isChecked);
    });

    // Handle user search filtering
    $('#user_search').on('keyup', function() {
        var value = $(this).val().toLowerCase();
        $('.user-item').filter(function() {
            $(this).toggle($(this).data('search').indexOf(value) > -1);
        });
        
        // If "Select All" is checked, update its state based on visible checkboxes
        updateSelectAllState();
    });

    // Update Select All checkbox state when individual checkboxes change
    $(document).on('change', '.user-checkbox', function() {
        updateSelectAllState();
    });

    function updateSelectAllState() {
        var visibleCheckboxes = $('.user-checkbox').filter(function() {
            return $(this).closest('.user-item').is(':visible');
        });
        
        if (visibleCheckboxes.length === 0) {
            $('#select_all_users').prop('checked', false);
            return;
        }

        var allChecked = visibleCheckboxes.filter(':checked').length === visibleCheckboxes.length;
        $('#select_all_users').prop('checked', allChecked);
    }

    // Form validation: ensure at least one user is checked
    $('#sendVoucherForm').on('submit', function(e) {
        if ($('.user-checkbox:checked').length === 0) {
            e.preventDefault();
            alert('Please select at least one recipient user.');
            return false;
        }
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layout.dashboard_master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/amerbofz/test.americanplastics.lk/resources/views/admin/vouchers/index.blade.php ENDPATH**/ ?>