@extends('layouts.app')

@section('title', 'Campañas de correo')
@section('page-title', 'Correo y automatizaciones')

@section('page-actions')
<div class="d-flex gap-2">
    <a href="{{ route('admin.dashboard') }}" class="btn btn-sm btn-outline-secondary">
        <i class="fas fa-arrow-left me-1"></i> Dashboard
    </a>
    <a href="{{ route('admin.mensajes') }}" class="btn btn-sm btn-outline-primary">
        <i class="fas fa-inbox me-1"></i> Mensajes
    </a>
</div>
@endsection

@section('content')
@php use Illuminate\Support\Str; @endphp
@php
    $estadoOptions = collect($resumenEstados)
        ->pluck('estado')
        ->filter()
        ->unique()
        ->mapWithKeys(fn($estado) => [$estado => ucfirst($estado)])
        ->toArray();

    $estadoOptions = ['todos' => 'Todos'] + $estadoOptions + ['pendiente' => 'Pendiente', 'contactado' => 'Contactado', 'completado' => 'Completado'];
    $estadoOptions = collect($estadoOptions)
        ->mapWithKeys(fn($label, $value) => [$value => ucfirst($label)])
        ->unique()
        ->toArray();

    if (!array_key_exists('todos', $estadoOptions)) {
        $estadoOptions = ['todos' => 'Todos'] + $estadoOptions;
    }

    $ordenOptions = [
        'recientes' => 'Más recientes',
        'presupuesto' => 'Mayor presupuesto',
        'cantidad' => 'Mayor cantidad de scawatts',
        'antiguedad' => 'Más antiguas',
    ];
@endphp

