@extends('layouts.admin')

@section('title', 'Vendeur - ' . $seller->shop_name)

@section('content')
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0">{{ $seller->shop_name }}</h1>
        <a href="{{ route('admin.sellers.index') }}" class="btn btn-secondary">Retour</a>
    </div>

    @if(session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif

    <div class="row">
        <div class="col-md-4">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Informations</h5>
                </div>
                <div class="card-body">
                    <p><strong>Propriétaire:</strong> {{ $seller->user->name ?? 'N/A' }}</p>
                    <p><strong>Email:</strong> {{ $seller->email ?? $seller->user->email ?? 'N/A' }}</p>
                    <p><strong>Téléphone:</strong> {{ $seller->phone ?? 'N/A' }}</p>
                    <p><strong>Adresse:</strong> {{ $seller->address ?? 'N/A' }}</p>
                    <p><strong>Ville:</strong> {{ $seller->city ?? 'N/A' }}</p>
                    <p><strong>Pays:</strong> {{ $seller->country ?? 'N/A' }}</p>
                    <hr>
                    <p><strong>Note:</strong> {{ $seller->rating }}/5 ({{ $seller->total_reviews }} avis)</p>
                    <p><strong>Ventes totales:</strong> {{ $seller->total_sales }}</p>
                    <p><strong>Revenus:</strong> {{ number_format($seller->total_revenue, 0, ',', ' ') }} XOF</p>
                </div>
            </div>

            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Commission</h5>
                </div>
                <div class="card-body">
                    <form action="{{ route('admin.sellers.update-commission', $seller) }}" method="POST">
                        @csrf
                        @method('PUT')
                        <div class="input-group">
                            <input type="number" name="commission_rate" value="{{ $seller->commission_rate }}" 
                                   class="form-control" step="0.01" min="0" max="100">
                            <span class="input-group-text">%</span>
                            <button type="submit" class="btn btn-primary">Mettre à jour</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-8">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Statut KYC: 
                        @switch($seller->kyc_status)
                            @case('pending')
                                <span class="badge bg-warning text-dark">En attente de documents</span>
                                @break
                            @case('submitted')
                                <span class="badge bg-info">Documents soumis - À vérifier</span>
                                @break
                            @case('approved')
                                <span class="badge bg-success">Approuvé</span>
                                @break
                            @case('rejected')
                                <span class="badge bg-danger">Rejeté</span>
                                @break
                        @endswitch
                    </h5>
                </div>
                <div class="card-body">
                    {{-- Informations business --}}
                    @if($seller->business_type || $seller->business_name)
                    <div class="mb-4">
                        <h6><i class="bi bi-building me-2"></i>Informations Business</h6>
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Type:</strong> 
                                    @switch($seller->business_type)
                                        @case('individual') Individuel @break
                                        @case('company') Société @break
                                        @case('association') Association @break
                                        @default {{ $seller->business_type ?? 'N/A' }}
                                    @endswitch
                                </p>
                                <p><strong>Nom entreprise:</strong> {{ $seller->business_name ?? 'N/A' }}</p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>N° RC:</strong> {{ $seller->business_registration ?? 'N/A' }}</p>
                                <p><strong>N° Fiscal:</strong> {{ $seller->tax_id ?? 'N/A' }}</p>
                            </div>
                        </div>
                    </div>
                    @endif

                    {{-- Documents KYC --}}
                    @if($seller->kyc_status === 'submitted' || $seller->kyc_status === 'pending' || $seller->id_document)
                    <div class="mb-4">
                        <h6><i class="bi bi-file-earmark-text me-2"></i>Documents KYC</h6>
                        <div class="row g-3">
                            @if($seller->id_document)
                            <div class="col-md-3">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        @php $idDocUrl = asset('storage/' . $seller->id_document); @endphp
                                        @if(Str::endsWith($seller->id_document, ['.jpg', '.jpeg', '.png', '.gif']))
                                            <img src="{{ $idDocUrl }}" alt="Piece d'identite" class="img-fluid rounded mb-2" style="max-height: 100px; cursor: pointer;" onclick="openDocumentModal('{{ $idDocUrl }}', 'image', 'Pièce d\'identité')">
                                        @else
                                            <i class="bi bi-file-earmark-pdf fs-1 text-danger" style="cursor: pointer;" onclick="openDocumentModal('{{ $idDocUrl }}', 'pdf', 'Pièce d\'identité')"></i>
                                        @endif
                                        <p class="small mb-2">Pièce d'identité</p>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-primary" onclick="openDocumentModal('{{ $idDocUrl }}', '{{ Str::endsWith($seller->id_document, ['.pdf']) ? 'pdf' : 'image' }}', 'Pièce d\'identité')">
                                                <i class="bi bi-eye"></i> Voir
                                            </button>
                                            <a href="{{ $idDocUrl }}" download class="btn btn-outline-secondary">
                                                <i class="bi bi-download"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endif
                            @if($seller->address_proof)
                            <div class="col-md-3">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        @php $addressUrl = asset('storage/' . $seller->address_proof); @endphp
                                        @if(Str::endsWith($seller->address_proof, ['.jpg', '.jpeg', '.png', '.gif']))
                                            <img src="{{ $addressUrl }}" alt="Justificatif adresse" class="img-fluid rounded mb-2" style="max-height: 100px; cursor: pointer;" onclick="openDocumentModal('{{ $addressUrl }}', 'image', 'Justificatif d\'adresse')">
                                        @else
                                            <i class="bi bi-file-earmark-pdf fs-1 text-danger" style="cursor: pointer;" onclick="openDocumentModal('{{ $addressUrl }}', 'pdf', 'Justificatif d\'adresse')"></i>
                                        @endif
                                        <p class="small mb-2">Justificatif d'adresse</p>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-info" onclick="openDocumentModal('{{ $addressUrl }}', '{{ Str::endsWith($seller->address_proof, ['.pdf']) ? 'pdf' : 'image' }}', 'Justificatif d\'adresse')">
                                                <i class="bi bi-eye"></i> Voir
                                            </button>
                                            <a href="{{ $addressUrl }}" download class="btn btn-outline-secondary">
                                                <i class="bi bi-download"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endif
                            @if($seller->business_document)
                            <div class="col-md-3">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        @php $businessUrl = asset('storage/' . $seller->business_document); @endphp
                                        @if(Str::endsWith($seller->business_document, ['.jpg', '.jpeg', '.png', '.gif']))
                                            <img src="{{ $businessUrl }}" alt="Document entreprise" class="img-fluid rounded mb-2" style="max-height: 100px; cursor: pointer;" onclick="openDocumentModal('{{ $businessUrl }}', 'image', 'Document entreprise')">
                                        @else
                                            <i class="bi bi-file-earmark-pdf fs-1 text-danger" style="cursor: pointer;" onclick="openDocumentModal('{{ $businessUrl }}', 'pdf', 'Document entreprise')"></i>
                                        @endif
                                        <p class="small mb-2">Document entreprise</p>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-warning" onclick="openDocumentModal('{{ $businessUrl }}', '{{ Str::endsWith($seller->business_document, ['.pdf']) ? 'pdf' : 'image' }}', 'Document entreprise')">
                                                <i class="bi bi-eye"></i> Voir
                                            </button>
                                            <a href="{{ $businessUrl }}" download class="btn btn-outline-secondary">
                                                <i class="bi bi-download"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endif
                            @if($seller->business_photo)
                            <div class="col-md-3">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        @php $photoUrl = asset('storage/' . $seller->business_photo); @endphp
                                        <img src="{{ $photoUrl }}" alt="Photo boutique" class="img-fluid rounded mb-2" style="max-height: 100px; cursor: pointer;" onclick="openDocumentModal('{{ $photoUrl }}', 'image', 'Photo boutique')">
                                        <p class="small mb-2">Photo boutique</p>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-outline-success" onclick="openDocumentModal('{{ $photoUrl }}', 'image', 'Photo boutique')">
                                                <i class="bi bi-eye"></i> Voir
                                            </button>
                                            <a href="{{ $photoUrl }}" download class="btn btn-outline-secondary">
                                                <i class="bi bi-download"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endif
                        </div>
                        
                        @if(!$seller->id_document && !$seller->address_proof && !$seller->business_document && !$seller->business_photo)
                            @if($seller->kyc_documents && count($seller->kyc_documents) > 0)
                                <ul class="list-unstyled">
                                    @foreach($seller->kyc_documents as $key => $doc)
                                        @php $docUrl = asset('storage/' . $doc); @endphp
                                        <li class="mb-2">
                                            <div class="btn-group btn-group-sm">
                                                <button type="button" class="btn btn-outline-primary" onclick="openDocumentModal('{{ $docUrl }}', '{{ Str::endsWith($doc, ['.pdf']) ? 'pdf' : 'image' }}', 'Document {{ $loop->iteration }}')">
                                                    <i class="bi bi-eye"></i> Document {{ $loop->iteration }}
                                                </button>
                                                <a href="{{ $docUrl }}" download class="btn btn-outline-secondary">
                                                    <i class="bi bi-download"></i>
                                                </a>
                                            </div>
                                        </li>
                                    @endforeach
                                </ul>
                            @else
                                <p class="text-muted"><i class="bi bi-exclamation-circle"></i> Aucun document soumis</p>
                            @endif
                        @endif
                    </div>
                    @endif

                    {{-- Actions KYC --}}
                    @if(in_array($seller->kyc_status, ['submitted', 'pending']))
                        @if($seller->id_document || ($seller->kyc_documents && count($seller->kyc_documents) > 0))
                        <div class="d-flex gap-2 flex-wrap">
                            <form action="{{ route('admin.sellers.approve-kyc', $seller) }}" method="POST">
                                @csrf
                                <button type="submit" class="btn btn-success">
                                    <i class="bi bi-check-circle me-1"></i> Approuver KYC
                                </button>
                            </form>

                            <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#rejectModal">
                                <i class="bi bi-x-circle me-1"></i> Rejeter KYC
                            </button>
                            
                            <form action="{{ route('admin.sellers.toggle-active', $seller) }}" method="POST">
                                @csrf
                                <button type="submit" class="btn btn-outline-{{ $seller->is_active ? 'warning' : 'success' }}">
                                    <i class="bi bi-power me-1"></i> {{ $seller->is_active ? 'Désactiver' : 'Activer' }} compte
                                </button>
                            </form>
                        </div>
                        @else
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            En attente de soumission des documents par le vendeur.
                        </div>
                        @endif
                    @elseif($seller->kyc_status === 'rejected')
                        <div class="alert alert-danger mb-3">
                            <strong>Raison du rejet:</strong> {{ $seller->kyc_rejection_reason }}
                        </div>
                        <div class="d-flex gap-2">
                            <form action="{{ route('admin.sellers.approve-kyc', $seller) }}" method="POST">
                                @csrf
                                <button type="submit" class="btn btn-success">
                                    <i class="bi bi-check-circle me-1"></i> Approuver malgré tout
                                </button>
                            </form>
                        </div>
                    @elseif($seller->kyc_status === 'approved')
                        <div class="alert alert-success">
                            <i class="bi bi-check-circle me-2"></i>
                            KYC approuvé le {{ $seller->kyc_approved_at?->format('d/m/Y H:i') ?? $seller->kyc_verified_at?->format('d/m/Y H:i') ?? 'N/A' }}
                        </div>
                        <div class="d-flex gap-2">
                            <form action="{{ route('admin.sellers.toggle-active', $seller) }}" method="POST">
                                @csrf
                                <button type="submit" class="btn btn-{{ $seller->is_active ? 'warning' : 'success' }}">
                                    <i class="bi bi-power me-1"></i> {{ $seller->is_active ? 'Désactiver' : 'Activer' }} compte
                                </button>
                            </form>
                            <form action="{{ route('admin.sellers.toggle-featured', $seller) }}" method="POST">
                                @csrf
                                <button type="submit" class="btn btn-outline-{{ $seller->is_featured ? 'secondary' : 'warning' }}">
                                    <i class="bi bi-star me-1"></i> {{ $seller->is_featured ? 'Retirer vedette' : 'Mettre en vedette' }}
                                </button>
                            </form>
                        </div>
                    @endif
                </div>
            </div>

            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Produits ({{ $seller->products->count() }})</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Produit</th>
                                    <th>Prix</th>
                                    <th>Stock</th>
                                    <th>Statut</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($seller->products->take(10) as $product)
                                <tr>
                                    <td>{{ $product->name }}</td>
                                    <td>{{ number_format($product->price, 0, ',', ' ') }} XOF</td>
                                    <td>{{ $product->quantity }}</td>
                                    <td>
                                        @if($product->is_active)
                                            <span class="badge bg-success">Actif</span>
                                        @else
                                            <span class="badge bg-secondary">Inactif</span>
                                        @endif
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="4" class="text-center">Aucun produit</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{{ route('admin.sellers.reject-kyc', $seller) }}" method="POST">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">Rejeter le KYC</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Raison du rejet</label>
                        <textarea name="rejection_reason" class="form-control" rows="3" required placeholder="Expliquez pourquoi les documents sont rejetés..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" class="btn btn-danger">Rejeter</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Modal pour visualiser les documents KYC --}}
