@extends('layouts.app')
@section('title','Reminders & Notifications')
@section('content')
@php
    $filters = [];

    if(request()->filled('search')) {
        $filters[] = [
            'label' => 'Search',
            'value' => request('search'),
            'removeUrl' => route('notifications.index', request()->except(['search', 'page'])),
        ];
    }

    if(request()->filled('status')) {
        $filters[] = [
            'label' => 'Status',
            'value' => str((string) request('status'))->headline(),
            'removeUrl' => route('notifications.index', request()->except(['status', 'page'])),
        ];
    }

    if(request()->filled('channel')) {
        $filters[] = [
            'label' => 'Channel',
            'value' => str((string) request('channel'))->replace('_', ' ')->headline(),
            'removeUrl' => route('notifications.index', request()->except(['channel', 'page'])),
        ];
    }

    if(request()->filled('type')) {
        $filters[] = [
            'label' => 'Reminder',
            'value' => str((string) request('type'))->replace('_', ' ')->headline(),
            'removeUrl' => route('notifications.index', request()->except(['type', 'page'])),
        ];
    }

    if(request()->filled('date_from')) {
        $filters[] = [
            'label' => 'From',
            'value' => \Carbon\CarbonImmutable::parse(request('date_from'))->format('d M Y'),
            'removeUrl' => route('notifications.index', request()->except(['date_from', 'page'])),
        ];
    }

    if(request()->filled('date_to')) {
        $filters[] = [
            'label' => 'To',
            'value' => \Carbon\CarbonImmutable::parse(request('date_to'))->format('d M Y'),
            'removeUrl' => route('notifications.index', request()->except(['date_to', 'page'])),
        ];
    }

    $totalNotifications = collect(['delivered', 'failed', 'pending'])
        ->sum(fn ($key) => (int) ($summary[$key] ?? 0));
@endphp

<x-ui.page-toolbar
    title="Reminders & Notifications"
    description="Review repayment reminder delivery across your assigned branches, including provider failures and retries."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Reminders & Notifications']]"
>
    @can('notifications.manage')
        <x-slot:actions>
            <a class="mf-btn" href="{{ route('notification-settings.edit') }}">Reminder settings</a>
        </x-slot:actions>
    @endcan
</x-ui.page-toolbar>

<x-ui.quick-status-tabs :tabs="[
    ['label' => 'All', 'value' => '', 'count' => $totalNotifications],
    ['label' => 'Delivered', 'value' => 'delivered', 'count' => (int) ($summary['delivered'] ?? 0)],
    ['label' => 'Failed', 'value' => 'failed', 'count' => (int) ($summary['failed'] ?? 0)],
    ['label' => 'Pending', 'value' => 'pending', 'count' => (int) ($summary['pending'] ?? 0)],
]" />

<x-ui.table-toolbar
    table-id="notification-delivery-table"
    search-placeholder="Search customer, loan, phone or message…"
    :filter-names="['channel', 'type', 'date_from', 'date_to']"
    :columns="[
        'date' => 'Date',
        'customer' => 'Customer / loan',
        'reminder' => 'Reminder',
        'channel' => 'Channel / recipient',
        'message' => 'Message',
        'status' => 'Status',
        'provider' => 'Provider result',
        'actions' => 'Actions',
    ]"
    export-filename="reminder-notifications.csv"
>
    <x-slot:filters>
        <select class="mf-filter-control" name="channel" aria-label="Filter by delivery channel">
            <option value="">All channels</option>
            @foreach(['in_system'=>'In-system','sms'=>'SMS','whatsapp'=>'WhatsApp','email'=>'Email'] as $value=>$label)
                <option value="{{ $value }}" @selected($channel === $value)>{{ $label }}</option>
            @endforeach
        </select>

        <select class="mf-filter-control" name="type" aria-label="Filter by reminder type">
            <option value="">All reminders</option>
            @foreach(['pre_due'=>'Pre-due','due'=>'Due date','overdue'=>'Overdue'] as $value=>$label)
                <option value="{{ $value }}" @selected($type === $value)>{{ $label }}</option>
            @endforeach
        </select>

        <input
            type="date"
            class="mf-filter-control"
            name="date_from"
            value="{{ request('date_from') }}"
            aria-label="From date"
            title="From date"
        >

        <input
            type="date"
            class="mf-filter-control"
            name="date_to"
            value="{{ request('date_to') }}"
            aria-label="To date"
            title="To date"
        >
    </x-slot:filters>
