@extends('layouts.app')

@section('content')
<div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">Laporan Keuangan</h1>
        <div class="flex space-x-2">
            <a href="#" onclick="exportToPDF()" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
                <i class="fas fa-file-pdf mr-2"></i>Export PDF
            </a>
            <a href="#" onclick="exportToExcel()" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
                <i class="fas fa-file-excel mr-2"></i>Export Excel
            </a>
        </div>
    </div>

    <div class="bg-white rounded-lg shadow-md overflow-hidden p-6 mb-6">
        <h2 class="text-lg font-semibold mb-4">Filter Laporan</h2>
        <form action="{{ route('reports.financial') }}" method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
            <div>
                <label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Tanggal Mulai</label>
                <input type="date" id="start_date" name="start_date" value="{{ $startDate }}" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">Tanggal Akhir</label>
                <input type="date" id="end_date" name="end_date" value="{{ $endDate }}" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
            </div>
            <div>
                <label for="project_id" class="block text-sm font-medium text-gray-700 mb-1">Proyek</label>
                <select id="project_id" name="project_id" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    <option value="">Semua Proyek</option>
                    @foreach($projects as $project)
                        <option value="{{ $project->id }}" {{ $projectId == $project->id ? 'selected' : '' }}>{{ $project->name }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label for="category" class="block text-sm font-medium text-gray-700 mb-1">Kategori</label>
                <select id="category" name="category" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    <option value="">Semua Kategori</option>
                    @foreach($categories as $cat)
                        <option value="{{ $cat }}" {{ $category == $cat ? 'selected' : '' }}>{{ $cat }}</option>
                    @endforeach
                </select>
            </div>
            <div>
                <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status Pengeluaran</label>
                <select id="status" name="status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                    <option value="">Semua Status</option>
                    @foreach($statuses as $stat)
                        <option value="{{ $stat }}" {{ $status == $stat ? 'selected' : '' }}>
                            @if($stat == 'draft')
                                Draft
                            @elseif($stat == 'approved')
                                Disetujui
                            @elseif($stat == 'rejected')
                                Ditolak
                            @endif
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="lg:col-span-5 flex justify-end">
                <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
                    <i class="fas fa-filter mr-2"></i>Filter
                </button>
            </div>
        </form>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-md p-6">
            <h3 class="text-lg font-semibold mb-2">Total Pendapatan</h3>
            <p class="text-3xl font-bold text-green-600">Rp {{ number_format($totalIncomes, 0, ',', '.') }}</p>
        </div>
        <div class="bg-white rounded-lg shadow-md p-6">
            <h3 class="text-lg font-semibold mb-2">Total Pengeluaran</h3>
            <p class="text-3xl font-bold text-red-600">Rp {{ number_format($totalExpenses, 0, ',', '.') }}</p>
        </div>
        <div class="bg-white rounded-lg shadow-md p-6">
            <h3 class="text-lg font-semibold mb-2">Saldo</h3>
            <p class="text-3xl font-bold {{ $balance >= 0 ? 'text-green-600' : 'text-red-600' }}">
                Rp {{ number_format($balance, 0, ',', '.') }}
            </p>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow-md p-6">
            <h3 class="text-lg font-semibold mb-4">Perbandingan Pendapatan & Pengeluaran</h3>
            <canvas id="incomeExpenseChart" width="400" height="300"></canvas>
        </div>
        <div class="bg-white rounded-lg shadow-md p-6">
            <h3 class="text-lg font-semibold mb-4">Pendapatan & Pengeluaran per Kategori</h3>
            <canvas id="categoryComparisonChart" width="400" height="300"></canvas>
        </div>
    </div>

    <div class="grid grid-cols-1 gap-6">
        <div class="bg-white rounded-lg shadow-md overflow-hidden">
            <h3 class="text-lg font-semibold p-6 border-b">Daftar Pendapatan</h3>
            @if($incomes->count() > 0)
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Judul</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Jumlah</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kategori</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Proyek</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            @foreach($incomes as $income)
                                <tr>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ $income->title }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">Rp {{ number_format($income->amount, 0, ',', '.') }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $income->income_date->format('d/m/Y') }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $income->category }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $income->project ? $income->project->name : 'Tidak Ada' }}</td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <div class="p-6 text-center text-gray-500">
                    Tidak ada data pendapatan yang sesuai dengan filter.
                </div>
            @endif
        </div>

        <div class="bg-white rounded-lg shadow-md overflow-hidden">
            <h3 class="text-lg font-semibold p-6 border-b">Daftar Pengeluaran</h3>
            @if($expenses->count() > 0)
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Judul</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Jumlah</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Kategori</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Proyek</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            @foreach($expenses as $expense)
                                <tr>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ $expense->title }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">Rp {{ number_format($expense->amount, 0, ',', '.') }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $expense->expense_date->format('d/m/Y') }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $expense->category }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $expense->project ? $expense->project->name : 'Tidak Ada' }}</td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        @if($expense->status == 'draft')
                                            <span class="px-2 py-1 bg-yellow-100 text-yellow-800 rounded-full text-xs">Draft</span>
                                        @elseif($expense->status == 'approved')
                                            <span class="px-2 py-1 bg-green-100 text-green-800 rounded-full text-xs">Disetujui</span>
                                        @elseif($expense->status == 'rejected')
                                            <span class="px-2 py-1 bg-red-100 text-red-800 rounded-full text-xs">Ditolak</span>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @else
                <div class="p-6 text-center text-gray-500">
                    Tidak ada data pengeluaran yang sesuai dengan filter.
                </div>
            @endif
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Data untuk grafik perbandingan pendapatan & pengeluaran
    const incomeExpenseData = {
        labels: ['Pendapatan', 'Pengeluaran'],
        datasets: [{
            data: [{{ $totalIncomes }}, {{ $totalExpenses }}],
            backgroundColor: ['#10B981', '#EF4444'],
            borderWidth: 1
        }]
    };
    
    // Buat grafik perbandingan pendapatan & pengeluaran
    const ctxIncomeExpense = document.getElementById('incomeExpenseChart').getContext('2d');
    new Chart(ctxIncomeExpense, {
        type: 'pie',
        data: incomeExpenseData,
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'right',
                }
            }
        }
    });
    
    // Hitung pendapatan dan pengeluaran per kategori
    const incomesByCategory = {};
    const expensesByCategory = {};
    
    @foreach($incomes->groupBy('category') as $category => $items)
        incomesByCategory['{{ $category }}'] = {{ $items->sum('amount') }};
    @endforeach
    
    @foreach($expenses->groupBy('category') as $category => $items)
        expensesByCategory['{{ $category }}'] = {{ $items->sum('amount') }};
    @endforeach
    
    // Gabungkan kategori dari pendapatan dan pengeluaran
    const allCategories = [...new Set([...Object.keys(incomesByCategory), ...Object.keys(expensesByCategory)])];
    
    // Siapkan data untuk grafik perbandingan per kategori
    const categoryComparisonData = {
        labels: allCategories,
        datasets: [
            {
                label: 'Pendapatan',
                data: allCategories.map(category => incomesByCategory[category] || 0),
                backgroundColor: '#10B981',
                borderWidth: 1
            },
            {
                label: 'Pengeluaran',
                data: allCategories.map(category => expensesByCategory[category] || 0),
                backgroundColor: '#EF4444',
                borderWidth: 1
            }
        ]
    };
    
    // Buat grafik perbandingan per kategori
    const ctxCategoryComparison = document.getElementById('categoryComparisonChart').getContext('2d');
    new Chart(ctxCategoryComparison, {
        type: 'bar',
        data: categoryComparisonData,
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return 'Rp ' + value.toLocaleString('id-ID');
                        }
                    }
                }
            }
        }
    });
    
    // Fungsi untuk export ke PDF
    function exportToPDF() {
        window.location.href = '{{ route("reports.financial.export.pdf") }}' + window.location.search;
    }
    
    // Fungsi untuk export ke Excel
    function exportToExcel() {
        window.location.href = '{{ route("reports.financial.export.excel") }}' + window.location.search;
    }
</script>
@endpush
@endsection