@extends('layouts.app')

@section('content')

@php
    $chartLabels = [];
    $chartBiayaData = [];
    $chartProfitData = [];
    
    foreach($proyeks as $proyek) {
        // [PERBAIKAN] Pastikan data untuk chart juga float
        $totalBiaya = (float) ($proyek->total_pengeluaran ?? 0) + (float) ($proyek->total_upah ?? 0);
        $profitLoss = (float) ($proyek->nilai_kontrak ?? 0) - $totalBiaya;
    
        // Hanya masukkan ke chart jika ada datanya
        if ($totalBiaya > 0 || $profitLoss !== 0) {
            $chartLabels[] = $proyek->nama_proyek;
            $chartBiayaData[] = $totalBiaya;
            $chartProfitData[] = $profitLoss;
        }
    }
@endphp

<div class="space-y-8"
     x-data="{ 
         modalOpen: false, 
         selectedProyek: null,
         formatRupiah(number) {
             if (isNaN(number) || number === null) return 'Rp. 0';
             return 'Rp. ' + new Intl.NumberFormat('id-ID').format(number);
         },
         formatTanggal(tgl) {
             if (!tgl) return '-'; 
             try {
                 const date = new Date(tgl);
                 if (isNaN(date.getTime())) return '-';
                 return date.toLocaleDateString('id-ID', {
                     day: '2-digit', 
                     month: '2-digit', 
                     year: 'numeric'
                 });
             } catch (e) {
                 return '-';
             }
         },
         // [TAMBAHAN] Fungsi helper untuk grouping di JavaScript
         groupBy(array, key) {
             if (!array) return {};
             return array.reduce((result, currentValue) => {
                 (result[currentValue[key] || 'Lain-lain'] = result[currentValue[key] || 'Lain-lain'] || []).push(currentValue);
                 return result;
             }, {});
         },
         // [TAMBAHAN] Fungsi helper untuk subtotal
         sumBy(array, key) {
             if (!array) return 0;
             return array.reduce((sum, item) => sum + (parseFloat(item[key]) || 0), 0);
         }
     }">

    {{-- Bagian Judul Halaman --}}
    <div>
        <h1 class="text-3xl font-bold text-gray-800">Laporan Proyek</h1>
        <p class="text-gray-500 mt-1">Dokumentasi dan ringkasan finansial dari seluruh proyek.</p>
    </div>

    @if (session('error'))
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-lg relative" role="alert">
            <strong class="font-bold">Error!</strong>
            <span class="block sm:inline">{{ session('error') }}</span>
        </div>
    @endif
    
    {{-- Bagian Filter --}}
    <div class="bg-white p-6 rounded-xl shadow-md border border-gray-200">
        <form action="{{ route('report.index') }}" method="GET">
            <div class="grid grid-cols-1 md:grid-cols-12 gap-x-6 gap-y-5">
                
                {{-- Filter Proyek --}}
                <div class="md:col-span-4 lg:col-span-3">
                    <label for="proyek_id" class="block text-sm font-medium text-gray-700 mb-1">Pilih Proyek</label>
                    <select name="proyek_id" id="proyek_id" class="mt-1 block w-full p-2 border border-gray-300 rounded-lg">
                        <option value="semua">Semua Proyek</option>
                        @foreach($all_proyeks as $p_filter)
                            <option value="{{ $p_filter->id_proyek }}" {{ request('proyek_id') == $p_filter->id_proyek ? 'selected' : '' }}>
                                {{ $p_filter->nama_proyek }}
                            </option>
                        @endforeach
                    </select>
                </div>

                {{-- Filter Status --}}
                <div class="md:col-span-4 lg:col-span-3">
                    <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status Proyek</label>
                    <select name="status" id="status" class="mt-1 block w-full p-2 border border-gray-300 rounded-lg">
                        <option value="semua" {{ request('status') == 'semua' ? 'selected' : '' }}>Semua Status</option>
                        <option value="Sedang Berjalan" {{ request('status') == 'Sedang Berjalan' ? 'selected' : '' }}>Sedang Berjalan</option>
                        <option value="Selesai" {{ request('status') == 'Selesai' ? 'selected' : '' }}>Selesai</option>
                    </select>
                </div>

                {{-- Filter Periode (Tanggal) --}}
                <div class="md:col-span-8 lg:col-span-6">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Periode Proyek</label>
                    <div class="flex items-center space-x-3 mt-1">
                        <input type="text" name="tanggal_mulai" id="tanggal_mulai" value="{{ request('tanggal_mulai') }}" class="date-picker w-full p-2 border border-gray-300 rounded-lg" placeholder="Pilih Tanggal Mulai">
                        <span class="text-gray-500 font-semibold">-</span>
                        <input type="text" name="tanggal_selesai" id="tanggal_selesai" value="{{ request('tanggal_selesai') }}" class="date-picker w-full p-2 border border-gray-300 rounded-lg" placeholder="Pilih Tanggal Selesai">
                    </div>
                </div>

            </div>

            {{-- Tombol Aksi --}}
            <div class="flex justify-end items-center mt-6 pt-6 border-t border-gray-200 space-x-4">
                <a href="{{ route('report.index') }}" class="text-sm font-medium text-gray-600 hover:text-gray-900">Reset Filter</a>
                <button type="submit" class="py-2 px-6 rounded-lg text-white bg-blue-600 hover:bg-blue-700">Filter</button>
            </div>
        </form>
    </div>

    {{-- Bagian Summary Cards --}}
     <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="bg-green-50 p-6 rounded-xl border border-green-200">
            <h3 class="text-sm font-medium text-green-800">Total Nilai Kontrak</h3>
            <p class="text-2xl font-bold text-green-900 mt-1">Rp. {{ number_format($summary['total_nilai_kontrak'] ?? 0, 0, ',', '.') }}</p>
        </div>
        <div class="bg-red-50 p-6 rounded-xl border border-red-200">
            <h3 class="text-sm font-medium text-red-800">Total Biaya Proyek</h3>
            <p class="text-2xl font-bold text-red-900 mt-1">Rp. {{ number_format($summary['total_biaya_proyek'] ?? 0, 0, ',', '.') }}</p>
        </div>
        <div class="bg-blue-50 p-6 rounded-xl border border-blue-200">
            <h3 class="text-sm font-medium text-blue-800">Estimasi Profit / Loss</h3>
            <p class="text-2xl font-bold text-blue-900 mt-1">Rp. {{ number_format($summary['total_profit_loss'] ?? 0, 0, ',', '.') }}</p>
        </div>
    </div>

    {{-- Bagian Chart --}}
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="bg-white p-6 rounded-xl shadow-md border border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Distribusi Biaya per Proyek</h3>
            <div class="relative h-72 sm:h-80">
                <canvas id="biayaPieChart"></canvas>
            </div>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-md border border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Profit / Loss per Proyek</h3>
            <div class="relative h-72 sm:h-80">
                <canvas id="profitBarChart"></canvas>
            </div>
        </div>
    </div>


    {{-- Bagian Tabel Laporan --}}
    <div class="bg-white rounded-xl shadow-lg border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="w-12 px-4 py-3"></th>
                        <th class="text-left py-3 px-4 text-xs font-semibold text-gray-600 uppercase tracking-wider">Nama Proyek</th>
                        <th class="text-left py-3 px-4 text-xs font-semibold text-gray-600 uppercase tracking-wider">Status</th>
                        <th class="text-right py-3 px-4 text-xs font-semibold text-gray-600 uppercase tracking-wider">Nilai Kontrak</th>
                        <th class="text-right py-3 px-4 text-xs font-semibold text-gray-600 uppercase tracking-wider">Total Biaya</th>
                        <th class="text-right py-3 px-4 text-xs font-semibold text-gray-600 uppercase tracking-wider">Profit/Loss</th>
                    </tr>
                </thead>
                @forelse($proyeks as $proyek)
                    @php
                        // [PERBAIKAN] Paksa (cast) data ke float untuk matematika JS
                        $totalPengeluaran = (float) ($proyek->total_pengeluaran ?? 0);
                        $totalUpah = (float) ($proyek->total_upah ?? 0);
                        $nilaiKontrak = (float) ($proyek->nilai_kontrak ?? 0);
                        
                        // Kalkulasi ini (sekarang) sudah benar
                        $totalBiaya = $totalPengeluaran + $totalUpah;
                        $profitLoss = $nilaiKontrak - $totalBiaya;

                        // [PERBAIKAN] Buat objek data manual untuk modal, pastikan semua float
                        // [MODIFIKASI] Ambil relasi tukangs dengan kolom yang benar
                        $modalData = [
                            'nama_proyek' => $proyek->nama_proyek,
                            'klien' => $proyek->klien,
                            'nilai_kontrak' => (float) $nilaiKontrak,
                            'total_pengeluaran' => (float) $totalPengeluaran,
                            'total_upah' => (float) $totalUpah,
                            'pengeluarans' => $proyek->pengeluarans, 
                            // [PENTING] Kirim data tukangs yang relevan ke modal
                            'tukangs' => $proyek->tukangs->map(function($t) {
                                return [
                                    'id_tukang' => $t->id_tukang,
                                    'nama_mandor' => $t->nama_mandor,
                                    'tanggal_jatuh_tempo' => $t->tanggal_jatuh_tempo ? $t->tanggal_jatuh_tempo->format('Y-m-d') : null,
                                    'total_pembayaran' => (float) $t->total_pembayaran, // pastikan float
                                    'status_pembayaran' => $t->status_pembayaran
                                ];
                            })
                        ];
                    @endphp
                    
                    <tbody x-data="{ open: false }" class="border-b border-gray-200 last:border-b-0">
                        {{-- Baris Data Utama (Tidak Berubah) --}}
                        <tr @click="open = !open" class="hover:bg-gray-50 transition cursor-pointer">
                            <td class="py-3 px-4 text-center">
                                <button title="Lihat Opsi" class="text-gray-400 hover:text-blue-600 transition">
                                    <svg class="w-5 h-5 transition-transform duration-200" :class="{'rotate-90': open}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path></svg>
                                </button>
                            </td>
                            <td class="py-3 px-4 font-medium text-gray-900">{{ $proyek->nama_proyek ?? 'Nama Proyek Tidak Tersedia' }}</td>
                            <td class="py-3 px-4">
                                @php
                                    $statusClass = '';
                                    switch ($proyek->status ?? '') {
                                        case 'Selesai': $statusClass = 'bg-green-100 text-green-800'; break;
                                        case 'Sedang Berjalan': $statusClass = 'bg-yellow-100 text-yellow-800'; break;
                                        default: $statusClass = 'bg-gray-100 text-gray-800';
                                    }
                                @endphp
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full {{ $statusClass }}">
                                    {{ $proyek->status ?? 'Status Tidak Diketahui' }}
                                </span>
                            </td>
                            <td class="py-3 px-4 text-right">Rp. {{ number_format($nilaiKontrak, 0, ',', '.') }}</td>
                            <td class="py-3 px-4 text-right text-red-600">Rp. {{ number_format($totalBiaya, 0, ',', '.') }}</td>
                            <td class="py-3 px-4 text-right font-bold {{ $profitLoss >= 0 ? 'text-green-600' : 'text-red-600' }}">
                                Rp. {{ number_format($profitLoss, 0, ',', '.') }}
                            </td>
                        </tr>

                        {{-- Baris Tombol Aksi --}}
                        <tr x-show="open" x-transition x-cloak>
                            <td colspan="6" class="p-4 bg-slate-100">
                                <div class="bg-white p-4 border rounded-lg shadow-sm">
                                    <h4 class="font-semibold text-gray-800 border-b pb-2 mb-3">Opsi Laporan</h4>
                                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                                        
                                        {{-- [PERBAIKAN] Menggunakan json_encode($modalData) --}}
                                        <button 
                                            type="button"
                                            @click="selectedProyek = {{ json_encode($modalData) }}; modalOpen = true; $event.stopPropagation()"
                                            class="w-full inline-flex justify-center items-center gap-2 px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" /></svg>
                                            Rincian Pengeluaran Proyek
                                        </button>

                                        <a href="{{ route('report.export', $proyek->id_proyek) }}" 
                                           @click="$event.stopPropagation()"
                                           class="w-full inline-flex justify-center items-center gap-2 px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M3 3a2 2 0 012-2h10a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2V3zm2 2v10h10V5H5zM8 8a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1zm0 4a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1z" clip-rule="evenodd" /></svg>
                                            Eksport CSV
                                        </a>
                                        
                                        <a href="{{ route('report.exportPdf', $proyek->id_proyek) }}" 
                                           @click="$event.stopPropagation()"
                                           class="w-full inline-flex justify-center items-center gap-2 px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4zm2 6a1 1 0 011-1h6a1 1 0 110 2H7a1 1 0 01-1-1zm1 3a1 1 0 100 2h6a1 1 0 100-2H7z" clip-rule="evenodd" /></svg>
                                            Eksport PDF
                                        </a>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </tbody>

                @empty
                    <tbody>
                        <tr>
                            <td colspan="6" class="py-12 text-center text-gray-500">
                                <p class="text-lg">Tidak ada data proyek.</p>
                                <p class="text-sm">Silakan ubah filter atau tambahkan data proyek baru.</p>
                            </td>
                        </tr>
                    </tbody>
                @endforelse
                
            </table>
        </div>
    </div>

    <div x-show="modalOpen" 
         x-transition:enter="ease-out duration-300"
         x-transition:enter-start="opacity-0"
         x-transition:enter-end="opacity-100"
         x-transition:leave="ease-in duration-200"
         x-transition:leave-start="opacity-100"
         x-transition:leave-end="opacity-0"
         class="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6" 
         style="display: none;"
         x-cloak>

        {{-- Latar belakang modal --}}
        <div x-show="modalOpen" 
             @click="modalOpen = false" 
             x-transition:enter="ease-out duration-300"
             x-transition:enter-start="opacity-0"
             x-transition:enter-end="opacity-100"
             x-transition:leave="ease-in duration-200"
             x-transition:leave-start="opacity-100"
             x-transition:leave-end="opacity-0"
             class="fixed inset-0 bg-gray-900/75 transition-opacity"></div> 

        {{-- Konten Modal --}}
        <div x-show="modalOpen"
             x-transition:enter="ease-out duration-300"
             x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
             x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
             x-transition:leave="ease-in duration-200"
             x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
             x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
             @click.stop
             class="relative bg-slate-100 rounded-xl shadow-xl w-full max-w-7xl max-h-[90vh] flex flex-col overflow-hidden">
            
            <template x-if="selectedProyek">
                <div class="flex-1 overflow-y-auto">
                    
                    {{-- Header Modal --}}
                    <div class="flex justify-between items-center p-4 sm:p-5 bg-white border-b sticky top-0 z-10">
                        <div>
                            <h3 class="text-lg font-bold text-gray-900" 
                                x-text="'Rincian Proyek: ' + (selectedProyek.nama_proyek || 'Tidak Ada Nama')">
                            </h3>
                            <p class="text-sm text-gray-500" x-text="'Klien: ' + (selectedProyek.klien || '-')"></p>
                        </div>
                        <button @click="modalOpen = false" class="text-gray-400 hover:text-gray-600 transition">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                        </button>
                    </div>

                    {{-- Body Modal --}}
                    <div class="p-4 sm:p-6 space-y-6">
                        
                        {{-- Ringkasan Finansial --}}
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div class="bg-green-50 p-4 rounded-lg border border-green-200">
                                <h4 class="text-xs font-medium text-green-700 uppercase tracking-wider">Nilai Kontrak</h4>
                                <p class="text-xl font-bold text-green-900 mt-1" x-text="formatRupiah(selectedProyek.nilai_kontrak || 0)"></p>
                            </div>
                            <div class="bg-red-50 p-4 rounded-lg border border-red-200">
                                <h4 class="text-xs font-medium text-red-700 uppercase tracking-wider">Total Biaya</h4>
                                <p class="text-xl font-bold text-red-900 mt-1" x-text="formatRupiah((selectedProyek.total_pengeluaran || 0) + (selectedProyek.total_upah || 0))"></p>
                            </div>
                            <div class="bg-blue-50 p-4 rounded-lg border border-blue-200">
                                <h4 class="text-xs font-medium text-blue-700 uppercase tracking-wider">Estimasi Profit/Loss</h4>
                                <p class="text-xl font-bold mt-1"
                                   :class="{
                                       'text-green-600': (selectedProyek.nilai_kontrak || 0) - ((selectedProyek.total_pengeluaran || 0) + (selectedProyek.total_upah || 0)) >= 0,
                                       'text-red-600': (selectedProyek.nilai_kontrak || 0) - ((selectedProyek.total_pengeluaran || 0) + (selectedProyek.total_upah || 0)) < 0
                                   }"
                                   x-text="formatRupiah( (selectedProyek.nilai_kontrak || 0) - ((selectedProyek.total_pengeluaran || 0) + (selectedProyek.total_upah || 0)) )">
                                </p>
                            </div>
                        </div>

                        {{-- Grid Tabel Rincian --}}
                        <div class="space-y-6">
                            
                            {{-- [MODIFIKASI] Tabel Pembayaran Material (Grouped by Toko) --}}
                            <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
                                <h4 class="font-semibold text-gray-800 bg-gray-50 p-3 border-b">Rincian Pembayaran Material</h4>
                                
                                {{-- Loop berdasarkan Toko/Vendor --}}
                                <template x-if="selectedProyek.pengeluarans && selectedProyek.pengeluarans.length > 0">
                                    <div class="space-y-4 p-3">
                                        <template x-for="[toko, items] in Object.entries(groupBy(selectedProyek.pengeluarans, 'toko'))" :key="toko">
                                            <div class="border rounded-lg overflow-hidden">
                                                <h5 class="font-semibold text-gray-700 bg-gray-100 p-3 text-sm" 
                                                    x-text="toko || 'Toko Tidak Teridentifikasi'">
                                                </h5>
                                                <div class="overflow-auto max-h-72 text-sm">
                                                    <table class="min-w-full">
                                                        <thead class="bg-gray-100 sticky top-0">
                                                            <tr>
                                                                <th class="text-left font-semibold text-gray-600 p-3">Tanggal</th>
                                                                <th class="text-left font-semibold text-gray-600 p-3">Deskripsi</th>
                                                                <th class="text-left font-semibold text-gray-600 p-3">Kategori</th>
                                                                <th class="text-right font-semibold text-gray-600 p-3">Jumlah</th>
                                                                <th class="text-left font-semibold text-gray-600 p-3">Status Bayar</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody class="divide-y divide-gray-200">
                                                            <template x-for="(p, index) in items" :key="p.id_pengeluaran">
                                                                <tr class="align-top" :class="index % 2 === 0 ? 'bg-white' : 'bg-gray-50'">
                                                                    <td class="p-3 whitespace-nowrap" x-text="formatTanggal(p.tanggal_struk)"></td>
                                                                    <td class="p-3 whitespace-normal min-w-[200px]" x-text="p.items || '-'"></td>
                                                                    <td class="p-3 whitespace-nowrap" x-text="p.kategori || '-'"></td>
                                                                    <td class="p-3 text-right whitespace-nowrap font-medium">
                                                                        <span x-text="formatRupiah(p.total)"></span>
                                                                    </td>
                                                                    <td class="p-3 whitespace-nowrap">
                                                                        <span class="px-2 py-1 text-xs font-semibold rounded-full"
                                                                            :class="{
                                                                                'bg-green-100 text-green-800': p.status_bayar === 'Sudah Bayar',
                                                                                'bg-red-100 text-red-800': p.status_bayar === 'Belum Bayar'
                                                                            }"
                                                                            x-text="p.status_bayar || '-'">
                                                                        </span>
                                                                    </td>
                                                                </tr>
                                                            </template>
                                                            {{-- Sub-Total per Toko --}}
                                                            <tr class="bg-gray-100 font-bold">
                                                                <td colspan="3" class="p-3 text-right text-gray-700">Total</td>
                                                                <td class="p-3 text-right text-gray-900">
                                                                    <span x-text="formatRupiah(sumBy(items, 'total'))"></span>
                                                                </td>
                                                                <td class="p-3"></td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </template>
                                        
                                        {{-- Total Keseluruhan Material --}}
                                        <div class="bg-gray-800 text-white p-3 rounded-lg flex justify-between items-center mt-4">
                                            <span class="font-bold text-base">Total Keseluruhan Material</span>
                                            <span class="font-bold text-base" x-text="formatRupiah(selectedProyek.total_pengeluaran)"></span>
                                        </div>
                                    </div>
                                </template>

                                <template x-if="!selectedProyek.pengeluarans || selectedProyek.pengeluarans.length === 0">
                                    <p class="text-sm text-gray-500 p-4">- Tidak ada data pengeluaran material -</p>
                                </template>
                            </div>

                            {{-- [MODIFIKASI] Tabel Pembayaran Tukang (Grouped by Mandor) --}}
                            <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
                                <h4 class="font-semibold text-gray-800 bg-gray-50 p-3 border-b">Rincian Pembayaran Tukang</h4>

                                <template x-if="selectedProyek.tukangs && selectedProyek.tukangs.length > 0">
                                    <div class="space-y-4 p-3">
                                        {{-- Loop berdasarkan Mandor --}}
                                        <template x-for="[mandor, items] in Object.entries(groupBy(selectedProyek.tukangs, 'nama_mandor'))" :key="mandor">
                                            <div class="border rounded-lg overflow-hidden">
                                                <h5 class="font-semibold text-gray-700 bg-gray-100 p-3 text-sm" 
                                                    x-text="mandor || 'Mandor Tidak Teridentifikasi'">
                                                </h5>
                                                <div class="overflow-auto max-h-72 text-sm">
                                                    <table class="min-w-full">
                                                        <thead class="bg-gray-100 sticky top-0">
                                                            <tr>
                                                                <th class="text-left font-semibold text-gray-600 p-3">Jatuh Tempo</th>
                                                                <th class="text-right font-semibold text-gray-600 p-3">Jumlah (Rp)</th>
                                                                <th class="text-left font-semibold text-gray-600 p-3">Status Bayar</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody class="divide-y divide-gray-200">
                                                            <template x-for="(t, index) in items" :key="t.id_tukang">
                                                                <tr :class="index % 2 === 0 ? 'bg-white' : 'bg-gray-50'">
                                                                    <td class="p-3 whitespace-nowrap" x-text="formatTanggal(t.tanggal_jatuh_tempo)"></td>
                                                                    <td class="p-3 text-right whitespace-nowrap font-medium">
                                                                        {{-- Gunakan 'total_pembayaran' sesuai data $modalData --}}
                                                                        <span x-text="formatRupiah(t.total_pembayaran)"></span> 
                                                                    </td>
                                                                    <td class="p-3 whitespace-nowrap">
                                                                        <span class="px-2 py-1 text-xs font-semibold rounded-full"
                                                                            :class="{
                                                                                'bg-green-100 text-green-800': t.status_pembayaran === 'Lunas',
                                                                                'bg-red-100 text-red-800': t.status_pembayaran !== 'Lunas'
                                                                            }"
                                                                            x-text="t.status_pembayaran || '-'">
                                                                        </span>
                                                                    </td>
                                                                </tr>
                                                            </template>
                                                            {{-- Sub-Total per Mandor --}}
                                                            <tr class="bg-gray-100 font-bold">
                                                                <td class="p-3 text-right text-gray-700">Total</td>
                                                                <td class="p-3 text-right text-gray-900">
                                                                    <span x-text="formatRupiah(sumBy(items, 'total_pembayaran'))"></span>
                                                                </td>
                                                                <td class="p-3"></td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </template>
                                        
                                        {{-- Total Keseluruhan Tukang --}}
                                        <div class="bg-gray-800 text-white p-3 rounded-lg flex justify-between items-center mt-4">
                                            <span class="font-bold text-base">Total Keseluruhan Upah</span>
                                            <span class="font-bold text-base" x-text="formatRupiah(selectedProyek.total_upah)"></span>
                                        </div>
                                    </div>
                                </template>
                                
                                <template x-if="!selectedProyek.tukangs || selectedProyek.tukangs.length === 0">
                                    <p class="text-sm text-gray-500 p-4">- Tidak ada data upah tukang -</p>
                                </template>
                            </div>

                        </div>
                    </div>
                </div>
            </template>
            
            {{-- Fallback jika data belum load --}}
            <template x-if="!selectedProyek">
                 <div class="p-6 text-center text-gray-500">Memuat data...</div>
            </template>
        </div>
    </div>