<div class="row g-3 mb-1">
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Solicitudes totales</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['total']) }}</h4>
                    </div>
                    <span class="icon-circle bg-secondary-subtle text-secondary"><i class="fas fa-envelope-open-text"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Pendientes por contactar</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['pendientes']) }}</h4>
                    </div>
                    <span class="icon-circle bg-warning-subtle text-warning"><i class="fas fa-phone-volume"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Contactadas</p>
                        <h4 class="fw-semibold mb-0">{{ number_format($stats['contactadas']) }}</h4>
                    </div>
                    <span class="icon-circle bg-success-subtle text-success"><i class="fas fa-handshake"></i></span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <p class="text-muted text-uppercase small mb-1">Presupuesto proyectado</p>
                        <h4 class="fw-semibold mb-0">{{ $stats['presupuesto_total'] }}</h4>
                    </div>
                    <span class="icon-circle bg-info-subtle text-info"><i class="fas fa-coins"></i></span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-3">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-xxl-3 col-lg-4 col-md-4">
                <label for="estado" class="form-label small text-uppercase text-muted mb-1">Estado</label>
                <select id="estado" name="estado" class="form-select form-select-sm">
                    @foreach($estadoOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['estado'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xxl-3 col-lg-4 col-md-4">
                <label for="orden" class="form-label small text-uppercase text-muted mb-1">Ordenar por</label>
                <select id="orden" name="orden" class="form-select form-select-sm">
                    @foreach($ordenOptions as $value => $label)
                        <option value="{{ $value }}" @selected($filtros['orden'] === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-xxl-3 col-lg-4 col-md-4">
                <label for="q" class="form-label small text-uppercase text-muted mb-1">Buscar</label>
                <input type="search" id="q" name="q" value="{{ $filtros['q'] }}" class="form-control form-control-sm" placeholder="Nombre, correo, teléfono o mensaje">
            </div>
            <div class="col-xxl-2 col-lg-3 col-md-4">
                <label for="por_pagina" class="form-label small text-uppercase text-muted mb-1">Por página</label>
                <input type="number" min="5" max="80" id="por_pagina" name="por_pagina" value="{{ $filtros['por_pagina'] }}" class="form-control form-control-sm">
            </div>
            <div class="col-xxl-1 col-lg-2 col-md-4 d-flex gap-2">
                <button type="submit" class="btn btn-sm btn-primary flex-fill">
                    <i class="fas fa-filter me-1"></i> Aplicar
                </button>
                <a href="{{ route('admin.correos') }}" class="btn btn-sm btn-outline-secondary" title="Limpiar filtros">
                    <i class="fas fa-rotate-right"></i>
                </a>
            </div>
        </form>
    </div>
</div>

<div class="row g-3">
    <div class="col-xxl-9">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <div>
                    <h6 class="mb-0">Solicitudes recibidas</h6>
                    <small class="text-muted">Mostrando {{ $solicitudes->firstItem() ?? 0 }}-{{ $solicitudes->lastItem() ?? 0 }} de {{ $solicitudes->total() }} registros</small>
                </div>
                <span class="badge bg-secondary-subtle text-secondary">{{ strtoupper($filtros['estado']) }}</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Solicitante</th>
                                <th class="text-center">Scawatts</th>
                                <th class="text-center">Presupuesto</th>
                                <th class="text-center">Estado</th>
                                <th>Seguimiento</th>
                                <th class="text-end">Registro</th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($solicitudes as $solicitud)
                            @php
                                $estado = $solicitud->estado ?? 'pendiente';
                                $badgeClass = match ($estado) {
                                    'contactado' => 'bg-info',
                                    'completado' => 'bg-success',
                                    'cancelado' => 'bg-danger',
                                    default => 'bg-warning text-dark',
                                };
                                $presupuesto = $solicitud->presupuesto_aproximado !== null
                                    ? '$' . number_format((float) $solicitud->presupuesto_aproximado, 0, ',', '.')
                                    : '—';
                            @endphp
                            <tr>
                                <td>
                                    <div class="fw-semibold">{{ $solicitud->nombre_completo ?? 'Sin nombre' }}</div>
                                    <small class="text-muted d-block">{{ $solicitud->email ?? '—' }} · {{ $solicitud->telefono ?? '—' }}</small>
                                    @if($solicitud->mensaje)
                                        <small class="text-muted d-block">{{ Str::limit($solicitud->mensaje, 120) }}</small>
                                    @endif
                                    @if($solicitud->usuario)
                                        <div class="small mt-1 text-muted">Usuario: {{ $solicitud->usuario->nombre }} ({{ $solicitud->usuario->email }})</div>
                                    @endif
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-light text-dark">{{ number_format($solicitud->cantidad_scawatts ?? 0) }}</span>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-light text-dark">{{ $presupuesto }}</span>
                                </td>
                                <td class="text-center">
                                    <span class="badge {{ $badgeClass }} text-uppercase">{{ ucfirst($estado) }}</span>
                                </td>
                                <td>
                                    <small class="text-muted d-block">Atiende: {{ $solicitud->adminAtendio->nombre ?? '—' }}</small>
                                    <small class="text-muted d-block">Contacto: {{ $solicitud->fecha_contacto?->format('d M Y H:i') ?? 'No registrado' }}</small>
                                    @if($solicitud->notas_admin)
                                        <small class="text-muted d-block">Notas: {{ Str::limit($solicitud->notas_admin, 100) }}</small>
                                    @endif
                                </td>
                                <td class="text-end">
                                    <div class="fw-semibold">{{ $solicitud->created_at?->format('d M Y H:i') ?? 'N/D' }}</div>
                                    <small class="text-muted">{{ $solicitud->created_at?->diffForHumans() ?? '—' }}</small>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="text-center text-muted py-5">No encontramos registros para los filtros seleccionados.</td>
                            </tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-white border-0">
                {{ $solicitudes->links('pagination::bootstrap-5') }}
            </div>
        </div>
    </div>
    <div class="col-xxl-3">
        <div class="card shadow-sm border-0 mb-3">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Últimas solicitudes</h6>
                <span class="badge bg-secondary-subtle text-secondary">{{ $ultimas->count() }}</span>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @forelse($ultimas as $reciente)
                        <li class="list-group-item">
                            <div class="fw-semibold">{{ $reciente->nombre_completo ?? 'Sin nombre' }}</div>
                            <small class="text-muted d-block">{{ $reciente->created_at?->diffForHumans() ?? '—' }}</small>
                            <small class="text-muted">Solicita {{ number_format($reciente->cantidad_scawatts ?? 0) }} scawatts</small>
                        </li>
                    @empty
                        <li class="list-group-item text-center text-muted py-4">Sin movimientos recientes.</li>
                    @endforelse
                </ul>
            </div>
        </div>

        <div class="card shadow-sm border-0">
            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                <h6 class="mb-0">Estado de solicitudes</h6>
                <span class="badge bg-dark-subtle text-dark">{{ $resumenEstados->sum('total') }}</span>
            </div>
            <div class="card-body">
                @forelse($resumenEstados as $resumen)
                    <div class="d-flex justify-content-between align-items-center py-2 border-bottom">
                        <div class="fw-semibold">{{ ucfirst($resumen->estado ?? 'sin estado') }}</div>
                        <span class="badge bg-light text-dark">{{ $resumen->total }}</span>
                    </div>
                @empty
                    <p class="text-muted mb-0">Sin datos disponibles.</p>
                @endforelse
            </div>
        </div>
    </div>
</div>
@endsection
