@extends('layouts.app')

@section('title', $company['name'] ?? 'Detalles de Empresa')

@section('breadcrumbs')
    <li class="breadcrumb-item">Empresa</li>
    <li class="breadcrumb-item"><a href="{{ route('companies.index') }}">ABM Empresas</a></li>
    <li class="breadcrumb-item active">{{ $company['name'] ?? 'Detalles' }}</li>
@endsection

@section('content')
@if(isset($company))
<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="d-flex align-items-center">
        <div class="company-avatar large me-3">
            {{ substr($company['name'], 0, 2) }}
        </div>
        <div>
            <h2 class="mb-1">{{ $company['name'] }}</h2>
            <div class="d-flex align-items-center gap-2">
                <span class="badge bg-{{ $company['status'] === 'active' ? 'success' : ($company['status'] === 'inactive' ? 'secondary' : 'warning') }}">
                    {{ ucfirst($company['status']) }}
                </span>
                <small class="text-muted">ID: {{ $company['id'] }}</small>
                <small class="text-muted">•</small>
                <small class="text-muted">Creada: {{ \Carbon\Carbon::parse($company['created_at'])->format('d/m/Y') }}</small>
            </div>
        </div>
    </div>
    <div class="btn-group">
        <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">
            <i class="fas fa-cog"></i> Acciones
        </button>
        <ul class="dropdown-menu dropdown-menu-end">
            <li><a class="dropdown-item" href="#" onclick="assignNewPlan()">
                <i class="fas fa-layer-group"></i> Asignar Plan
            </a></li>
            <li><a class="dropdown-item" href="#" onclick="toggleStatus()">
                <i class="fas fa-toggle-{{ $company['status'] === 'active' ? 'off' : 'on' }}"></i> 
                {{ $company['status'] === 'active' ? 'Desactivar' : 'Activar' }}
            </a></li>
            <li><a class="dropdown-item" href="#" onclick="sendNotification()">
                <i class="fas fa-bell"></i> Enviar Notificación
            </a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" href="#" onclick="exportData()">
                <i class="fas fa-download"></i> Exportar Datos
            </a></li>
            <li><a class="dropdown-item text-danger" href="#" onclick="suspendCompany()">
                <i class="fas fa-ban"></i> Suspender
            </a></li>
        </ul>
    </div>
</div>

