@extends('layouts.admin')

@section('title', 'Commandes')
@section('page-title', 'Gestion des Commandes')

@section('content')
{{-- Statistiques rapides --}}
<div class="row g-3 mb-4">
    <div class="col-md-2">
        <div class="card text-center h-100">
            <div class="card-body py-3">
                <div class="h4 mb-0 fw-bold">{{ $stats['total'] ?? 0 }}</div>
                <small class="text-muted">Total</small>
            </div>
        </div>
    </div>
    <div class="col-md-2">
        <a href="{{ route('admin.orders.index', ['status' => 'pending']) }}" class="text-decoration-none">
            <div class="card text-center h-100 border-warning">
                <div class="card-body py-3">
                    <div class="h4 mb-0 fw-bold text-warning">{{ $stats['pending'] ?? 0 }}</div>
                    <small class="text-muted">En attente</small>
                </div>
            </div>
        </a>
    </div>
    <div class="col-md-2">
        <a href="{{ route('admin.orders.index', ['status' => 'processing']) }}" class="text-decoration-none">
            <div class="card text-center h-100 border-info">
                <div class="card-body py-3">
                    <div class="h4 mb-0 fw-bold text-info">{{ $stats['processing'] ?? 0 }}</div>
                    <small class="text-muted">En cours</small>
                </div>
            </div>
        </a>
    </div>
    <div class="col-md-2">
        <a href="{{ route('admin.orders.index', ['status' => 'shipped']) }}" class="text-decoration-none">
            <div class="card text-center h-100 border-primary">
                <div class="card-body py-3">
                    <div class="h4 mb-0 fw-bold text-primary">{{ $stats['shipped'] ?? 0 }}</div>
                    <small class="text-muted">Expédiées</small>
                </div>
            </div>
        </a>
    </div>
    <div class="col-md-2">
        <a href="{{ route('admin.orders.index', ['status' => 'delivered']) }}" class="text-decoration-none">
            <div class="card text-center h-100 border-success">
                <div class="card-body py-3">
                    <div class="h4 mb-0 fw-bold text-success">{{ $stats['delivered'] ?? 0 }}</div>
                    <small class="text-muted">Livrées</small>
                </div>
            </div>
        </a>
    </div>
    <div class="col-md-2">
        <a href="{{ route('admin.orders.index', ['status' => 'cancelled']) }}" class="text-decoration-none">
            <div class="card text-center h-100 border-danger">
                <div class="card-body py-3">
                    <div class="h4 mb-0 fw-bold text-danger">{{ $stats['cancelled'] ?? 0 }}</div>
                    <small class="text-muted">Annulées</small>
                </div>
            </div>
        </a>
    </div>
</div>

{{-- Bouton Preuves de Livraison --}}
<div class="d-flex justify-content-end mb-3">
    <a href="{{ route('admin.orders.delivery-proofs') }}" class="btn btn-outline-primary">
        <i class="bi bi-truck me-2"></i>Gérer les preuves de livraison
        @php
            $pendingProofs = \App\Models\Order::where('delivery_proof_status', 'submitted')->count();
        @endphp
        @if($pendingProofs > 0)
            <span class="badge bg-warning text-dark ms-2">{{ $pendingProofs }}</span>
        @endif
    </a>
</div>

{{-- Filtres --}}
<div class="card mb-4">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <h6 class="mb-0"><i class="bi bi-funnel me-2"></i>Filtres de recherche</h6>
        <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#filterCollapse">
            <i class="bi bi-chevron-down"></i>
        </button>
    </div>
    <div class="collapse {{ request()->hasAny(['status', 'member_id', 'min_amount', 'max_amount', 'date_from', 'date_to', 'search']) ? 'show' : '' }}" id="filterCollapse">
        <div class="card-body">
            <form action="{{ route('admin.orders.index') }}" method="GET">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label small">Recherche</label>
                        <input type="text" name="search" class="form-control form-control-sm" 
                               placeholder="N° commande, nom, email, tél..." value="{{ request('search') }}">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Statut</label>
                        <select name="status" class="form-select form-select-sm">
                            <option value="">Tous</option>
                            @foreach($statuses as $status)
                                <option value="{{ $status }}" {{ request('status') == $status ? 'selected' : '' }}>
                                    {{ ucfirst($status) }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small">Membre</label>
                        <select name="member_id" class="form-select form-select-sm">
                            <option value="">Tous les membres</option>
                            @foreach($members as $member)
                                <option value="{{ $member->id }}" {{ request('member_id') == $member->id ? 'selected' : '' }}>
                                    {{ $member->name }} ({{ $member->email }})
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Montant min</label>
                        <input type="number" name="min_amount" class="form-control form-control-sm" 
                               placeholder="Min" value="{{ request('min_amount') }}">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Montant max</label>
                        <input type="number" name="max_amount" class="form-control form-control-sm" 
                               placeholder="Max" value="{{ request('max_amount') }}">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Date début</label>
                        <input type="date" name="date_from" class="form-control form-control-sm" 
                               value="{{ request('date_from') }}">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small">Date fin</label>
                        <input type="date" name="date_to" class="form-control form-control-sm" 
                               value="{{ request('date_to') }}">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary btn-sm">
                                <i class="bi bi-search me-1"></i>Filtrer
                            </button>
                            <a href="{{ route('admin.orders.index') }}" class="btn btn-outline-secondary btn-sm">
                                <i class="bi bi-x-circle me-1"></i>Réinitialiser
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Formulaire caché pour fallback --}}
<form id="bulkForm" action="{{ route('admin.orders.bulk-status') }}" method="POST" style="display: none;">
    @csrf
    <div id="hiddenOrderIds"></div>
    <input type="hidden" name="status" id="hiddenStatus">
