@extends('layouts.comptabilite')

@section('title', 'Rapports - Comptabilité')
@section('page-title', 'Rapports Financiers')

@section('content')
@php
    use App\Models\Order;
    use App\Models\Commission;
    use App\Models\Withdrawal;
    use Illuminate\Support\Facades\DB;
    
    $currentMonth = now();
    $lastMonth = now()->subMonth();
    
    // Revenus
    $revenueThisMonth = Order::where('status', 'delivered')
        ->whereMonth('created_at', $currentMonth->month)
        ->whereYear('created_at', $currentMonth->year)
        ->sum('total_amount');
    
    $revenueLastMonth = Order::where('status', 'delivered')
        ->whereMonth('created_at', $lastMonth->month)
        ->whereYear('created_at', $lastMonth->year)
        ->sum('total_amount');
    
    // Commissions
    $commissionsThisMonth = Commission::where('status', 'paid')
        ->whereMonth('created_at', $currentMonth->month)
        ->whereYear('created_at', $currentMonth->year)
        ->sum('amount');
    
    // Retraits
    $withdrawalsThisMonth = Withdrawal::where('status', 'approved')
        ->whereMonth('updated_at', $currentMonth->month)
        ->whereYear('updated_at', $currentMonth->year)
        ->sum('amount');
    
    // Données graphiques (7 derniers jours)
    $revenueChart = Order::where('status', 'delivered')
        ->where('created_at', '>=', now()->subDays(7))
        ->select(DB::raw('DATE(created_at) as date'), DB::raw('SUM(total_amount) as total'))
        ->groupBy('date')
        ->orderBy('date')
        ->get();
@endphp

<div class="row g-4 mb-4">
    <div class="col-md-4">
        <div class="card stat-card h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="text-muted mb-1">Revenus ce mois</h6>
                        <h3 class="fw-bold text-success">{{ number_format($revenueThisMonth, 0, ',', ' ') }} XOF</h3>
                        @php
                            $revenueChange = $revenueLastMonth > 0 ? (($revenueThisMonth - $revenueLastMonth) / $revenueLastMonth) * 100 : 0;
                        @endphp
                        <small class="{{ $revenueChange >= 0 ? 'text-success' : 'text-danger' }}">
                            <i class="bi bi-arrow-{{ $revenueChange >= 0 ? 'up' : 'down' }}"></i>
                            {{ number_format(abs($revenueChange), 1) }}% vs mois dernier
                        </small>
                    </div>
                    <div class="text-success opacity-50">
                        <i class="bi bi-graph-up-arrow fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card stat-card h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="text-muted mb-1">Commissions payées</h6>
                        <h3 class="fw-bold text-info">{{ number_format($commissionsThisMonth, 0, ',', ' ') }} XOF</h3>
                        <small class="text-muted">Ce mois</small>
                    </div>
                    <div class="text-info opacity-50">
                        <i class="bi bi-wallet2 fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card stat-card h-100">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <h6 class="text-muted mb-1">Retraits approuvés</h6>
                        <h3 class="fw-bold text-warning">{{ number_format($withdrawalsThisMonth, 0, ',', ' ') }} XOF</h3>
                        <small class="text-muted">Ce mois</small>
                    </div>
                    <div class="text-warning opacity-50">
                        <i class="bi bi-cash-stack fs-1"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-bar-chart me-2"></i>Revenus (7 derniers jours)</h5>
            </div>
            <div class="card-body">
                <canvas id="revenueChart" height="100"></canvas>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-download me-2"></i>Exporter</h5>
            </div>
            <div class="card-body">
                <p class="text-muted small">Téléchargez les rapports financiers au format CSV ou PDF.</p>
                <div class="d-grid gap-2">
                    <a href="{{ route('comptabilite.reports.export') }}?type=revenue" class="btn btn-outline-primary">
                        <i class="bi bi-file-earmark-spreadsheet me-2"></i>Rapport des revenus
                    </a>
                    <a href="{{ route('comptabilite.reports.export') }}?type=commissions" class="btn btn-outline-info">
                        <i class="bi bi-file-earmark-spreadsheet me-2"></i>Rapport des commissions
                    </a>
                    <a href="{{ route('comptabilite.reports.export') }}?type=withdrawals" class="btn btn-outline-warning">
                        <i class="bi bi-file-earmark-spreadsheet me-2"></i>Rapport des retraits
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    const ctx = document.getElementById('revenueChart').getContext('2d');
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: {!! json_encode($revenueChart->pluck('date')->map(fn($d) => \Carbon\Carbon::parse($d)->format('d/m'))) !!},
            datasets: [{
                label: 'Revenus (XOF)',
                data: {!! json_encode($revenueChart->pluck('total')) !!},
                backgroundColor: 'rgba(14, 165, 233, 0.5)',
                borderColor: 'rgb(14, 165, 233)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
</script>
@endpush