</div>
@endsection

@push('scripts')
{{-- Ini adalah CSS untuk flatpickr --}}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
{{-- Ini adalah JS untuk flatpickr --}}
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
{{-- Ini adalah JS untuk Chart.js --}}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        
        // Script Flatpickr (sudah ada)
        flatpickr('.date-picker', {
            altInput: true,       // Membuat input visual yang ramah (datestring)
            altFormat: "d M Y",   // Format datestring (Contoh: 25 Okt 2025)
            dateFormat: "Y-m-d",  // Format data asli yang dikirim ke server (Contoh: 2025-10-25)
        });
        
        // 1. Ambil data proyek dari variabel Blade yang sudah diolah di PHP
        const labels = @json($chartLabels);
        const totalBiayaData = @json($chartBiayaData);
        const profitLossData = @json($chartProfitData);

        const profitLossColors = [];
        
        // Fungsi helper untuk format Rupiah di tooltip
        const formatRupiah = (number) => {
             if (isNaN(number)) return 'Rp. 0';
             return 'Rp. ' + new Intl.NumberFormat('id-ID').format(number);
        };

        // 3. Olah data (HANYA WARNA)
        // Data angka sudah diolah di PHP
        profitLossData.forEach(profitLoss => {
            // Tentukan warna bar (hijau untuk profit, merah untuk loss)
            if (profitLoss >= 0) {
                profitLossColors.push('rgba(22, 163, 74, 0.6)'); // Hijau (profit)
            } else {
                profitLossColors.push('rgba(220, 38, 38, 0.6)'); // Merah (loss)
            }
        });

        // 4. Inisialisasi Pie Chart (Distribusi Biaya)
        const pieCtx = document.getElementById('biayaPieChart');
        if (pieCtx && totalBiayaData.length > 0) {
            new Chart(pieCtx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Total Biaya',
                        data: totalBiayaData, // [PERBAIKAN] Gunakan data bersih
                        backgroundColor: [
                            'rgba(59, 130, 246, 0.7)',
                            'rgba(239, 68, 68, 0.7)',
                            'rgba(16, 185, 129, 0.7)',
                            'rgba(245, 158, 11, 0.7)',
                            'rgba(107, 114, 128, 0.7)',
                            'rgba(139, 92, 246, 0.7)'
                        ],
                        borderColor: 'rgba(255, 255, 255, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.label || '';
                                    let value = context.raw || 0;
                                    let sum = 0;
                                    context.chart.data.datasets[0].data.forEach(data => {
                                        sum += data;
                                    });
                                    let percentage = (value / sum * 100).toFixed(2) + '%';
                                    return `${label}: ${formatRupiah(value)} (${percentage})`;
                                }
                            }
                        }
                    }
                }
            });
        } else if (pieCtx) {
            // Tampilkan pesan jika tidak ada data
            const ctx = pieCtx.getContext('2d');
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillStyle = '#6B7280'; // gray-500
            ctx.font = '16px sans-serif';
            ctx.fillText("Tidak ada data biaya untuk ditampilkan", pieCtx.width / 2, pieCtx.height / 2);
        }

        // 5. Inisialisasi Bar Chart (Profit/Loss)
        const barCtx = document.getElementById('profitBarChart');
        if (barCtx && profitLossData.length > 0) {
            new Chart(barCtx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Profit / Loss',
                        data: profitLossData, // [PERBAIKAN] Gunakan data bersih
                        backgroundColor: profitLossColors,
                        borderColor: profitLossColors.map(color => color.replace('0.6', '1')),
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            ticks: {
                                callback: function(value, index, values) {
                                    if (Math.abs(value) >= 1000000000) return 'Rp ' + (value / 1000000000) + ' M';
                                    if (Math.abs(value) >= 1000000) return 'Rp ' + (value / 1000000) + ' Jt';
                                    if (Math.abs(value) >= 1000) return 'Rp ' + (value / 1000) + ' Rb';
                                    return 'Rp ' + value;
                                }
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: false 
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    let value = context.raw || 0;
                                    return `${label}: ${formatRupiah(value)}`;
                                }
                            }
                        }
                    }
                }
            });
        } else if (barCtx) {
            // Tampilkan pesan jika tidak ada data
            const ctx = barCtx.getContext('2d');
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillStyle = '#6B7280'; // gray-500
            ctx.font = '16px sans-serif';
            ctx.fillText("Tidak ada data profit/loss untuk ditampilkan", barCtx.width / 2, barCtx.height / 2);
        }

    });
</script>
@endpush