</form>

{{-- Actions en masse --}}
<div class="card">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Liste des Commandes</h5>
        <div class="d-flex gap-2 align-items-center">
            <div class="bulk-actions d-none align-items-center gap-2" id="bulkActions">
                <span class="text-muted small"><span id="selectedCount">0</span> sélectionnée(s)</span>
                <select class="form-select form-select-sm" style="width: auto;" id="bulkStatus">
                    <option value="">Changer statut...</option>
                    <option value="pending">En Attente</option>
                    <option value="processing">En Cours</option>
                    <option value="shipped">Expédiée</option>
                    <option value="delivered">Livrée</option>
                    <option value="cancelled">Annulée</option>
                </select>
                <button type="button" class="btn btn-primary btn-sm" id="bulkSubmit" disabled>
                    <i class="bi bi-check2-all me-1"></i>Appliquer
                </button>
            </div>
        </div>
    </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 style="width: 40px;">
                            <input type="checkbox" class="form-check-input" id="selectAll">
                        </th>
                        <th>N° Commande</th>
                        <th>Client</th>
                        <th>Contact</th>
                        <th class="text-center">Articles</th>
                        <th class="text-end">Montant</th>
                        <th>Statut</th>
                        <th>Date</th>
                        <th style="width: 100px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($orders as $order)
                    @php
                        $statusColors = [
                            'pending' => 'warning',
                            'processing' => 'info',
                            'shipped' => 'primary',
                            'delivered' => 'success',
                            'cancelled' => 'danger',
                        ];
                        $statusLabels = [
                            'pending' => 'En Attente',
                            'processing' => 'En Cours',
                            'shipped' => 'Expédiée',
                            'delivered' => 'Livrée',
                            'cancelled' => 'Annulée',
                        ];
                        $statusColor = $statusColors[$order->status] ?? 'secondary';
                    @endphp
                    <tr>
                        <td>
                            <input type="checkbox" class="form-check-input order-checkbox" 
                                   data-order-id="{{ $order->id }}" value="{{ $order->id }}">
                        </td>
                            <td>
                                <strong>#{{ $order->order_number ?? $order->id }}</strong>
                            </td>
                            <td>
                                <strong>{{ $order->customer_name ?? $order->user->name ?? 'N/A' }}</strong>
                                @if($order->user)
                                    <br><small class="text-muted">Membre #{{ $order->user->id }}</small>
                                @endif
                            </td>
                            <td>
                                <small>{{ $order->customer_email ?? $order->user->email ?? '-' }}</small><br>
                                <small class="text-muted">{{ $order->customer_phone ?? $order->user->phone ?? '-' }}</small>
                            </td>
                            <td class="text-center">
                                <span class="badge bg-secondary">{{ $order->items->count() }}</span>
                            </td>
                            <td class="text-end">
                                <strong>{{ number_format($order->total_amount, 0, ',', ' ') }} FCFA</strong>
                            </td>
                            <td>
                                <form action="{{ route('admin.orders.update-status', $order) }}" method="POST" class="d-inline status-form">
                                    @csrf
                                    @method('PUT')
                                    <select name="status" class="form-select form-select-sm border-{{ $statusColor }}" 
                                            style="width: 130px;" onchange="this.form.submit()">
                                        @foreach($statuses as $status)
                                            <option value="{{ $status }}" {{ $order->status == $status ? 'selected' : '' }}>
                                                {{ $statusLabels[$status] ?? ucfirst($status) }}
                                            </option>
                                        @endforeach
                                    </select>
                                </form>
                            </td>
                            <td>
                                <small>{{ $order->created_at->format('d/m/Y') }}</small><br>
                                <small class="text-muted">{{ $order->created_at->format('H:i') }}</small>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="{{ route('admin.orders.show', $order) }}" class="btn btn-outline-primary" title="Détails">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="9" class="text-center text-muted py-5">
                                <i class="bi bi-inbox" style="font-size: 3rem;"></i>
                                <p class="mt-2 mb-0">Aucune commande trouvée</p>
                                @if(request()->hasAny(['status', 'member_id', 'min_amount', 'max_amount', 'date_from', 'date_to', 'search']))
                                    <a href="{{ route('admin.orders.index') }}" class="btn btn-sm btn-outline-primary mt-2">
                                        <i class="bi bi-x-circle me-1"></i>Réinitialiser les filtres
                                    </a>
                                @endif
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        @if($orders->hasPages())
        <div class="card-footer bg-white">
            <div class="d-flex justify-content-between align-items-center">
                <small class="text-muted">
                    Affichage de {{ $orders->firstItem() }} à {{ $orders->lastItem() }} sur {{ $orders->total() }} commandes
                </small>
                {{ $orders->links() }}
            </div>
        </div>
        @endif
    </div>

