<?php $__env->startSection('title', 'Send Messages'); ?>
<?php $__env->startSection('page-title', 'Send Messages'); ?>
<?php $__env->startSection('page-subtitle', 'Send email, SMS, WhatsApp, and portal messages from one notification center'); ?>

<?php $__env->startSection('content'); ?>
<?php
    $campaignPage = $campaigns->getCollection();
    $sentOnPage = $campaignPage->sum('total_recipients');
    $failedOnPage = $campaignPage->sum('failed_count');
    $externalOnPage = $campaignPage
        ->filter(fn ($campaign) => in_array($campaign->recipient_type, ['external', 'bulk_sms'], true) || $campaign->audience_type === 'numbers')
        ->count();
    $membersWithPhone = $customers->filter(fn ($customer) => filled($customer->phone))->count();
    $channelCards = [
        ['email', 'Email', 'bi-envelope', 'Member or external email inbox'],
        ['sms', 'SMS', 'bi-phone', $smsConfigured ? 'Gateway ready' : 'Log mode'],
        ['portal', 'Portal', 'bi-bell', 'Registered members only'],
        ['whatsapp', 'WhatsApp', 'bi-whatsapp', $whatsappConfigured ? 'Gateway ready' : 'Log mode'],
    ];
    $channelStatuses = [
        ['email', 'Email', 'email_status', 'email_error'],
        ['sms', 'SMS', 'sms_status', 'sms_error'],
        ['portal', 'Portal', 'portal_alert_status', null],
        ['whatsapp', 'WhatsApp', 'whatsapp_status', 'whatsapp_error'],
    ];
?>

<section class="section-hero mb-4">
    <div class="section-hero-copy">
        <span>Notification center</span>
        <h2>One place for member and custom messages</h2>
        <p>Send normal member notifications, custom SMS, WhatsApp broadcasts, and external email campaigns without jumping between menus.</p>
    </div>
    <div class="section-hero-panel">
        <span>Ready contacts</span>
        <strong><?php echo e(number_format($customers->count())); ?></strong>
        <small><?php echo e(number_format($membersWithPhone)); ?> with phone numbers - <?php echo e($smsConfigured ? 'SMS ready' : 'SMS log mode'); ?> - <?php echo e($whatsappConfigured ? 'WhatsApp ready' : 'WhatsApp log mode'); ?></small>
    </div>
</section>

<div class="section-stat-grid mb-4">
    <div class="section-stat-card">
        <i class="bi bi-people"></i>
        <span>Members</span>
        <strong><?php echo e(number_format($customers->count())); ?></strong>
        <small>Visible recipients</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-send-check"></i>
        <span>Campaigns shown</span>
        <strong><?php echo e(number_format($campaignPage->count())); ?></strong>
        <small>Current page</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-person-plus"></i>
        <span>Custom campaigns</span>
        <strong><?php echo e(number_format($externalOnPage)); ?></strong>
        <small>External recipients</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-exclamation-triangle"></i>
        <span>Failed</span>
        <strong><?php echo e(number_format($failedOnPage)); ?></strong>
        <small>Needs attention</small>
    </div>
</div>

