@extends('layouts.app')

@section('title', 'Email Logs')
@section('page-title', 'Email Logs')
@section('page-subtitle', 'Track platform emails sent from Super Admin to tenants and other platform recipients')

@section('content')
@php
    $statusClasses = [
        'sent' => 'text-bg-success',
        'failed' => 'text-bg-danger',
        'skipped' => 'text-bg-secondary',
    ];
    $sourceLabel = fn (?string $source) => $source ? str($source)->replace('_', ' ')->title() : 'All sources';
    $statCards = [
        ['Sent today', number_format($stats['today_sent'] ?? 0), 'Successful emails today', 'bi-send-check', 'green'],
        ['Failed today', number_format($stats['today_failed'] ?? 0), 'Needs attention today', 'bi-exclamation-triangle', 'rose'],
        ['All failures', number_format($stats['failed_total'] ?? 0), 'Total failed attempts', 'bi-bug', 'amber'],
        ['Total logs', number_format($stats['total'] ?? 0), 'All recorded email attempts', 'bi-envelope-paper', 'blue'],
    ];
@endphp

<style>
    .email-log-card{border:0;border-radius:18px;box-shadow:0 16px 45px rgba(15,23,42,.08)}
    .email-stat-card{border:0;border-radius:18px;color:#fff;overflow:hidden;min-height:126px}
    .email-stat-card.green{background:linear-gradient(135deg,#047857,#22c55e)}
    .email-stat-card.rose{background:linear-gradient(135deg,#be123c,#fb7185)}
    .email-stat-card.amber{background:linear-gradient(135deg,#b45309,#f59e0b)}
    .email-stat-card.blue{background:linear-gradient(135deg,#1d4ed8,#38bdf8)}
    .email-stat-card .card-body{display:flex;justify-content:space-between;gap:1rem}
    .email-stat-card i{font-size:2rem;opacity:.85}
    .email-log-subject{max-width:320px}
    .email-log-error{max-width:260px}
    .email-filter-grid{display:grid;grid-template-columns:minmax(220px,1.5fr) repeat(5,minmax(150px,1fr)) auto;gap:.75rem;align-items:end}
    @media (max-width: 1199.98px){.email-filter-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
    @media (max-width: 575.98px){.email-filter-grid{grid-template-columns:1fr}}
</style>

<div class="row g-3 mb-4">
    @foreach($statCards as [$label, $value, $hint, $icon, $tone])
        <div class="col-md-6 col-xl-3">
            <div class="card email-stat-card {{ $tone }}">
                <div class="card-body">
                    <div>
                        <div class="small text-white-50">{{ $label }}</div>
                        <div class="display-6 fw-bold mb-1">{{ $value }}</div>
                        <div class="small">{{ $hint }}</div>
                    </div>
                    <i class="bi {{ $icon }}"></i>
                </div>
            </div>
        </div>
    @endforeach
</div>

<div class="card email-log-card mb-4">
    <div class="card-body">
        <div class="d-flex justify-content-between align-items-start gap-3 mb-3">
            <div>
                <h2 class="h5 mb-1">Filter Email Activity</h2>
                <div class="text-muted small">Search by recipient, tenant, subject, message, or SMTP error.</div>
            </div>
            <a href="{{ route('super.email-logs.index') }}" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-counterclockwise me-1"></i>Reset</a>
        </div>
        <form method="GET" class="email-filter-grid">
            <div>
                <label class="form-label">Search</label>
                <input name="q" value="{{ $filters['q'] ?? '' }}" class="form-control" placeholder="Tenant, email, subject, error...">
            </div>
            <div>
                <label class="form-label">Status</label>
                <select name="status" class="form-select">
                    <option value="">All statuses</option>
                    @foreach(['sent' => 'Sent', 'failed' => 'Failed', 'skipped' => 'Skipped'] as $value => $label)
                        <option value="{{ $value }}" @selected(($filters['status'] ?? '') === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="form-label">Source</label>
                <select name="source" class="form-select">
                    <option value="">All sources</option>
                    @foreach($sources as $source)
                        <option value="{{ $source }}" @selected(($filters['source'] ?? '') === $source)>{{ $sourceLabel($source) }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="form-label">Tenant</label>
                <select name="tenant_id" class="form-select">
                    <option value="">All tenants</option>
                    @foreach($tenants as $tenant)
                        <option value="{{ $tenant->id }}" @selected((string) ($filters['tenant_id'] ?? '') === (string) $tenant->id)>{{ $tenant->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label class="form-label">From</label>
                <input name="from" type="date" value="{{ $filters['from'] ?? '' }}" class="form-control">
            </div>
            <div>
                <label class="form-label">To</label>
                <input name="to" type="date" value="{{ $filters['to'] ?? '' }}" class="form-control">
            </div>
            <div>
                <button class="btn btn-primary w-100"><i class="bi bi-search me-1"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="card email-log-card">
    <div class="card-body">
        <div class="d-flex justify-content-between align-items-center gap-3 mb-3">
            <div>
                <h2 class="h5 mb-1">Delivery Timeline</h2>
                <div class="text-muted small">Showing platform email attempts sent from Super Admin workflows.</div>
            </div>
            <span class="badge text-bg-light border">{{ number_format($logs->total()) }} records</span>
        </div>

        <div class="table-responsive">
            <table class="table align-middle">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Recipient</th>
                        <th>Tenant</th>
                        <th>Source</th>
                        <th>Subject</th>
                        <th>Status</th>
                        <th>Error</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($logs as $log)
                        <tr>
                            <td>
                                <div class="fw-semibold">{{ app_datetime($log->created_at) }}</div>
                                <div class="small text-muted">{{ $log->mailer ?: '-' }} {{ $log->smtp_host ? '· '.$log->smtp_host : '' }}</div>
                            </td>
                            <td>
                                <div class="fw-semibold">{{ $log->recipient_name ?: '-' }}</div>
                                <div class="small text-muted">{{ $log->recipient_email ?: '-' }}</div>
                            </td>
                            <td>{{ $log->tenant?->name ?? '-' }}</td>
                            <td><span class="badge text-bg-light border">{{ $log->sourceLabel() }}</span></td>
                            <td>
                                <div class="fw-semibold email-log-subject text-truncate">{{ $log->subject }}</div>
                                <div class="small text-muted email-log-subject text-truncate">{{ str($log->body)->limit(90) }}</div>
                            </td>
                            <td><span class="badge {{ $statusClasses[$log->status] ?? 'text-bg-secondary' }}">{{ $log->statusLabel() }}</span></td>
                            <td>
                                <div class="small text-danger email-log-error text-truncate">{{ $log->error_message ?: '-' }}</div>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#emailLog{{ $log->id }}">
                                    View
                                </button>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" class="text-center text-muted py-5">
                                <i class="bi bi-envelope-open d-block display-6 mb-2"></i>
                                No email delivery logs match this filter.
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

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

@foreach($logs as $log)
    <div class="modal fade" id="emailLog{{ $log->id }}" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <div>
                        <h5 class="modal-title">{{ $log->subject }}</h5>
                        <div class="small text-muted">{{ app_datetime($log->created_at) }} · {{ $log->sourceLabel() }}</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-6"><div class="border rounded p-3 h-100"><div class="small text-muted">Recipient</div><strong>{{ $log->recipient_name ?: '-' }}</strong><div>{{ $log->recipient_email ?: '-' }}</div></div></div>
                        <div class="col-md-3"><div class="border rounded p-3 h-100"><div class="small text-muted">Status</div><span class="badge {{ $statusClasses[$log->status] ?? 'text-bg-secondary' }}">{{ $log->statusLabel() }}</span></div></div>
                        <div class="col-md-3"><div class="border rounded p-3 h-100"><div class="small text-muted">Tenant</div><strong>{{ $log->tenant?->name ?? '-' }}</strong></div></div>
                    </div>
                    <div class="mb-3">
                        <div class="small text-muted mb-1">Message</div>
                        <pre class="bg-light border rounded p-3 mb-0" style="white-space:pre-wrap;font-family:inherit">{{ $log->body ?: '-' }}</pre>
                    </div>
                    @if($log->error_message)
                        <div class="alert alert-danger mb-0">
                            <div class="fw-semibold mb-1">Delivery error</div>
                            <div>{{ $log->error_message }}</div>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
@endforeach
@endsection