@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAll = document.getElementById('selectAll');
    const orderCheckboxes = document.querySelectorAll('.order-checkbox');
    const bulkActions = document.getElementById('bulkActions');
    const selectedCount = document.getElementById('selectedCount');
    const bulkStatus = document.getElementById('bulkStatus');
    const bulkSubmit = document.getElementById('bulkSubmit');

    function updateBulkActions() {
        const checked = document.querySelectorAll('.order-checkbox:checked');
        const count = checked.length;
        
        if (count > 0) {
            bulkActions.classList.remove('d-none');
            bulkActions.classList.add('d-flex');
            selectedCount.textContent = count;
        } else {
            bulkActions.classList.add('d-none');
            bulkActions.classList.remove('d-flex');
        }
    }

    // Select all
    selectAll.addEventListener('change', function() {
        orderCheckboxes.forEach(cb => cb.checked = this.checked);
        updateBulkActions();
    });

    // Individual checkboxes
    orderCheckboxes.forEach(cb => {
        cb.addEventListener('change', function() {
            updateBulkActions();
            if (!this.checked) {
                selectAll.checked = false;
            }
            if (document.querySelectorAll('.order-checkbox:checked').length === orderCheckboxes.length) {
                selectAll.checked = true;
            }
        });
    });

    // Bulk status change - enable button
    bulkStatus.addEventListener('change', function() {
        bulkSubmit.disabled = !this.value;
    });

    // Bulk Update avec fallback formulaire
    bulkSubmit.addEventListener('click', function(e) {
        e.preventDefault();
        
        const checkedBoxes = document.querySelectorAll('.order-checkbox:checked');
        const checkedCount = checkedBoxes.length;
        const newStatus = bulkStatus.value;
        
        if (checkedCount === 0) {
            alert('Veuillez sélectionner au moins une commande.');
            return;
        }
        
        if (!newStatus) {
            alert('Veuillez sélectionner un statut.');
            return;
        }
        
        const statusLabels = {
            'pending': 'En Attente',
            'processing': 'En Cours',
            'shipped': 'Expédiée',
            'delivered': 'Livrée',
            'cancelled': 'Annulée'
        };
        
        if (!confirm(`Êtes-vous sûr de vouloir changer le statut de ${checkedCount} commande(s) en "${statusLabels[newStatus]}" ?`)) {
            return;
        }
        
        // Collect order IDs
        const orderIds = [];
        checkedBoxes.forEach(cb => {
            orderIds.push(cb.getAttribute('data-order-id') || cb.value);
        });
        
        console.log('Order IDs:', orderIds);
        console.log('New Status:', newStatus);
        
        // Disable button during request
        bulkSubmit.disabled = true;
        bulkSubmit.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Traitement...';
        
        // Essayer AJAX d'abord
        const csrfToken = document.querySelector('meta[name="csrf-token"]');
        if (!csrfToken) {
            console.error('CSRF token not found');
            submitViaForm(orderIds, newStatus);
            return;
        }
        
        fetch('{{ url("/admin/orders/bulk-status") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken.getAttribute('content'),
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                order_ids: orderIds,
                status: newStatus
            })
        })
        .then(response => {
            console.log('Response status:', response.status);
            if (response.status === 404) {
                console.log('404 - Fallback to form submission');
                submitViaForm(orderIds, newStatus);
                return null;
            }
            if (!response.ok) {
                throw new Error('Erreur serveur: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (data === null) return; // Déjà géré par fallback
            
            if (data.success) {
                alert(data.message || `${checkedCount} commande(s) mise(s) à jour avec succès !`);
                window.location.reload();
            } else {
                alert(data.message || 'Une erreur est survenue.');
                resetButton();
            }
        })
        .catch(error => {
            console.error('AJAX Error:', error);
            // Fallback vers soumission par formulaire
            console.log('Falling back to form submission');
            submitViaForm(orderIds, newStatus);
        });
    });
    
    // Fonction pour soumettre via formulaire classique (fallback)
    function submitViaForm(orderIds, status) {
        const form = document.getElementById('bulkForm');
        const hiddenOrderIds = document.getElementById('hiddenOrderIds');
        const hiddenStatus = document.getElementById('hiddenStatus');
        
        // Vider les anciens inputs
        hiddenOrderIds.innerHTML = '';
        
        // Ajouter les IDs des commandes
        orderIds.forEach(id => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'order_ids[]';
            input.value = id;
            hiddenOrderIds.appendChild(input);
        });
        
        // Définir le statut
        hiddenStatus.value = status;
        
        // Soumettre le formulaire
        form.submit();
    }
    
    function resetButton() {
        bulkSubmit.disabled = false;
        bulkSubmit.innerHTML = '<i class="bi bi-check2-all me-1"></i>Appliquer';
    }
});
</script>
@endpush