<div class="modal fade" id="documentModal" tabindex="-1" aria-labelledby="documentModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="documentModalLabel">Document</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
            </div>
            <div class="modal-body text-center p-0" style="min-height: 500px; background: #f8f9fa;">
                {{-- Contenu chargé dynamiquement --}}
                <div id="documentContent"></div>
            </div>
            <div class="modal-footer">
                <a href="#" id="documentDownloadBtn" download class="btn btn-primary">
                    <i class="bi bi-download me-1"></i> Télécharger
                </a>
                <a href="#" id="documentOpenBtn" target="_blank" class="btn btn-outline-secondary">
                    <i class="bi bi-box-arrow-up-right me-1"></i> Ouvrir dans un nouvel onglet
                </a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fermer</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
function openDocumentModal(url, type, title) {
    const modal = new bootstrap.Modal(document.getElementById('documentModal'));
    const content = document.getElementById('documentContent');
    const titleEl = document.getElementById('documentModalLabel');
    const downloadBtn = document.getElementById('documentDownloadBtn');
    const openBtn = document.getElementById('documentOpenBtn');
    
    titleEl.textContent = title || 'Document';
    downloadBtn.href = url;
    openBtn.href = url;
    
    if (type === 'pdf') {
        // Afficher le PDF dans un iframe
        content.innerHTML = `
            <iframe src="${url}" 
                    style="width: 100%; height: 80vh; border: none;"
                    title="${title}">
                <p>Votre navigateur ne supporte pas l'affichage des PDF. 
                   <a href="${url}" target="_blank">Cliquez ici pour télécharger</a>
                </p>
            </iframe>
        `;
    } else {
        // Afficher l'image
        content.innerHTML = `
            <img src="${url}" 
                 alt="${title}" 
                 class="img-fluid" 
                 style="max-height: 80vh; object-fit: contain;">
        `;
    }
    
    modal.show();
}
</script>
@endpush
