@extends('layouts.yellow')
@section('content')
<style>
    :root {
        --azul-primario: #2A4E6D;
        --azul-secundario: #3B6EA5;
        --azul-destacado: #4A90E2;
        --azul-suave: #E3F2FD;
        --degradado-azul: linear-gradient(135deg, #4A90E2 0%, #2A4E6D 100%);
        --verde-exito: #28a745;
        --naranja-advertencia: #fd7e14;
        --rojo-peligro: #dc3545;
    }

    .container-dashboard {
        padding: 1.25rem;
    }

    .dashboard-header {
        background: var(--degradado-azul);
        border-radius: 14px;
        padding: 1.35rem;
        color: white;
        box-shadow: 0 8px 30px rgba(42, 78, 109, 0.15);
        margin-bottom: 1.75rem;
    }

    .stat-card {
        background: white;
        border-radius: 14px;
        padding: 1.35rem;
        position: relative;
        overflow: hidden;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border-left: 4px solid var(--azul-primario);
        box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        height: 100%;
    }

    .stat-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 10px 30px rgba(42, 78, 109, 0.15);
    }

    .stat-icon {
        width: 54px;
        height: 54px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 10px;
        background: var(--azul-suave);
        margin-bottom: 0.9rem;
    }

    .chart-container {
        background: white;
        border-radius: 14px;
        padding: 1.35rem;
        box-shadow: 0 4px 20px rgba(42, 78, 109, 0.08);
    }

    .dashboard-btn-group .btn {
        border-radius: 8px;
        padding: 0.65rem 1.35rem;
        font-weight: 600;
        transition: all 0.3s ease;
    }
    
    .dashboard-btn-group .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .quick-action-card {
        background: white;
        border-radius: 14px;
        padding: 1.3rem 1rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        transition: all 0.3s ease;
        text-align: center;
        cursor: pointer;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-bottom: 0.5rem;
    }
    
    .quick-action-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.1);
    }
    
    .quick-action-icon {
        width: 52px;
        height: 52px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 1rem auto;
        border-radius: 50%;
        font-size: 1.5rem;
        color: white;
    }
    
    .upcoming-appointment-card {
        border-left: 4px solid var(--azul-destacado);
        border-radius: 10px;
        padding: 0.9rem;
        background: white;
        margin-bottom: 1rem;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
    }
    
    .upcoming-appointment-card:hover {
        box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        transform: translateX(3px);
    }
    
    .appointment-time {
        background: var(--azul-suave);
        color: var(--azul-primario);
        padding: 0.45rem 0.65rem;
        border-radius: 8px;
        font-weight: 600;
        font-size: 0.9rem;
        margin-right: 1rem;
        text-align: center;
        min-width: 75px;
    }
    
    .appointment-details {
        flex-grow: 1;
    }

    .section-title {
        position: relative;
        padding-bottom: 0.45rem;
        margin-bottom: 1.35rem;
        font-weight: 600;
        color: var(--azul-primario);
        font-size: 1.2rem;
    }
    
    .section-title::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 45px;
        height: 3px;
        background: var(--azul-destacado);
        border-radius: 3px;
    }
    
    .status-tag {
        display: inline-block;
        padding: 0.22rem 0.65rem;
        border-radius: 50px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
    }
    
    .status-tag.pending {
        background-color: rgba(255, 193, 7, 0.15);
        color: #ff9800;
    }
    
    .status-tag.scheduled {
        background-color: rgba(33, 150, 243, 0.15);
        color: #2196f3;
    }
    
    .status-tag.completed {
        background-color: rgba(76, 175, 80, 0.15);
        color: #4caf50;
    }
    
    .welcome-greeting {
        font-size: 1.9rem;
        font-weight: 700;
        margin-bottom: 0.4rem;
        text-shadow: 1px 1px 3px rgba(0,0,0,0.2);
    }
    
    @media (max-width: 768px) {
        .welcome-greeting {
            font-size: 1.5rem;
        }
        
        .stat-card {
            margin-bottom: 1.2rem;
        }
        
        .dashboard-btn-group .btn {
            width: 100%;
            margin-bottom: 0.5rem;
        }
        
        .quick-action-card {
            margin-bottom: 1rem;
            padding: 1.2rem 0.8rem;
        }
        
        .quick-action-icon {
            width: 48px;
            height: 48px;
            margin-bottom: 0.8rem;
        }
    }

    /* Añadimos esta clase para tener 5 elementos equidistantes */
    @media (min-width: 992px) {
        .col-lg-2-4 {
            flex: 0 0 20%;
            max-width: 20%;
            padding-left: 15px;
            padding-right: 15px;
        }
    }

    /* Podemos agregar un separador visual entre secciones */
    .section-separator {
        height: 1px;
        background: linear-gradient(to right, rgba(74, 144, 226, 0.1), rgba(74, 144, 226, 0.5), rgba(74, 144, 226, 0.1));
        margin: 1.5rem 0 2.5rem;
        border-radius: 2px;
    }

    /* Ajustamos los márgenes entre secciones */
    .section-margin-large {
        margin-bottom: 3rem;
    }

    .section-margin-medium {
        margin-bottom: 2.5rem;
    }
