@extends('layouts.app')

@section('title', 'Bulk SMS')
@section('page-title', 'Bulk SMS')
@section('page-subtitle', 'Send SMS campaigns to members or custom phone numbers')

@section('content')
@php
    $campaignPage = $campaigns->getCollection();
    $recipientsOnPage = $campaignPage->sum('total_recipients');
    $failedOnPage = $campaignPage->sum('failed_count');
@endphp

<section class="section-hero mb-4">
    <div class="section-hero-copy">
        <span>Account center</span>
        <h2>Bulk SMS campaigns</h2>
        <p>Send reminders, announcements, thrift notices, payment alerts, and custom SMS campaigns to members or external numbers.</p>
    </div>
    <div class="section-hero-panel">
        <span>SMS status</span>
        <strong>{{ $smsConfigured ? 'Ready' : 'Log mode' }}</strong>
        <small>{{ number_format($customers->count()) }} members with phone numbers</small>
    </div>
</section>

<div class="section-stat-grid mb-4">
    <div class="section-stat-card">
        <i class="bi bi-phone"></i>
        <span>Phone contacts</span>
        <strong>{{ number_format($customers->count()) }}</strong>
        <small>Members available for SMS</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-people"></i>
        <span>Recipients</span>
        <strong>{{ number_format($recipientsOnPage) }}</strong>
        <small>From listed campaigns</small>
    </div>
    <div class="section-stat-card">
        <i class="bi bi-exclamation-triangle"></i>
        <span>Failed</span>
        <strong>{{ number_format($failedOnPage) }}</strong>
        <small>Delivery issues</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-chat-dots"></i></span>
                <div>
                    <strong>New SMS campaign</strong>
                    <small>Uses the SMS gateway configured in tenant settings.</small>
                </div>
            </div>

            <form method="POST" action="{{ route('tenant.bulk-sms.store') }}" class="row g-3">
                @csrf
                <div class="col-12">
                    <label class="form-label">Campaign name</label>
                    <input name="subject" value="{{ old('subject') }}" class="form-control" placeholder="Loan repayment reminder" required>
                </div>

                <div class="col-12">
                    <label class="form-label">Audience</label>
                    <select name="audience_type" id="bulkSmsAudience" class="form-select" required>
                        <option value="all" @selected(old('audience_type', 'all') === 'all')>All members</option>
                        <option value="status" @selected(old('audience_type') === 'status')>Member status</option>
                        <option value="kyc" @selected(old('audience_type') === 'kyc')>KYC status</option>
                        <option value="individual" @selected(old('audience_type') === 'individual')>Selected members</option>
                        <option value="numbers" @selected(old('audience_type') === 'numbers')>Custom phone numbers</option>
                    </select>
                </div>

                <div class="col-12 audience-box" data-bulk-sms-section="status">
                    <label class="form-label">Member group</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 audience-box" data-bulk-sms-section="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 audience-box" data-bulk-sms-section="individual">
                    <label class="form-label">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 }}</option>
                        @endforeach
                    </select>
                    <div class="form-text">Hold Ctrl to select more than one member.</div>
                </div>

                <div class="col-12 audience-box" data-bulk-sms-section="numbers">
                    <label class="form-label">Phone numbers</label>
                    <textarea name="phone_numbers" class="form-control" rows="5" placeholder="Enter one number per line, or separate with commas">{{ old('phone_numbers') }}</textarea>
                </div>

                <div class="col-12">
                    <label class="form-label">Message</label>
                    <textarea name="message" id="bulkSmsMessage" class="form-control" rows="5" maxlength="918" placeholder="Type your SMS message" required>{{ old('message') }}</textarea>
                    <div class="sms-counter">
                        <span id="bulkSmsCount">0</span>/918 characters
                        <span class="mx-1">-</span>
                        <span id="bulkSmsUnits">1</span> SMS unit<span id="bulkSmsUnitsPlural"></span>
                    </div>
                    <div class="form-text">1 SMS is up to 160 characters. Longer messages use 153 characters per SMS page, so 2 pages = 306 and 3 pages = 459.</div>
                </div>

                <div class="col-12 d-grid">
                    <button class="btn btn-primary btn-lg"><i class="bi bi-send me-1"></i> Send bulk SMS</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>SMS campaign history</strong>
                    <small>Recent bulk messages sent or logged by the system.</small>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table section-table align-middle mb-0">
                    <thead><tr><th>Date</th><th>Campaign</th><th>Audience</th><th>Recipients</th><th>Status</th><th>Action</th></tr></thead>
                    <tbody>
                    @forelse($campaigns as $campaign)
                        @php
                            $lastSmsError = $campaign->recipients
                                ->pluck('sms_error')
                                ->filter()
                                ->first();
                        @endphp
                        <tr>
                            <td>{{ app_datetime($campaign->created_at) }}</td>
                            <td>
                                <div class="fw-semibold">{{ $campaign->subject }}</div>
                                <small class="text-muted">{{ str($campaign->message)->limit(80) }}</small>
                                @if($lastSmsError)
                                    <div class="small text-danger mt-1"><i class="bi bi-exclamation-circle me-1"></i>{{ str($lastSmsError)->limit(90) }}</div>
                                @endif
                            </td>
                            <td>{{ ucfirst(str_replace('_', ' ', $campaign->audience_type)) }}</td>
                            <td>
                                <div>{{ number_format($campaign->total_recipients) }} total</div>
                                <small class="text-muted">{{ number_format($campaign->sms_sent_count) }} sent/logged, {{ number_format($campaign->failed_count) }} failed</small>
                            </td>
                            <td><span class="badge text-bg-{{ $campaign->status === 'completed' ? 'success' : ($campaign->status === 'completed_with_errors' ? 'warning' : 'secondary') }}">{{ str_replace('_', ' ', ucfirst($campaign->status)) }}</span></td>
                            <td>
                                <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#bulkSmsCampaign{{ $campaign->id }}">
                                    <i class="bi bi-eye me-1"></i> View
                                </button>
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="6" class="text-center text-muted py-5">No bulk SMS campaigns yet.</td></tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
            @foreach($campaigns as $campaign)
                @php
                    $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="bulkSmsCampaign{{ $campaign->id }}" tabindex="-1" aria-labelledby="bulkSmsCampaign{{ $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="bulkSmsCampaign{{ $campaign->id }}Label">{{ $campaign->subject }}</h5>
                                    <div class="text-muted small">{{ app_datetime($campaign->created_at) }} - {{ 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">Sent/logged</span><div class="fw-semibold text-success">{{ number_format($campaign->sms_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 class="col-md-3"><div class="border rounded-3 p-3 h-100"><span class="text-muted small">SMS units per recipient</span><div class="fw-semibold">{{ number_format($messageUnits) }}</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 recipient</div>
                                </div>
                                <div class="table-responsive">
                                    <table class="table section-table align-middle mb-0">
                                        <thead><tr><th>Recipient</th><th>Phone</th><th>Status</th><th>Error / Delivery note</th></tr></thead>
                                        <tbody>
                                        @foreach($campaign->recipients as $recipient)
                                            <tr>
                                                <td>{{ $recipient->customer_name ?: 'Manual number' }}</td>
                                                <td>{{ $recipient->phone ?: '-' }}</td>
                                                <td>
                                                    <span class="badge text-bg-{{ in_array($recipient->sms_status, ['sent', 'logged'], true) ? 'success' : ($recipient->sms_status === 'failed' ? 'danger' : 'secondary') }}">
                                                        {{ ucfirst($recipient->sms_status ?: 'pending') }}
                                                    </span>
                                                </td>
                                                <td>
                                                    @if($recipient->sms_error)
                                                        <span class="text-danger">{{ $recipient->sms_error }}</span>
                                                    @else
                                                        <span class="text-muted">No error reported.</span>
                                                    @endif
                                                </td>
                                            </tr>
                                        @endforeach
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <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.addEventListener('DOMContentLoaded', () => {
    const audience = document.getElementById('bulkSmsAudience');
    const sections = document.querySelectorAll('[data-bulk-sms-section]');
    const message = document.getElementById('bulkSmsMessage');
    const count = document.getElementById('bulkSmsCount');
    const units = document.getElementById('bulkSmsUnits');
    const unitsPlural = document.getElementById('bulkSmsUnitsPlural');

    const toggleSections = () => {
        sections.forEach((section) => {
            section.classList.toggle('d-none', section.dataset.bulkSmsSection !== audience.value);
        });
    };

    const updateCount = () => {
        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';
    };

    audience.addEventListener('change', toggleSections);
    message.addEventListener('input', updateCount);
    toggleSections();
    updateCount();
});
</script>
@endsection
