@extends('layouts.app')

@section('title', 'Send Messages')
@section('page-title', 'Send Messages')
@section('page-subtitle', 'Send email, SMS, WhatsApp, and portal messages from one notification center')

@section('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'],
    ];
@endphp

<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>{{ number_format($customers->count()) }}</strong>
        <small>{{ number_format($membersWithPhone) }} with phone numbers - {{ $smsConfigured ? 'SMS ready' : 'SMS log mode' }} - {{ $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>{{ 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>{{ 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>{{ 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>{{ 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="{{ route('tenant.customer-notifications.store') }}" class="row g-3" data-customer-notification-form>
                @csrf

                <div class="col-12">
                    <label class="form-label">Subject</label>
                    <input name="subject" value="{{ 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">{{ 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">
                        @foreach($channelCards as [$value, $label, $icon, $note])
                            <label class="channel-option">
                                <input class="form-check-input" type="checkbox" name="channels[]" value="{{ $value }}" data-channel="{{ $value }}" @checked(in_array($value, old('channels', ['email', 'portal']), true))>
                                <span><i class="bi {{ $icon }}"></i></span>
                                <strong>{{ $label }}</strong>
                                <small>{{ $note }}</small>
                            </label>
                        @endforeach
                    </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" @selected(old('audience_type', 'all') === 'all')>All members</option>
                        <option value="individual" @selected(old('audience_type') === 'individual')>Selected members</option>
                        <option value="status" @selected(old('audience_type') === 'status')>Member status</option>
                        <option value="kyc" @selected(old('audience_type') === 'kyc')>KYC group</option>
                        <option value="numbers" @selected(old('audience_type') === 'numbers')>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">
                        @foreach($customers as $customer)
                            <option value="{{ $customer->id }}" @selected(in_array($customer->id, old('customer_ids', [])))>
                                {{ $customer->fullName() }} - {{ $customer->phone ?: $customer->email ?: 'No contact' }}
                            </option>
                        @endforeach
                    </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" @selected(old('customer_status', 'active') === 'active')>Active members</option>
                        <option value="inactive" @selected(old('customer_status') === 'inactive')>Inactive members</option>
                        <option value="suspended" @selected(old('customer_status') === 'suspended')>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" @selected(old('kyc_status', 'pending') === 'pending')>Pending KYC</option>
                        <option value="verified" @selected(old('kyc_status') === 'verified')>Verified KYC</option>
                        <option value="rejected" @selected(old('kyc_status') === 'rejected')>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">{{ 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>
                    @forelse($campaigns as $campaign)
                        @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();
                        @endphp
                        <tr>
                            <td>
                                <div class="fw-semibold">{{ $campaign->subject }}</div>
                                <small class="text-muted">By {{ $campaign->createdBy?->name ?? 'System' }}</small>
                                @if($lastError)
                                    <div class="small text-danger mt-1"><i class="bi bi-exclamation-circle me-1"></i>{{ str($lastError)->limit(90) }}</div>
                                @endif
                            </td>
                            <td>
                                <div>{{ $isExternal ? 'Custom contacts' : ucfirst(str_replace('_', ' ', $campaign->audience_type)) }}</div>
                                <small class="text-muted">{{ number_format($campaign->total_recipients) }} {{ $recipientLabel }}{{ $campaign->total_recipients === 1 ? '' : 's' }}</small>
                            </td>
                            <td>{{ app_datetime($campaign->sent_at) ?? '-' }}</td>
                            <td>
                                <div class="d-flex flex-wrap gap-1">
                                    @foreach($campaign->channels ?? [] as $channel)
                                        <span class="badge text-bg-light border">{{ strtoupper($channel === 'portal' ? 'alert' : $channel) }}</span>
                                    @endforeach
                                </div>
                                <small class="text-muted d-block mt-1">
                                    Email {{ number_format($campaign->email_sent_count) }} - SMS {{ number_format($campaign->sms_sent_count) }} - Alerts {{ number_format($campaign->portal_alert_count) }} - WhatsApp {{ number_format($campaign->whatsapp_sent_count) }}
                                </small>
                            </td>
                            <td>
                                <span class="badge {{ $campaign->failed_count > 0 ? 'text-bg-warning' : ($campaign->status === 'no_recipients' ? 'text-bg-secondary' : 'text-bg-success') }}">
                                    {{ ucwords(str_replace('_', ' ', $campaign->status)) }}
                                </span>
                                @if($campaign->failed_count > 0)
                                    <div class="small text-muted">{{ number_format($campaign->failed_count) }} failed</div>
                                @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{{ $campaign->id }}">
                                        <i class="bi bi-eye me-1"></i> View
                                    </button>
                                    @if($campaign->failed_count > 0)
                                        <form method="POST" action="{{ route('tenant.customer-notifications.resend-failed', $campaign) }}">
                                            @csrf
                                            <button class="btn btn-sm btn-warning" type="submit">
                                                <i class="bi bi-arrow-repeat me-1"></i> Resend failed
                                            </button>
                                        </form>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="6" class="text-center text-muted py-5">No messages have been sent yet.</td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>

            @foreach($campaigns as $campaign)
                @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);
                @endphp
                <div class="modal fade" id="notificationCampaign{{ $campaign->id }}" tabindex="-1" aria-labelledby="notificationCampaign{{ $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{{ $campaign->id }}Label">{{ $campaign->subject }}</h5>
                                    <div class="text-muted small">
                                        {{ app_datetime($campaign->created_at) }} - {{ $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">{{ 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">{{ 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">{{ 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">{{ 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>{{ $campaign->message }}</div>
                                    <div class="text-muted small mt-2">{{ number_format($messageLength) }} characters - {{ number_format($messageUnits) }} SMS unit{{ $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>
                                        @forelse($campaign->recipients as $recipient)
                                            <tr>
                                                <td>{{ $recipient->customer_name ?: ($isExternal ? 'External contact' : 'Member') }}</td>
                                                <td>{{ $recipient->email ?: '-' }}</td>
                                                <td>{{ $recipient->phone ?: '-' }}</td>
                                                <td>
                                                    <div class="d-flex flex-column gap-1">
                                                        @foreach($channelStatuses as [$channel, $label, $statusField, $errorField])
                                                            @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'));
                                                                @endphp
                                                                <div>
                                                                    <span class="badge text-bg-{{ $badge }}">{{ $label }}: {{ ucfirst(str_replace('_', ' ', $status)) }}</span>
                                                                    @if($error)
                                                                        <span class="small text-danger ms-1">{{ $error }}</span>
                                                                    @endif
                                                                </div>
                                                            @endif
                                                        @endforeach
                                                    </div>
                                                </td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="4" class="text-center text-muted py-4">No recipient records were saved for this campaign.</td>
                                            </tr>
                                        @endforelse
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                @if($campaign->failed_count > 0)
                                    <form method="POST" action="{{ route('tenant.customer-notifications.resend-failed', $campaign) }}" class="me-auto">
                                        @csrf
                                        <button class="btn btn-warning" type="submit">
                                            <i class="bi bi-arrow-repeat me-1"></i> Resend failed email/SMS/WhatsApp
                                        </button>
                                    </form>
                                @endif
                                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>
            @endforeach

            <div class="p-3">{{ $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>
@endsection