<!-- Estadísticas Rápidas -->
<div class="row mb-4">
    <div class="col-lg-3 col-md-6">
        <div class="stats-card mini success">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h4>{{ $stats['active_plans'] ?? 0 }}</h4>
                    <small>Planes Activos</small>
                </div>
                <i class="fas fa-layer-group fs-3"></i>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-md-6">
        <div class="stats-card mini info">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h4>${{ number_format($stats['total_paid'] ?? 0, 0, ',', '.') }}</h4>
                    <small>Total Pagado</small>
                </div>
                <i class="fas fa-dollar-sign fs-3"></i>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-md-6">
        <div class="stats-card mini warning">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h4>{{ $stats['pending_payments'] ?? 0 }}</h4>
                    <small>Pagos Pendientes</small>
                </div>
                <i class="fas fa-clock fs-3"></i>
            </div>
        </div>
    </div>
    <div class="col-lg-3 col-md-6">
        <div class="stats-card mini">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h4>{{ $stats['days_active'] ?? 0 }}</h4>
                    <small>Días Activa</small>
                </div>
                <i class="fas fa-calendar-alt fs-3"></i>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Información de la Empresa -->
    <div class="col-lg-4">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-info-circle"></i> Información General
                </h5>
            </div>
            <div class="card-body">
                <table class="table table-borderless">
                    <tr>
                        <td><strong>Nombre:</strong></td>
                        <td>{{ $company['name'] }}</td>
                    </tr>
                    <tr>
                        <td><strong>ID:</strong></td>
                        <td><code>{{ $company['id'] }}</code></td>
                    </tr>
                    <tr>
                        <td><strong>Estado:</strong></td>
                        <td>
                            <span class="badge bg-{{ $company['status'] === 'active' ? 'success' : ($company['status'] === 'inactive' ? 'secondary' : 'warning') }}">
                                {{ ucfirst($company['status']) }}
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>Creación:</strong></td>
                        <td>
                            {{ \Carbon\Carbon::parse($company['created_at'])->format('d/m/Y H:i') }}
                            <br>
                            <small class="text-muted">{{ \Carbon\Carbon::parse($company['created_at'])->diffForHumans() }}</small>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>Última Actualización:</strong></td>
                        <td>
                            {{ \Carbon\Carbon::parse($company['updated_at'])->format('d/m/Y H:i') }}
                            <br>
                            <small class="text-muted">{{ \Carbon\Carbon::parse($company['updated_at'])->diffForHumans() }}</small>
                        </td>
                    </tr>
                </table>
                
                @if(isset($company['notes']) && $company['notes'])
                <div class="mt-3">
                    <strong>Notas:</strong>
                    <div class="mt-2 p-3 bg-light rounded">
                        {{ $company['notes'] }}
                    </div>
                </div>
                @endif
            </div>
        </div>
        
        <!-- Plan Actual -->
        @if(isset($current_plan))
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-layer-group"></i> Plan Actual
                </h5>
                <span class="badge bg-{{ $current_plan['status'] === 'active' ? 'success' : 'warning' }}">
                    {{ ucfirst($current_plan['status']) }}
                </span>
            </div>
            <div class="card-body">
                <div class="text-center mb-3">
                    <h4 class="text-primary">{{ $current_plan['plan_name'] }}</h4>
                    <h3>${{ number_format($current_plan['final_price'], 0, ',', '.') }}</h3>
                    @if($current_plan['discount_percentage'] > 0)
                        <small class="text-muted">
                            <del>${{ number_format($current_plan['original_price'], 0, ',', '.') }}</del>
                            ({{ $current_plan['discount_percentage'] }}% off)
                        </small>
                    @endif
                </div>
                
                <table class="table table-sm table-borderless">
                    <tr>
                        <td><strong>Inicio:</strong></td>
                        <td>{{ \Carbon\Carbon::parse($current_plan['starts_at'])->format('d/m/Y') }}</td>
                    </tr>
                    <tr>
                        <td><strong>Vencimiento:</strong></td>
                        <td>
                            {{ \Carbon\Carbon::parse($current_plan['expires_at'])->format('d/m/Y') }}
                            <br>
                            @php
                                $daysLeft = \Carbon\Carbon::now()->diffInDays(\Carbon\Carbon::parse($current_plan['expires_at']), false);
                            @endphp
                            <small class="badge bg-{{ $daysLeft < 7 ? 'danger' : ($daysLeft < 30 ? 'warning' : 'success') }}">
                                {{ $daysLeft > 0 ? $daysLeft . ' días restantes' : 'Vencido' }}
                            </small>
                        </td>
                    </tr>
                    <tr>
                        <td><strong>Auto-renovación:</strong></td>
                        <td>
                            <span class="badge bg-{{ $current_plan['auto_renew'] ? 'success' : 'secondary' }}">
                                {{ $current_plan['auto_renew'] ? 'Sí' : 'No' }}
                            </span>
                        </td>
                    </tr>
                </table>
                
                <div class="btn-group w-100 btn-group-sm mt-3">
                    <button type="button" class="btn btn-outline-primary" onclick="renewPlan()">
                        <i class="fas fa-redo"></i> Renovar
                    </button>
                    <button type="button" class="btn btn-outline-warning" onclick="modifyPlan()">
                        <i class="fas fa-edit"></i> Modificar
                    </button>
                    <button type="button" class="btn btn-outline-danger" onclick="cancelPlan()">
                        <i class="fas fa-times"></i> Cancelar
                    </button>
                </div>
            </div>
        </div>
        @else
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-layer-group"></i> Plan Actual
                </h5>
            </div>
            <div class="card-body text-center">
                <i class="fas fa-layer-group fa-3x text-muted mb-3"></i>
                <p class="text-muted">Esta empresa no tiene ningún plan asignado.</p>
                <button type="button" class="btn btn-primary" onclick="assignNewPlan()">
                    <i class="fas fa-plus"></i> Asignar Plan
                </button>
            </div>
        </div>
        @endif
    </div>
    
    <!-- Historial y Actividad -->
    <div class="col-lg-8">
        <!-- Pestañas -->
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="detailTabs">
                    <li class="nav-item">
                        <button class="nav-link active" id="plans-tab" data-bs-toggle="tab" data-bs-target="#plans">
                            <i class="fas fa-layer-group"></i> Historial de Planes
                        </button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link" id="payments-tab" data-bs-toggle="tab" data-bs-target="#payments">
                            <i class="fas fa-credit-card"></i> Pagos
                        </button>
                    </li>
                    <li class="nav-item">
                        <button class="nav-link" id="activity-tab" data-bs-toggle="tab" data-bs-target="#activity">
                            <i class="fas fa-history"></i> Actividad
                        </button>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content">
                    <!-- Historial de Planes -->
                    <div class="tab-pane fade show active" id="plans">
                        @if(isset($plans_history) && count($plans_history) > 0)
                        <div class="timeline">
                            @foreach($plans_history as $plan)
                            <div class="timeline-item">
                                <div class="timeline-marker bg-{{ $plan['status'] === 'active' ? 'success' : ($plan['status'] === 'expired' ? 'secondary' : 'warning') }}">
                                    <i class="fas fa-layer-group"></i>
                                </div>
                                <div class="timeline-content">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6 class="mb-1">{{ $plan['plan_name'] }}</h6>
                                            <p class="mb-1">
                                                <strong>${{ number_format($plan['final_price'], 0, ',', '.') }}</strong>
                                                @if($plan['discount_percentage'] > 0)
                                                    <small class="text-muted">({{ $plan['discount_percentage'] }}% descuento)</small>
                                                @endif
                                            </p>
                                            <small class="text-muted">
                                                {{ \Carbon\Carbon::parse($plan['starts_at'])->format('d/m/Y') }} - 
                                                {{ \Carbon\Carbon::parse($plan['expires_at'])->format('d/m/Y') }}
                                            </small>
                                        </div>
                                        <span class="badge bg-{{ $plan['status'] === 'active' ? 'success' : ($plan['status'] === 'expired' ? 'secondary' : 'warning') }}">
                                            {{ ucfirst($plan['status']) }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            @endforeach
                        </div>
                        @else
                        <div class="text-center py-4">
                            <i class="fas fa-layer-group fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No hay historial de planes para esta empresa.</p>
                        </div>
                        @endif
                    </div>
                    
                    <!-- Pagos -->
                    <div class="tab-pane fade" id="payments">
                        @if(isset($payments_history) && count($payments_history) > 0)
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Fecha</th>
                                        <th>Concepto</th>
                                        <th>Monto</th>
                                        <th>Estado</th>
                                        <th>Método</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($payments_history as $payment)
                                    <tr>
                                        <td>
                                            {{ \Carbon\Carbon::parse($payment['created_at'])->format('d/m/Y') }}
                                            <br>
                                            <small class="text-muted">{{ \Carbon\Carbon::parse($payment['created_at'])->format('H:i') }}</small>
                                        </td>
                                        <td>
                                            <strong>{{ $payment['description'] }}</strong>
                                            @if(isset($payment['plan_name']))
                                                <br><small class="text-muted">Plan {{ $payment['plan_name'] }}</small>
                                            @endif
                                        </td>
                                        <td>
                                            <strong>${{ number_format($payment['amount'], 0, ',', '.') }}</strong>
                                        </td>
                                        <td>
                                            <span class="badge bg-{{ $payment['status'] === 'confirmed' ? 'success' : ($payment['status'] === 'pending' ? 'warning' : 'danger') }}">
                                                {{ ucfirst($payment['status']) }}
                                            </span>
                                        </td>
                                        <td>{{ $payment['payment_method'] ?? 'N/A' }}</td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button type="button" class="btn btn-outline-primary" onclick="viewPaymentDetails('{{ $payment['id'] }}')">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                @if($payment['status'] === 'pending')
                                                <button type="button" class="btn btn-outline-success" onclick="confirmPayment('{{ $payment['id'] }}')">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                                @endif
                                            </div>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        @else
                        <div class="text-center py-4">
                            <i class="fas fa-credit-card fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No hay historial de pagos para esta empresa.</p>
                        </div>
                        @endif
                    </div>
                    
                    <!-- Actividad -->
                    <div class="tab-pane fade" id="activity">
                        @if(isset($activity_log) && count($activity_log) > 0)
                        <div class="timeline">
                            @foreach($activity_log as $activity)
                            <div class="timeline-item">
                                <div class="timeline-marker bg-{{ $activity['type'] === 'plan' ? 'primary' : ($activity['type'] === 'payment' ? 'success' : 'info') }}">
                                    <i class="fas fa-{{ $activity['icon'] }}"></i>
                                </div>
                                <div class="timeline-content">
                                    <p class="mb-1">{{ $activity['description'] }}</p>
                                    <small class="text-muted">{{ \Carbon\Carbon::parse($activity['created_at'])->diffForHumans() }}</small>
                                    @if(isset($activity['details']))
                                        <div class="mt-2">
                                            <small class="text-muted">{{ $activity['details'] }}</small>
                                        </div>
                                    @endif
                                </div>
                            </div>
                            @endforeach
                        </div>
                        @else
                        <div class="text-center py-4">
                            <i class="fas fa-history fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No hay actividad registrada para esta empresa.</p>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@else
<div class="text-center py-5">
    <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
    <h4>Empresa no encontrada</h4>
    <p class="text-muted">La empresa solicitada no existe o no tienes permisos para verla.</p>
    <a href="{{ route('companies.index') }}" class="btn btn-primary">
        <i class="fas fa-arrow-left"></i> Volver a la lista
    </a>
</div>
@endif

@endsection

@push('styles')
<style>
    .company-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 14px;
    }
    
    .company-avatar.large {
        width: 60px;
        height: 60px;
        font-size: 18px;
    }
    
    .timeline {
        position: relative;
        padding-left: 30px;
    }
    
    .timeline::before {
        content: '';
        position: absolute;
        left: 15px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #dee2e6;
    }
    
    .timeline-item {
        position: relative;
        margin-bottom: 20px;
    }
    
    .timeline-marker {
        position: absolute;
        left: -23px;
        top: 5px;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 12px;
        border: 2px solid white;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .timeline-content {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 8px;
        border-left: 4px solid #dee2e6;
    }
    
    .stats-card.mini {
        padding: 15px;
        margin-bottom: 0;
    }
    
    .stats-card.mini h4 {
        font-size: 1.5rem;
        margin-bottom: 0;
    }
</style>
@endpush

@push('scripts')
<script>
    function assignNewPlan() {
        alert('Funcionalidad de asignación de plan en desarrollo');
    }
    
    function toggleStatus() {
        const currentStatus = '{{ $company['status'] ?? '' }}';
        const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
        
        if (confirm(`¿Deseas ${newStatus === 'active' ? 'activar' : 'desactivar'} esta empresa?`)) {
            alert('Funcionalidad de cambio de estado en desarrollo');
        }
    }
    
    function sendNotification() {
        alert('Funcionalidad de notificaciones en desarrollo');
    }
    
    function exportData() {
        alert('Funcionalidad de exportación en desarrollo');
    }
    
    function suspendCompany() {
        if (confirm('¿Estás seguro de que deseas suspender esta empresa?')) {
            alert('Funcionalidad de suspensión en desarrollo');
        }
    }
    
    function renewPlan() {
        alert('Funcionalidad de renovación de plan en desarrollo');
    }
    
    function modifyPlan() {
        alert('Funcionalidad de modificación de plan en desarrollo');
    }
    
    function cancelPlan() {
        if (confirm('¿Estás seguro de que deseas cancelar el plan actual?')) {
            alert('Funcionalidad de cancelación de plan en desarrollo');
        }
    }
    
    function viewPaymentDetails(paymentId) {
        alert('Ver detalles del pago: ' + paymentId);
    }
    
    function confirmPayment(paymentId) {
        if (confirm('¿Confirmar este pago?')) {
            alert('Confirmar pago: ' + paymentId);
        }
    }
</script>
@endpush