@extends('layouts.app')

@section('title', 'Notifications')
@section('page-title', 'Notifications')
@section('page-subtitle', 'Send email, SMS, portal, and WhatsApp alerts to tenants')

@section('content')
<div class="row g-4">
    <div class="col-xl-5">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
                    <div>
                        <h2 class="h5 mb-1">Send notification</h2>
                        <div class="small text-muted">Email uses your mail settings. SMS and WhatsApp use configured gateways.</div>
                    </div>
                    <div class="d-flex flex-column align-items-end gap-1">
                        <span class="badge {{ $smsConfigured ? 'text-bg-success' : 'text-bg-warning' }}">SMS {{ $smsConfigured ? 'ready' : 'log mode' }}</span>
                        <span class="badge {{ $whatsappConfigured ? 'text-bg-success' : 'text-bg-warning' }}">WhatsApp {{ $whatsappConfigured ? 'ready' : 'log mode' }}</span>
                    </div>
                </div>

                <form method="POST" action="{{ route('super.notifications.store') }}" class="vstack gap-3" data-notification-form>
                    @csrf

                    <div>
                        <label class="form-label">Subject</label>
                        <input name="subject" value="{{ old('subject') }}" class="form-control" required maxlength="255">
                    </div>

                    <div>
                        <label class="form-label">Message</label>
                        <textarea name="message" rows="6" class="form-control" required maxlength="5000">{{ old('message') }}</textarea>
                    </div>

                    <div>
                        <label class="form-label">Channels</label>
                        <div class="d-flex flex-wrap gap-3">
                            <label class="form-check">
                                <input class="form-check-input" type="checkbox" name="channels[]" value="email" @checked(in_array('email', old('channels', ['email'])))>
                                <span class="form-check-label"><i class="bi bi-envelope me-1"></i>Email</span>
                            </label>
                            <label class="form-check">
                                <input class="form-check-input" type="checkbox" name="channels[]" value="sms" @checked(in_array('sms', old('channels', [])))>
                                <span class="form-check-label"><i class="bi bi-phone me-1"></i>SMS</span>
                            </label>
                            <label class="form-check">
                                <input class="form-check-input" type="checkbox" name="channels[]" value="portal" @checked(in_array('portal', old('channels', ['portal'])))>
                                <span class="form-check-label"><i class="bi bi-bell me-1"></i>Portal alert</span>
                            </label>
                            <label class="form-check">
                                <input class="form-check-input" type="checkbox" name="channels[]" value="whatsapp" @checked(in_array('whatsapp', old('channels', [])))>
                                <span class="form-check-label"><i class="bi bi-whatsapp me-1"></i>WhatsApp</span>
                            </label>
                        </div>
                    </div>

                    <div>
                        <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 tenants</option>
                            <option value="individual" @selected(old('audience_type') === 'individual')>Selected tenants</option>
                            <option value="status" @selected(old('audience_type') === 'status')>Tenant group</option>
                            <option value="plan" @selected(old('audience_type') === 'plan')>Plan group</option>
                        </select>
                    </div>

                    <div data-audience-panel="individual" class="d-none">
                        <label class="form-label">Selected tenants</label>
                        <select name="tenant_ids[]" class="form-select" multiple size="8">
                            @foreach($tenants as $tenant)
                                <option value="{{ $tenant->id }}" @selected(in_array($tenant->id, old('tenant_ids', [])))>
                                    {{ $tenant->name }} - {{ $tenant->email }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div data-audience-panel="status" class="d-none">
                        <label class="form-label">Tenant group</label>
                        <select name="tenant_state" class="form-select">
                            <option value="active" @selected(old('tenant_state') === 'active')>Active tenants</option>
                            <option value="trial" @selected(old('tenant_state') === 'trial')>Trial tenants</option>
                            <option value="new" @selected(old('tenant_state') === 'new')>New tenants</option>
                            <option value="expired" @selected(old('tenant_state') === 'expired')>Expired tenants</option>
                            <option value="suspended" @selected(old('tenant_state') === 'suspended')>Suspended tenants</option>
                        </select>
                    </div>

                    <div data-audience-panel="plan" class="d-none">
                        <label class="form-label">Plan group</label>
                        <select name="plan_id" class="form-select">
                            <option value="">Choose plan</option>
                            @foreach($plans as $plan)
                                <option value="{{ $plan->id }}" @selected((string) old('plan_id') === (string) $plan->id)>{{ $plan->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <button class="btn btn-primary">
                        <i class="bi bi-send me-1"></i> Send notification
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-7">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white fw-semibold">Recent notifications</div>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Message</th>
                            <th>Audience</th>
                            <th>Sent</th>
                            <th>Channels</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                    @forelse($campaigns as $campaign)
                        <tr>
                            <td>
                                <div class="fw-semibold">{{ $campaign->subject }}</div>
                                <small class="text-muted">By {{ $campaign->createdBy?->name ?? 'System' }}</small>
                            </td>
                            <td>
                                <div>{{ ucfirst(str_replace('_', ' ', $campaign->audience_type)) }}</div>
                                <small class="text-muted">{{ $campaign->total_recipients }} recipient{{ $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 {{ $campaign->email_sent_count }} &middot; SMS {{ $campaign->sms_sent_count }} &middot; Alerts {{ $campaign->portal_alert_count }} &middot; WhatsApp {{ $campaign->whatsapp_sent_count }}
                                </small>
                            </td>
                            <td>
                                <span class="badge {{ $campaign->failed_count > 0 ? 'text-bg-warning' : 'text-bg-success' }}">
                                    {{ ucwords(str_replace('_', ' ', $campaign->status)) }}
                                </span>
                                @if($campaign->failed_count > 0)
                                    <div class="small text-muted">{{ $campaign->failed_count }} failed</div>
                                @endif
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="5" class="text-center text-muted py-5">No notifications have been sent yet.</td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
            <div class="card-body">{{ $campaigns->links() }}</div>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('[data-notification-form]').forEach((form) => {
    const select = form.querySelector('[data-audience-select]');
    const panels = form.querySelectorAll('[data-audience-panel]');

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

    select.addEventListener('change', refresh);
    refresh();
});
</script>
@endsection