</style>

<div class="container-fluid container-dashboard">
    <!-- Encabezado mejorado -->
    <div class="dashboard-header d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center">
        <div class="mb-3 mb-md-0">
            @php
                $identity = \App\Helper\ClinicIdentityHelper::getActiveIdentity();
            @endphp
            
            <h1 class="welcome-greeting">{{ __('dashboard.welcome') }}, {{ Auth::user()->name }}</h1>
            <div class="d-flex align-items-center mb-2">
                <i class="bi bi-calendar-event me-2"></i>
                <span>{{ \Carbon\Carbon::now()->isoFormat('dddd, D [de] MMMM [de] YYYY') }}</span>
            </div>
            
            @if($identity)
                <div class="d-flex flex-column align-items-start mt-3">
                    <h2 class="m-0 text-break" style="font-size: min(1.8rem, 5vw); font-weight: 700; color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.2); line-height: 1.2; padding-bottom: 5px;">
                        {{ $identity->name }}
                    </h2>
                    @if($identity->specialty)
                        <span class="mt-1 badge bg-light text-dark">{{ $identity->specialty }}</span>
                    @endif
                </div>
            @endif
        </div>
        <div class="dashboard-btn-group">
        @php $accessMode = \App\Models\Settings::getAccessMode(); @endphp

            @if(in_array(\App\Models\Settings::APPOINTMENT_ONLY_MODE, $accessMode) || in_array(\App\Models\Settings::FULL_ACCESS_MODE, $accessMode))
            <a href="{{URL::to('/admin/create-appointment')}}" class="btn btn-light me-2">
                <i class="bi bi-calendar-plus me-2"></i>
                {{__("view-appointments.create")}}
            </a>
            @endif
            <a href="{{URL::to('/admin/create-patient')}}" class="btn btn-outline-light">
                <i class="bi bi-person-plus me-2"></i>
                {{__("view-patients.create")}}
            </a>
        </div>
    </div>

    @if(isset($paymentTotals) && count($paymentTotals) > 0)
    <!-- Totales por moneda como etiquetas destacadas después del header -->
    <!--<div class="mb-4">
        <div class="d-flex flex-wrap gap-2 justify-content-end">
            @foreach($paymentTotals as $paymentTotal)
            <div class="badge bg-primary py-2 px-3" style="font-size: 1rem; background: var(--degradado-azul) !important;">
                <i class="bi bi-currency-exchange me-1"></i>
                <span class="fw-bold">{{ $paymentTotal['currency'] }}:</span> 
                {{ number_format($paymentTotal['total'], 2) }}
            </div>
            @endforeach
        </div>
    </div> -->
    @endif

    <!-- Tarjetas de estadísticas mejoradas -->
    <div class="row g-4 section-margin-large">
        <div class="col-12 col-md-6 col-lg-3">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="bi bi-people-fill text-azul-primario" style="font-size: 1.5rem;"></i>
                </div>
                <h6 class="text-muted mb-1">{{__('dashboard.patientRegistered')}}</h6>
                <div class="d-flex align-items-end">
                    <h3 class="mb-0 fw-bold text-azul-primario">{{ $patientsMinorThat18 + $patientsMajorThat18 }}</h3>
                </div>
                <small class="text-muted">{{ $patientsMinorThat18 }} menores / {{ $patientsMajorThat18 }} adultos</small>
            </div>
        </div>

        @if(in_array(\App\Models\Settings::APPOINTMENT_ONLY_MODE, $accessMode) || in_array(\App\Models\Settings::FULL_ACCESS_MODE, $accessMode))
        <div class="col-12 col-md-6 col-lg-3">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="bi bi-calendar-check text-azul-primario" style="font-size: 1.5rem;"></i>
                </div>
                <h6 class="text-muted mb-1">{{__('dashboard.appointmentsToday')}}</h6>
                <div class="d-flex align-items-end">
                    <h3 class="mb-0 fw-bold text-azul-primario">{{ $appointmentsToday }}</h3>
                    @if($appointmentsToday > 0)
                        <small class="ms-2 text-success">
                            <i class="bi bi-arrow-up-short"></i> 
                            {{__('dashboard.active')}}
                        </small>
                    @endif
                </div>
                <small class="text-muted">Para hoy {{ \Carbon\Carbon::now()->format('d/m/Y') }}</small>
            </div>
        </div>

        <div class="col-12 col-md-6 col-lg-3">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="bi bi-bar-chart-line text-azul-primario" style="font-size: 1.5rem;"></i>
                </div>
                <h6 class="text-muted mb-1">{{__('dashboard.appointmentsViews')}}</h6>
                <div class="d-flex align-items-end">
                    <h3 class="mb-0 fw-bold text-azul-primario">{{ $appointmentsViews }}</h3>
                    @if($appointmentsViews > 0)
                        <small class="ms-2 text-success">
                            <i class="bi bi-check-circle-fill"></i> 
                            {{__('dashboard.completed')}}
                        </small>
                    @endif
                </div>
                <small class="text-muted">Consultas completadas</small>
            </div>
        </div>
        
        <div class="col-12 col-md-6 col-lg-3">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="bi bi-clock-history text-azul-primario" style="font-size: 1.5rem;"></i>
                </div>
                <h6 class="text-muted mb-1">Próxima Cita</h6>
                @if($appointmentsToday > 0)
                    @php
                        $nextAppointment = \App\Models\Appointments::where("active", "1")
                            ->whereDate('date', \Carbon\Carbon::today())
                            ->where('date', '>=', \Carbon\Carbon::now())
                            ->orderBy('date', 'asc')
                            ->first();
                        
                        if (!$nextAppointment) {
                            $nextAppointment = \App\Models\Appointments::where("active", "1")
                                ->whereDate('date', \Carbon\Carbon::today())
                                ->orderBy('date', 'asc')
                                ->first();
                        }
                        
                        $hora = $nextAppointment ? (new DateTime($nextAppointment->date))->format('H:i') : '-';
                    @endphp
                    <h3 class="mb-0 fw-bold text-azul-primario">{{ $hora }}</h3>
                    <small class="text-muted">{{ __('dashboard.today') }}</small>
                @else
                    <h3 class="mb-0 fw-bold text-azul-primario">-</h3>
                    <small class="text-muted">Sin citas programadas</small>
                @endif
            </div>
        </div>
        @endif
    </div>

    <div class="section-separator"></div>

    <!-- Acciones Rápidas -->
    <div class="row section-margin-large">
        <div class="col-12 mb-3">
            <h5 class="section-title">Acciones Rápidas</h5>
        </div>
        <div class="col-6 col-md-4 col-lg-2-4 mb-4">
            <a href="{{URL::to('/admin/view-appointments')}}" class="text-decoration-none">
                <div class="quick-action-card">
                    <div class="quick-action-icon" style="background-color: #4A90E2;">
                        <i class="bi bi-calendar-week"></i>
                    </div>
                    <h6 class="mb-0">Citas</h6>
                </div>
            </a>
        </div>
        <div class="col-6 col-md-4 col-lg-2-4 mb-4">
            <a href="{{URL::to('/admin/view-patients')}}" class="text-decoration-none">
                <div class="quick-action-card">
                    <div class="quick-action-icon" style="background-color: #28a745;">
                        <i class="bi bi-person-lines-fill"></i>
                    </div>
                    <h6 class="mb-0">Pacientes</h6>
                </div>
            </a>
        </div>
        <div class="col-6 col-md-4 col-lg-2-4 mb-4">
            <a href="{{URL::to('/admin/clinic-identity')}}" class="text-decoration-none">
                <div class="quick-action-card">
                    <div class="quick-action-icon" style="background-color: #fd7e14;">
                        <i class="bi bi-building"></i>
                    </div>
                    <h6 class="mb-0">Consultorio</h6>
                </div>
            </a>
        </div>
        <div class="col-6 col-md-4 col-lg-2-4 mb-4">
            <a href="{{URL::to('/admin/view-histories')}}" class="text-decoration-none">
                <div class="quick-action-card">
                    <div class="quick-action-icon" style="background-color: #6f42c1;">
                        <i class="bi bi-file-medical"></i>
                    </div>
                    <h6 class="mb-0">Historia</h6>
                </div>
            </a>
        </div>
        <div class="col-6 col-md-4 col-lg-2-4 mb-4">
            <a href="{{URL::to('/admin/appointment-payment-relation')}}" class="text-decoration-none">
                <div class="quick-action-card">
                    <div class="quick-action-icon" style="background-color: #20c997;">
                        <i class="bi bi-file-earmark-text"></i>
                    </div>
                    <h6 class="mb-0">Pagos</h6>
                </div>
            </a>
        </div>
    </div>

    <div class="section-separator"></div>

    <!-- Sección de gráficos mejorada + Próximas citas -->
    <div class="row g-4">
        @if(in_array(\App\Models\Settings::APPOINTMENT_ONLY_MODE, $accessMode) || in_array(\App\Models\Settings::FULL_ACCESS_MODE, $accessMode))
        <div class="col-12 col-lg-8">
            <div class="chart-container mb-4">
                <h5 class="section-title">Actividad Reciente</h5>
                <div class="medical-chart">
                    {!! $chart1->renderHtml() !!}
                </div>
            </div>
            
            <!-- Información de Pacientes -->
            <div class="chart-container">
                <div class="row">
                    <div class="col-md-6">
                        <div class="medical-chart">
                            {!! $chart2->renderHtml() !!}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="medical-chart">
                            {!! $chart3->renderHtml() !!}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-12 col-lg-4">
            <div class="chart-container mb-4">
                <h5 class="section-title">Próximas Citas</h5>
                
                @if($appointmentsToday > 0)
                    @php 
                        $todayAppointments = \App\Models\Appointments::where("active", "1")
                            ->whereDate('date', \Carbon\Carbon::today())
                            ->orderBy('date', 'asc')
                            ->take(3)
                            ->get();
                    @endphp
                    
                    @foreach($todayAppointments as $appointment)
                        @php
                            $patient = $appointment->patient()->first();
                            $dateTime = new DateTime($appointment->date);
                            $hour = $dateTime->format('H:i');
                            $ampm = $dateTime->format('A');
                            $especiality = \App\Models\Especiality::find($appointment->especiality_id);
                            $motivo = $especiality ? $especiality->especiality : ($appointment->appointment_type ?: 'Consulta');
                        @endphp
                        <div class="upcoming-appointment-card">
                            <div class="appointment-time">
                                <div>{{ $hour }}</div>
                                <small>{{ $ampm }}</small>
                            </div>
                            <div class="appointment-details">
                                <h6 class="mb-0">{{ $patient ? $patient->firstname . ' ' . $patient->lastname : 'Paciente' }}</h6>
                                <div class="d-flex justify-content-between">
                                    <small class="text-muted">{{ $motivo }}</small>
                                    <span class="status-tag scheduled">Agendada</span>
                                </div>
                            </div>
                        </div>
                    @endforeach
                    
                    <div class="mt-3 text-center">
                        <a href="{{URL::to('/admin/view-appointments')}}" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-calendar-week me-1"></i> Ver todas las citas
                        </a>
                    </div>
                @else
                    <div class="text-center py-4">
                        <i class="bi bi-calendar-x text-muted" style="font-size: 2.5rem;"></i>
                        <p class="mt-2 text-muted">No hay citas programadas para hoy</p>
                        <a href="{{URL::to('/admin/create-appointment')}}" class="btn btn-sm btn-primary mt-2">
                            <i class="bi bi-calendar-plus me-1"></i> Programar nueva cita
                        </a>
                    </div>
                @endif
            </div>

            <!-- Widget de Citas Recurrentes -->
            <div class="chart-container">
                <h5 class="section-title">{{ __('recurring-appointments.upcomingReturnHeading') }}</h5>
                
                @php 
                    $recurringAppointments = \App\Models\RecurringAppointment::where('is_active', true)
                        ->where('next_appointment_date', '>=', \Carbon\Carbon::now())
                        ->orderBy('next_appointment_date', 'asc')
                        ->take(3)
                        ->with(['patient', 'doctor', 'especialityRelation'])
                        ->get();
                @endphp
                
                @if($recurringAppointments->isNotEmpty())
                    @foreach($recurringAppointments as $recurring)
                        @php
                            $daysUntil = \Carbon\Carbon::now()->startOfDay()->diffInDays(\Carbon\Carbon::parse($recurring->next_appointment_date)->startOfDay(), false);
                            $patient = $recurring->patient;
                            $doctor = $recurring->doctor;
                            $especiality = $recurring->especialityRelation;
                            $nextDate = \Carbon\Carbon::parse($recurring->next_appointment_date)->format('d/m/Y');
                        @endphp
                        <div class="upcoming-appointment-card" style="{{ $daysUntil <= $recurring->reminder_days ? 'border-left-color: #dc3545;' : '' }}">
                            <div class="appointment-time">
                                <div>{{ $nextDate }}</div>
                                <small>{{ $daysUntil }} días</small>
                            </div>
                            <div class="appointment-details">
                                <h6 class="mb-0">{{ $patient->firstname . ' ' . $patient->lastname }}</h6>
                                <div class="d-flex justify-content-between">
                                    <small class="text-muted">{{ $especiality->name }} - {{ $doctor->name }}</small>
                                    <span class="status-tag {{ $daysUntil <= $recurring->reminder_days ? 'pending' : 'scheduled' }}">
                                        {{ $daysUntil <= $recurring->reminder_days ? 'Próximo' : 'Programado' }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    @endforeach
                    
                    <div class="mt-3 text-center">
                        <a href="{{ route('recurring-appointments.index') }}" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-calendar-check me-1"></i> Ver todos los retornos
                        </a>
                    </div>
                @else
                    <div class="text-center py-4">
                        <i class="bi bi-calendar-x text-muted" style="font-size: 2.5rem;"></i>
                        <p class="mt-2 text-muted">No hay retornos programados próximamente</p>
                        <a href="{{ route('recurring-appointments.index') }}" class="btn btn-sm btn-primary mt-2">
                            <i class="bi bi-calendar-check me-1"></i> Gestionar retornos
                        </a>
                    </div>
                @endif
            </div>
        </div>
        @endif
    </div>
</div>
@endsection

@section('javascript')
{!! $chart1->renderChartJsLibrary() !!}
{!! $chart1->renderJs() !!}
{!! $chart2->renderJs() !!}
{!! $chart3->renderJs() !!}
@endsection