</x-ui.table-toolbar>

<x-ui.applied-filter-chips :filters="$filters" :clear-url="route('notifications.index')" />

<div class="mb-2 flex flex-wrap items-end justify-between gap-2">
    <div>
        <h2 class="text-sm font-semibold">Delivery log</h2>
        <p class="mt-0.5 text-xs text-muted-foreground">Generated messages are permanent records. Failed deliveries are never shown as delivered.</p>
    </div>
</div>

<div class="mf-table-frame">
    <table id="notification-delivery-table" class="mf-table" data-standard-table>
        <thead>
            <tr>
                <th data-table-column="date">Date</th>
                <th data-table-column="customer">Customer / loan</th>
                <th data-table-column="reminder">Reminder</th>
                <th data-table-column="channel">Channel / recipient</th>
                <th data-table-column="message">Message</th>
                <th data-table-column="status">Status</th>
                <th data-table-column="provider">Provider result</th>
                <th data-table-column="actions"><span class="sr-only">Actions</span></th>
            </tr>
        </thead>
        <tbody>
            @forelse($logs as $log)
                <tr>
                    <td data-table-column="date">
                        {{ $log->scheduled_for->format('d M Y') }}
                        <div class="text-xs text-muted-foreground">Attempt{{ $log->attempts === 1 ? '' : 's' }}: {{ $log->attempts }}</div>
                    </td>
                    <td data-table-column="customer">
                        <div class="font-medium">{{ $log->customer->full_name }}</div>
                        <div class="text-xs text-muted-foreground">{{ $log->customer->customer_number }} · {{ $log->loan->loan_number }}</div>
                    </td>
                    <td data-table-column="reminder">
                        {{ str($log->reminder_type)->replace('_', ' ')->title() }}
                        <div class="text-xs text-muted-foreground">
                            Installment #{{ $log->installment->installment_number }} ·
                            {{ $log->days_from_due > 0 ? $log->days_from_due.'d overdue' : ($log->days_from_due < 0 ? abs($log->days_from_due).'d before' : 'due today') }}
                        </div>
                    </td>
                    <td data-table-column="channel">
                        {{ str($log->channel)->replace('_', ' ')->title() }}
                        <div class="text-xs text-muted-foreground">{{ $log->recipient }}</div>
                    </td>
                    <td data-table-column="message" class="max-w-xs">
                        <div title="{{ $log->message }}">{{ str($log->message)->limit(110) }}</div>
                        @if($log->subject)
                            <div class="mt-1 text-xs text-muted-foreground">{{ $log->subject }}</div>
                        @endif
                    </td>
                    <td data-table-column="status">
                        <span class="mf-badge {{ $log->status === 'delivered' ? 'mf-badge-success' : ($log->status === 'failed' ? 'mf-badge-destructive' : 'mf-badge-muted') }}">
                            {{ ucfirst($log->status) }}
                        </span>
                        @if($log->delivered_at)
                            <div class="mt-1 text-xs text-muted-foreground">{{ $log->delivered_at->format('d M H:i') }}</div>
                        @endif
                    </td>
                    <td data-table-column="provider" class="max-w-xs text-xs">
                        @if($log->error)
                            <span class="text-destructive" title="{{ $log->error }}">{{ str($log->error)->limit(90) }}</span>
                        @elseif($log->provider_response)
                            <span class="text-muted-foreground" title="{{ $log->provider_response }}">{{ str($log->provider_response)->limit(90) }}</span>
                        @else
                            <span class="text-muted-foreground">—</span>
                        @endif
                    </td>
                    <td data-table-column="actions" class="text-right">
                        @if($log->status === 'failed')
                            @can('retry', $log)
                                <form method="POST" action="{{ route('notifications.retry', $log) }}">
                                    @csrf
                                    <button class="mf-btn mf-btn-sm">Retry</button>
                                </form>
                            @endcan
                        @endif
                    </td>
                </tr>
            @empty
                <tr>
                    <td colspan="8" class="text-center text-muted-foreground">No reminder notifications have been generated yet.</td>
                </tr>
            @endforelse
        </tbody>
    </table>
</div>

<div class="mt-4">{{ $logs->links() }}</div>
@endsection