<div class="row g-4">
    <div class="col-xl-5">
        <div class="section-form-card sticky-lg-top">
            <div class="section-card-title">
                <span><i class="bi bi-megaphone"></i></span>
                <div>
                    <strong>Compose message</strong>
                    <small>Portal is disabled automatically for custom contacts.</small>
                </div>
            </div>

            <form method="POST" action="<?php echo e(route('tenant.customer-notifications.store')); ?>" class="row g-3" data-customer-notification-form>
                <?php echo csrf_field(); ?>

                <div class="col-12">
                    <label class="form-label">Subject</label>
                    <input name="subject" value="<?php echo e(old('subject')); ?>" class="form-control" placeholder="Loan reminder, KYC update, or campaign title" required maxlength="255">
                </div>

                <div class="col-12">
                    <label class="form-label">Message</label>
                    <textarea name="message" id="notificationMessage" rows="6" class="form-control" placeholder="Write the message recipients should receive" required maxlength="5000"><?php echo e(old('message')); ?></textarea>
                    <div class="sms-counter">
                        <span id="notificationSmsCount">0</span> characters
                        <span class="mx-1">-</span>
                        <span id="notificationSmsUnits">1</span> SMS unit<span id="notificationSmsUnitsPlural"></span> per SMS recipient
                    </div>
                    <div class="form-text">SMS uses 1 unit up to 160 characters. Longer messages use 153 characters per SMS page.</div>
                </div>

                <div class="col-12">
                    <label class="form-label">Channels</label>
                    <div class="channel-option-grid">
                        <?php $__currentLoopData = $channelCards; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as [$value, $label, $icon, $note]): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <label class="channel-option">
                                <input class="form-check-input" type="checkbox" name="channels[]" value="<?php echo e($value); ?>" data-channel="<?php echo e($value); ?>" <?php if(in_array($value, old('channels', ['email', 'portal']), true)): echo 'checked'; endif; ?>>
                                <span><i class="bi <?php echo e($icon); ?>"></i></span>
                                <strong><?php echo e($label); ?></strong>
                                <small><?php echo e($note); ?></small>
                            </label>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </div>
                    <div class="alert alert-info py-2 px-3 mt-3 mb-0 d-none" data-custom-portal-notice>
                        <i class="bi bi-info-circle me-1"></i> Portal alerts are only for registered members, so custom contacts can receive email, SMS, or WhatsApp only.
                    </div>
                </div>

                <div class="col-12">
                    <label class="form-label">Recipients</label>
                    <select name="audience_type" class="form-select" data-audience-select>
                        <option value="all" <?php if(old('audience_type', 'all') === 'all'): echo 'selected'; endif; ?>>All members</option>
                        <option value="individual" <?php if(old('audience_type') === 'individual'): echo 'selected'; endif; ?>>Selected members</option>
                        <option value="status" <?php if(old('audience_type') === 'status'): echo 'selected'; endif; ?>>Member status</option>
                        <option value="kyc" <?php if(old('audience_type') === 'kyc'): echo 'selected'; endif; ?>>KYC group</option>
                        <option value="numbers" <?php if(old('audience_type') === 'numbers'): echo 'selected'; endif; ?>>Custom numbers / emails</option>
                    </select>
                </div>

                <div class="col-12 d-none" data-audience-panel="individual">
                    <label class="form-label">Selected members</label>
                    <select name="customer_ids[]" class="form-select" multiple size="8">
                        <?php $__currentLoopData = $customers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $customer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($customer->id); ?>" <?php if(in_array($customer->id, old('customer_ids', []))): echo 'selected'; endif; ?>>
                                <?php echo e($customer->fullName()); ?> - <?php echo e($customer->phone ?: $customer->email ?: 'No contact'); ?>

                            </option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    <div class="form-text">Hold Ctrl to select more than one member.</div>
                </div>

                <div class="col-12 d-none" data-audience-panel="status">
                    <label class="form-label">Member status</label>
                    <select name="customer_status" class="form-select">
                        <option value="active" <?php if(old('customer_status', 'active') === 'active'): echo 'selected'; endif; ?>>Active members</option>
                        <option value="inactive" <?php if(old('customer_status') === 'inactive'): echo 'selected'; endif; ?>>Inactive members</option>
                        <option value="suspended" <?php if(old('customer_status') === 'suspended'): echo 'selected'; endif; ?>>Suspended members</option>
                    </select>
                </div>

                <div class="col-12 d-none" data-audience-panel="kyc">
                    <label class="form-label">KYC group</label>
                    <select name="kyc_status" class="form-select">
                        <option value="pending" <?php if(old('kyc_status', 'pending') === 'pending'): echo 'selected'; endif; ?>>Pending KYC</option>
                        <option value="verified" <?php if(old('kyc_status') === 'verified'): echo 'selected'; endif; ?>>Verified KYC</option>
                        <option value="rejected" <?php if(old('kyc_status') === 'rejected'): echo 'selected'; endif; ?>>Rejected KYC</option>
                    </select>
                </div>

                <div class="col-12 d-none" data-audience-panel="numbers">
                    <label class="form-label">Custom numbers / emails</label>
                    <textarea name="custom_recipients" class="form-control" rows="6" placeholder="Enter phone numbers or email addresses, one per line or separated with commas"><?php echo e(old('custom_recipients', old('phone_numbers'))); ?></textarea>
                    <div class="form-text">Use phone numbers for SMS or WhatsApp. Use email addresses for email. Portal messages are not available for custom contacts.</div>
                </div>

                <div class="col-12 d-grid">
                    <button class="btn btn-primary btn-lg">
                        <i class="bi bi-send me-1"></i> Send message
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="section-data-card">
            <div class="section-card-title">
                <span><i class="bi bi-clock-history"></i></span>
                <div>
                    <strong>Message history</strong>
                    <small>Member notifications, custom SMS, external email, and WhatsApp campaigns.</small>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table section-table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Message</th>
                            <th>Audience</th>
                            <th>Sent</th>
                            <th>Channels</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php $__empty_1 = true; $__currentLoopData = $campaigns; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $campaign): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                        <?php
                            $isExternal = in_array($campaign->recipient_type, ['external', 'bulk_sms'], true) || $campaign->audience_type === 'numbers';
                            $recipientLabel = $isExternal ? 'contact' : 'member';
                            $lastError = $campaign->recipients
                                ->flatMap(fn ($recipient) => [$recipient->email_error, $recipient->sms_error, $recipient->whatsapp_error])
                                ->filter()
                                ->first();
                        ?>
                        <tr>
                            <td>
                                <div class="fw-semibold"><?php echo e($campaign->subject); ?></div>
                                <small class="text-muted">By <?php echo e($campaign->createdBy?->name ?? 'System'); ?></small>
                                <?php if($lastError): ?>
                                    <div class="small text-danger mt-1"><i class="bi bi-exclamation-circle me-1"></i><?php echo e(str($lastError)->limit(90)); ?></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div><?php echo e($isExternal ? 'Custom contacts' : ucfirst(str_replace('_', ' ', $campaign->audience_type))); ?></div>
                                <small class="text-muted"><?php echo e(number_format($campaign->total_recipients)); ?> <?php echo e($recipientLabel); ?><?php echo e($campaign->total_recipients === 1 ? '' : 's'); ?></small>
                            </td>
                            <td><?php echo e(app_datetime($campaign->sent_at) ?? '-'); ?></td>
                            <td>
                                <div class="d-flex flex-wrap gap-1">
                                    <?php $__currentLoopData = $campaign->channels ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $channel): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <span class="badge text-bg-light border"><?php echo e(strtoupper($channel === 'portal' ? 'alert' : $channel)); ?></span>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </div>
                                <small class="text-muted d-block mt-1">
                                    Email <?php echo e(number_format($campaign->email_sent_count)); ?> - SMS <?php echo e(number_format($campaign->sms_sent_count)); ?> - Alerts <?php echo e(number_format($campaign->portal_alert_count)); ?> - WhatsApp <?php echo e(number_format($campaign->whatsapp_sent_count)); ?>

                                </small>
                            </td>
                            <td>
                                <span class="badge <?php echo e($campaign->failed_count > 0 ? 'text-bg-warning' : ($campaign->status === 'no_recipients' ? 'text-bg-secondary' : 'text-bg-success')); ?>">
                                    <?php echo e(ucwords(str_replace('_', ' ', $campaign->status))); ?>

                                </span>
                                <?php if($campaign->failed_count > 0): ?>
                                    <div class="small text-muted"><?php echo e(number_format($campaign->failed_count)); ?> failed</div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="d-flex flex-wrap gap-2">
                                    <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#notificationCampaign<?php echo e($campaign->id); ?>">
                                        <i class="bi bi-eye me-1"></i> View
                                    </button>
                                    <?php if($campaign->failed_count > 0): ?>
                                        <form method="POST" action="<?php echo e(route('tenant.customer-notifications.resend-failed', $campaign)); ?>">
                                            <?php echo csrf_field(); ?>
                                            <button class="btn btn-sm btn-warning" type="submit">
                                                <i class="bi bi-arrow-repeat me-1"></i> Resend failed
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                        <tr>
                            <td colspan="6" class="text-center text-muted py-5">No messages have been sent yet.</td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php $__currentLoopData = $campaigns; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $campaign): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <?php
                    $isExternal = in_array($campaign->recipient_type, ['external', 'bulk_sms'], true) || $campaign->audience_type === 'numbers';
                    $messageLength = function_exists('mb_strlen') ? mb_strlen($campaign->message ?? '') : strlen($campaign->message ?? '');
                    $messageUnits = $messageLength <= 160 ? 1 : (int) ceil($messageLength / 153);
                ?>
                <div class="modal fade" id="notificationCampaign<?php echo e($campaign->id); ?>" tabindex="-1" aria-labelledby="notificationCampaign<?php echo e($campaign->id); ?>Label" aria-hidden="true">
                    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
                        <div class="modal-content">
                            <div class="modal-header">
                                <div>
                                    <h5 class="modal-title" id="notificationCampaign<?php echo e($campaign->id); ?>Label"><?php echo e($campaign->subject); ?></h5>
                                    <div class="text-muted small">
                                        <?php echo e(app_datetime($campaign->created_at)); ?> - <?php echo e($isExternal ? 'Custom contacts' : ucfirst(str_replace('_', ' ', $campaign->audience_type))); ?>

                                    </div>
                                </div>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row g-3 mb-3">
                                    <div class="col-md-3"><div class="border rounded-3 p-3 h-100"><span class="text-muted small">Recipients</span><div class="fw-semibold"><?php echo e(number_format($campaign->total_recipients)); ?></div></div></div>
                                    <div class="col-md-3"><div class="border rounded-3 p-3 h-100"><span class="text-muted small">Email sent</span><div class="fw-semibold"><?php echo e(number_format($campaign->email_sent_count)); ?></div></div></div>
                                    <div class="col-md-3"><div class="border rounded-3 p-3 h-100"><span class="text-muted small">SMS / WhatsApp</span><div class="fw-semibold"><?php echo e(number_format($campaign->sms_sent_count + $campaign->whatsapp_sent_count)); ?></div></div></div>
                                    <div class="col-md-3"><div class="border rounded-3 p-3 h-100"><span class="text-muted small">Failed</span><div class="fw-semibold text-danger"><?php echo e(number_format($campaign->failed_count)); ?></div></div></div>
                                </div>
                                <div class="border rounded-3 p-3 bg-light mb-3">
                                    <div class="fw-semibold mb-1">Message</div>
                                    <div><?php echo e($campaign->message); ?></div>
                                    <div class="text-muted small mt-2"><?php echo e(number_format($messageLength)); ?> characters - <?php echo e(number_format($messageUnits)); ?> SMS unit<?php echo e($messageUnits === 1 ? '' : 's'); ?> per SMS recipient</div>
                                </div>
                                <div class="table-responsive">
                                    <table class="table section-table align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>Recipient</th>
                                                <th>Email</th>
                                                <th>Phone</th>
                                                <th>Delivery</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        <?php $__empty_1 = true; $__currentLoopData = $campaign->recipients; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $recipient): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                            <tr>
                                                <td><?php echo e($recipient->customer_name ?: ($isExternal ? 'External contact' : 'Member')); ?></td>
                                                <td><?php echo e($recipient->email ?: '-'); ?></td>
                                                <td><?php echo e($recipient->phone ?: '-'); ?></td>
                                                <td>
                                                    <div class="d-flex flex-column gap-1">
                                                        <?php $__currentLoopData = $channelStatuses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as [$channel, $label, $statusField, $errorField]): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                                            <?php if(in_array($channel, $campaign->channels ?? [], true)): ?>
                                                                <?php
                                                                    $status = $recipient->{$statusField} ?: 'pending';
                                                                    $error = $errorField ? $recipient->{$errorField} : null;
                                                                    $badge = in_array($status, ['sent', 'logged'], true) ? 'success' : ($status === 'failed' ? 'danger' : ($status === 'skipped' ? 'secondary' : 'light'));
                                                                ?>
                                                                <div>
                                                                    <span class="badge text-bg-<?php echo e($badge); ?>"><?php echo e($label); ?>: <?php echo e(ucfirst(str_replace('_', ' ', $status))); ?></span>
                                                                    <?php if($error): ?>
                                                                        <span class="small text-danger ms-1"><?php echo e($error); ?></span>
                                                                    <?php endif; ?>
                                                                </div>
                                                            <?php endif; ?>
                                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                            <tr>
                                                <td colspan="4" class="text-center text-muted py-4">No recipient records were saved for this campaign.</td>
                                            </tr>
                                        <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <?php if($campaign->failed_count > 0): ?>
                                    <form method="POST" action="<?php echo e(route('tenant.customer-notifications.resend-failed', $campaign)); ?>" class="me-auto">
                                        <?php echo csrf_field(); ?>
                                        <button class="btn btn-warning" type="submit">
                                            <i class="bi bi-arrow-repeat me-1"></i> Resend failed email/SMS/WhatsApp
                                        </button>
                                    </form>
                                <?php endif; ?>
                                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

            <div class="p-3"><?php echo e($campaigns->links()); ?></div>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('[data-customer-notification-form]').forEach((form) => {
    const select = form.querySelector('[data-audience-select]');
    const panels = form.querySelectorAll('[data-audience-panel]');
    const portalInput = form.querySelector('[data-channel="portal"]');
    const portalNotice = form.querySelector('[data-custom-portal-notice]');
    const message = form.querySelector('#notificationMessage');
    const count = form.querySelector('#notificationSmsCount');
    const units = form.querySelector('#notificationSmsUnits');
    const unitsPlural = form.querySelector('#notificationSmsUnitsPlural');

    const refreshAudience = () => {
        const customContacts = select.value === 'numbers';

        panels.forEach((panel) => {
            panel.classList.toggle('d-none', panel.dataset.audiencePanel !== select.value);
        });

        if (portalInput) {
            portalInput.disabled = customContacts;
            if (customContacts) {
                portalInput.checked = false;
            }
        }

        if (portalNotice) {
            portalNotice.classList.toggle('d-none', ! customContacts);
        }
    };

    const updateSmsCount = () => {
        const length = message.value.length;
        const smsUnits = length <= 160 ? 1 : Math.ceil(length / 153);

        count.textContent = length;
        units.textContent = smsUnits;
        unitsPlural.textContent = smsUnits === 1 ? '' : 's';
    };

    select.addEventListener('change', refreshAudience);
    message.addEventListener('input', updateSmsCount);
    refreshAudience();
    updateSmsCount();
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Polite hp\Documents\Codex\2026-05-08\build-a-complete-production-ready-saas\microfinance-saas\resources\views\tenant\customer-notifications\index.blade.php ENDPATH**/ ?>