@extends('admin.layout')

@section('page_title', 'Gestion des Commandes')

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h3 class="fw-bold text-dark mb-1">Commandes</h3>
        <p class="text-muted small mb-0">Suivez et gérez les ventes de votre boutique en temps réel</p>
    </div>
    <div class="d-flex gap-2">
        @if(Auth::user()->role === 'admin')
        <button onclick="exportOrdersToCSV()" class="btn btn-dark rounded-pill px-4 shadow-sm border-0">
            <i class="bi bi-download me-2"></i> Exporter en CSV
        </button>
        @endif
    </div>
</div>

<div class="card border-0 shadow-sm rounded-4 overflow-hidden">
    <div class="card-header bg-white border-0 py-3 px-4 mt-2">
        <form action="{{ route('admin.orders.index') }}" method="GET" class="row align-items-center g-3">
            <div class="col-md-4">
                <div class="input-group input-group-sm bg-light rounded-pill px-3 py-1 border shadow-sm">
                    <span class="input-group-text bg-transparent border-0"><i class="bi bi-search text-muted"></i></span>
                    <input type="text" name="search" class="form-control bg-transparent border-0" placeholder="Rechercher une commande..." value="{{ request('search') }}">
                </div>
            </div>
            <div class="col-md-8 text-md-end mt-3 mt-md-0">
                <div class="d-flex justify-content-md-end gap-3 align-items-center">
                    <div style="min-width: 200px;">
                        <select name="statut" class="form-select form-select-sm bg-white border rounded-pill px-3 shadow-sm py-2" onchange="this.form.submit()" style="width: 100%; margin-right: 24px;">
                            <option value="">Tous les statuts de commande</option>
                            <option value="en_attente" {{ request('statut') == 'en_attente' ? 'selected' : '' }}>En attente</option>
                            <option value="en_cours" {{ request('statut') == 'en_cours' ? 'selected' : '' }}>En cours</option>
                            <option value="livres" {{ request('statut') == 'livres' ? 'selected' : '' }}>Livrée</option>
                            <option value="annulee" {{ request('statut') == 'annulee' ? 'selected' : '' }}>Annulée</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-sm btn-dark rounded-pill px-4 py-2 shadow-sm">Filtrer</button>
                    <a href="{{ route('admin.orders.index') }}" class="btn btn-sm btn-outline-secondary rounded-pill px-3 py-2">Reset</a>
                </div>
            </div>
        </form>
    </div>
    
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light border-bottom">
                    <tr>
                        <th class="ps-4 py-3 text-muted small fw-bold text-uppercase border-0">Numéro</th>
                        <th class="py-3 text-muted small fw-bold text-uppercase border-0">Client</th>
                        <th class="py-3 text-muted small fw-bold text-uppercase border-0">Date & Heure</th>
                        <th class="py-3 text-muted small fw-bold text-uppercase border-0 text-end">Montant Total</th>
                        <th class="py-3 text-muted small fw-bold text-uppercase border-0 text-center">Statut</th>
                        <th class="pe-4 py-3 text-muted small fw-bold text-uppercase border-0 text-end">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($commandes as $commande)
                        <tr>
                            <td class="ps-4">
                                <span class="fw-bold text-primary">#{{ $commande->id }}</span>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="avatar-sm bg-primary bg-opacity-10 text-primary rounded-circle me-3 d-flex align-items-center justify-content-center fw-bold" style="width: 38px; height: 38px;">
                                        {{ substr($commande->user ? $commande->user->nom : $commande->name_client, 0, 1) }}
                                    </div>
                                    <div>
                                        <div class="fw-bold text-dark">
                                            @if($commande->user)
                                                {{ $commande->user->nom }} {{ $commande->user->prenom }}
                                            @else
                                                {{ $commande->name_client }} {{ $commande->prenom_client }}
                                            @endif
                                        </div>
                                        @if(!$commande->user_id)
                                            <span class="badge bg-secondary bg-opacity-10 text-secondary border-0 p-0 small" style="font-size: 10px;">CLIENT INVITÉ</span>
                                        @else
                                            <div class="text-muted small">{{ $commande->user->email }}</div>
                                        @endif
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="text-dark fw-medium">{{ $commande->created_at->format('d M, Y') }}</div>
                                <div class="text-muted small">{{ $commande->created_at->format('H:i') }}</div>
                            </td>
                            <td class="text-end fw-bold text-dark">
                                {{ number_format($commande->total, 2) }} <small>MAD</small>
                            </td>
                            <td class="text-center">
                                @switch($commande->statut)
                                    @case('en_attente')
                                        <span class="badge bg-warning bg-opacity-10 text-warning px-3 py-2 rounded-pill fw-semibold">
                                            <i class="bi bi-clock me-1"></i> En attente
                                        </span>
                                        @break
                                    @case('en_cours')
                                        <span class="badge bg-info bg-opacity-10 text-info px-3 py-2 rounded-pill fw-semibold">
                                            <i class="bi bi-truck me-1"></i> En cours
                                        </span>
                                        @break
                                    @case('livres')
                                        <span class="badge bg-success bg-opacity-10 text-success px-3 py-2 rounded-pill fw-semibold">
                                            <i class="bi bi-check-circle me-1"></i> Livrée
                                        </span>
                                        @break
                                    @case('annulee')
                                        <span class="badge bg-danger bg-opacity-10 text-danger px-3 py-2 rounded-pill fw-semibold">
                                            <i class="bi bi-x-circle me-1"></i> Annulée
                                        </span>
                                        @break
                                @endswitch
                            </td>
                            <td class="pe-4 text-end">
                                <div class="d-flex justify-content-end gap-2">
                                    <a href="{{ route('admin.orders.show', $commande->id) }}" class="btn btn-sm btn-dark rounded-pill px-3 shadow-sm">
                                        Détails <i class="bi bi-arrow-right ms-1"></i>
                                    </a>
                                    <form action="{{ route('admin.orders.destroy', $commande->id) }}" method="POST" class="d-inline"
                                          onsubmit="return confirm('Êtes-vous sûr de vouloir supprimer cette commande? Le stock sera restauré si nécessaire.');">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-sm btn-outline-danger rounded-pill px-3 shadow-sm">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
        
        <div class="card-footer bg-white border-0 py-4 px-4 border-top">
            <div class="d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
                <div class="text-muted small">
                    Affichage de <b>{{ $commandes->firstItem() }}</b> à <b>{{ $commandes->lastItem() }}</b> sur <b>{{ $commandes->total() }}</b> commandes
                </div>
                <div>
                    {{ $commandes->links() }}
                </div>
            </div>
        </div>
    </div>
</div>

</style>

<script>
function exportOrdersToCSV() {
    let csv = [];
    const rows = document.querySelectorAll("table tr");
    
    for (const row of rows) {
        let cols = row.querySelectorAll("td, th");
        let csvRow = [];
        for (let i = 0; i < cols.length - 1; i++) { // Skip the last 'Action' column
            let text = cols[i].innerText.replace(/(\r\n|\n|\r)/gm, " ").trim();
            csvRow.push('"' + text + '"');
        }
        csv.push(csvRow.join(","));
    }

    const csvFile = new Blob([csv.join("\n")], { type: "text/csv" });
    const downloadLink = document.createElement("a");
    downloadLink.download = "export_commandes.csv";
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}
</script>
@endsection
