@extends('layouts.Owner') 

@section('content')
{{-- [TETAP] x-data untuk modal ada di sini (ini adalah $root) --}}
<div class="space-y-8" x-data="{ showModal: false, modalContent: '', modalTitle: '' }">
    
    <div>
        <h1 class="text-3xl font-bold text-gray-800">Laporan Keuangan</h1>
        <p class="text-gray-500 mt-1">Ringkasan keuangan dari semua proyek.</p>
    </div>

    {{-- Kartu Statistik (Sekarang menampilkan total gabungan) --}}
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div class="bg-white p-6 rounded-xl shadow-lg border">
            <h2 class="text-sm font-medium text-gray-500">Total Pemasukan</h2>
            <p class="text-3xl font-bold text-green-600 mt-2">Rp. {{ number_format($totalPemasukan, 0, ',', '.') }}</p>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg border">
            <h2 class="text-sm font-medium text-gray-500">Total Pengeluaran (Material + Tukang)</h2>
            <p class="text-3xl font-bold text-red-600 mt-2">Rp. {{ number_format($totalPengeluaran, 0, ',', '.') }}</p>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg border">
            <h2 class="text-sm font-medium text-gray-500">Profit / Loss Global</h2>
            <p class="text-3xl font-bold {{ $profitLoss >= 0 ? 'text-blue-600' : 'text-orange-500' }} mt-2">Rp. {{ number_format($profitLoss, 0, ',', '.') }}</p>
        </div>
    </div>

    {{-- Grafik (Tetap Sama) --}}
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div class="bg-white p-6 rounded-xl shadow-lg border">
            <h3 class="font-bold text-lg mb-4 text-gray-700">Visualisasi Keuangan</h3>
            <canvas id="financialPieChart" style="max-height: 350px;"></canvas>
        </div>
        
        <div class="bg-white p-6 rounded-xl shadow-lg border">
            <h3 class="font-bold text-lg mb-4 text-gray-700">Profit/Loss per Proyek</h3>
            <canvas id="barChart" style="max-height: 350px;"></canvas>
        </div>
    </div>

    {{-- Tabel Rincian Proyek (Accordion) --}}
    <div class="bg-white p-6 rounded-xl shadow-lg border">
        <h3 class="font-bold text-lg mb-4 text-gray-700">Rincian per Proyek</h3>
        <div class="overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="text-left py-2 px-4 font-semibold text-gray-600 uppercase">Nama Proyek</th>
                        <th class="text-right py-2 px-4 font-semibold text-gray-600 uppercase">Pemasukan</th>
                        <th class="text-right py-2 px-4 font-semibold text-gray-600 uppercase">Pengeluaran (Total Biaya)</th>
                        <th class="text-right py-2 px-4 font-semibold text-gray-600 uppercase">Profit/Loss</th>
                    </tr>
                </thead>

                <tbody class="divide-y divide-gray-200" x-data="{ openRow: null }">
                    @forelse($laporanProyek as $proyek)
                        {{-- Baris data utama yang bisa diklik --}}
                        <tr @click="openRow = (openRow === {{ $proyek->id_proyek }}) ? null : {{ $proyek->id_proyek }}" 
                            class="hover:bg-gray-50 cursor-pointer">
                            
                            <td class="py-3 px-4">
                                <div class="flex items-center space-x-2">
                                    <svg class="w-4 h-4 text-gray-400 transform transition-transform" 
                                         :class="{ 'rotate-180': openRow === {{ $proyek->id_proyek }} }" 
                                         fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                                    </svg>
                                    <div>
                                        <div class="font-medium text-gray-800">{{ $proyek->nama_proyek }}</div>
                                        <div class="text-xs text-gray-500">{{ $proyek->status }}</div>
                                    </div>
                                </div>
                            </td>
                            <td class="py-3 px-4 text-right text-green-600 font-medium">Rp. {{ number_format($proyek->nilai_kontrak, 0, ',', '.') }}</td>
                            <td class="py-3 px-4 text-right text-red-600 font-medium">Rp. {{ number_format($proyek->total_pengeluaran, 0, ',', '.') }}</td>
                            <td class="py-3 px-4 text-right font-bold {{ $proyek->profit_loss >= 0 ? 'text-blue-600' : 'text-orange-500' }}">Rp. {{ number_format($proyek->profit_loss, 0, ',', '.') }}</td>
                        </tr>
                        
                        {{-- Baris detail (accordion content) yang tersembunyi --}}
                        <tr x-show="openRow === {{ $proyek->id_proyek }}" x-cloak 
                            x-transition:enter="transition ease-out duration-200"
                            x-transition:enter-start="opacity-0 -translate-y-2"
                            x-transition:enter-end="opacity-100 translate-y-0"
                            x-transition:leave="transition ease-in duration-150"
                            x-transition:leave-start="opacity-100 translate-y-0"
                            x-transition:leave-end="opacity-0 -translate-y-2">
                            
                            <td colspan="4" class="p-4 bg-gray-50">
                                <h4 class="text-sm font-semibold text-gray-700 mb-3">Opsi Laporan</h4>
                                
                                <div class="flex w-full"> 
                                    <button 
                                       type="button"
                                       {{-- 
                                          [PERBAIKAN KRITIS]
                                          Menggunakan @json() untuk mengirim data PHP ke JS dengan aman.
                                          Ini akan memperbaiki error jika ada tanda kutip (') di data Anda.
                                       --}}
                                       @click="openProyekModal($root, @json($proyek))"
                                       class="inline-flex items-center justify-center w-full px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 text-sm transition-colors">
                                        <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg>
                                        Lihat Rincian Pengeluaran
                                    </button>
                                </div>
                            </td>
                        </tr>

                    @empty
                        <tr>
                            <td colspan="4" class="py-4 text-center text-gray-500">Belum ada data proyek.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    {{-- ========================================================= --}}
    {{--         [DIUBAH] HTML Modal Rincian Proyek LENGKAP        --}}
    {{-- ========================================================= --}}
    <div x-show="showModal" 
         @keydown.escape.window="showModal = false"
         @click.self="showModal = false" 
         class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center p-4 z-[9999]" 
         style="display: none;">
        
        <div @click.stop class="bg-gray-100 rounded-xl shadow-2xl w-full max-w-5xl max-h-[90vh] flex flex-col transform transition-all"
             x-show="showModal"
             x-transition:enter="ease-out duration-300"
             x-transition:enter-start="opacity-0 scale-90"
             x-transition:enter-end="opacity-100 scale-100"
             x-transition:leave="ease-in duration-200"
             x-transition:leave-start="opacity-100 scale-100"
             x-transition:leave-end="opacity-0 scale-90">
            
            <div class="flex justify-between items-start p-4 border-b border-gray-200 bg-white rounded-t-xl">
                <div x-html="modalTitle"></div> 
                <button @click="showModal = false" class="text-gray-500 hover:text-gray-800 text-3xl font-light -mt-2 -mr-1">&times;</button>
            </div>
            
            <div class="p-6 overflow-y-auto space-y-6" x-html="modalContent">
                {{-- Konten akan di-generate oleh JS --}}
            </div>
            
        </div>
    </div>

</div> 
@endsection

@push('scripts')

{{-- Pastikan Alpine.js sudah ada di <head> layout Owner.blade.php Anda! --}}

<script>
    // Fungsi helper untuk format Rupiah
    const formatRupiah = (value) => {
        if (value === null || value === undefined) value = 0;
        return 'Rp. ' + Number(value).toLocaleString('id-ID');
    }

    // Fungsi helper untuk format Tanggal
    const formatDate = (dateString) => {
        if (!dateString) return '-';
        // Format: 02/10/2025
        return new Date(dateString).toLocaleDateString('id-ID', {
            day: '2-digit', month: '2-digit', year: 'numeric'
        });
    }

    /**
     * [BARU] Fungsi untuk membangun dan membuka Modal Rincian Proyek LENGKAP
     */
    function openProyekModal(root, proyek) {
        
        // 1. Ambil data total dari objek proyek (sudah dihitung di controller)
        const totalBiaya = proyek.total_pengeluaran || 0; // Ini sudah total gabungan
        const profitLoss = proyek.profit_loss || 0; // Ini sudah profit/loss gabungan

        // 2. Buat HTML Judul
        const titleHtml = `
            <div>
                <h3 class="text-xl font-bold text-gray-800">Rincian Proyek: ${proyek.nama_proyek}</h3>
                <p class="text-sm text-gray-500">Klien: ${proyek.klien || 'N/A'}</p>
            </div>`;

        // 3. Buat HTML Konten
        let contentHtml = `
            {{-- Panel Statistik --}}
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-green-100 p-4 rounded-lg border border-green-200">
                    <h4 class="text-sm font-medium text-green-700">NILAI KONTRAK</h4>
                    <p class="text-2xl font-bold text-green-800">${formatRupiah(proyek.nilai_kontrak)}</p>
                </div>
                <div class="bg-red-100 p-4 rounded-lg border border-red-200">
                    <h4 class="text-sm font-medium text-red-700">TOTAL BIAYA</h4>
                    <p class="text-2xl font-bold text-red-800">${formatRupiah(totalBiaya)}</p>
                </div>
                <div class="bg-blue-100 p-4 rounded-lg border border-blue-200">
                    <h4 class="text-sm font-medium text-blue-700">ESTIMASI PROFIT/LOSS</h4>
                    <p class="text-2xl font-bold ${profitLoss < 0 ? 'text-red-600' : 'text-blue-800'}">
                        ${formatRupiah(profitLoss)}
                    </p>
                </div>
            </div>

            {{-- Tabel Rincian Material (Pengeluaran) --}}
            <div class="bg-white rounded-lg shadow border">
                <h4 class="text-lg font-semibold p-4 border-b">Rincian Pembayaran Material</h4>
                <div class="max-h-60 overflow-y-auto">
                    <table class="min-w-full text-sm">
                        <thead class="bg-gray-50 sticky top-0">
                            <tr>
                                <th class="p-3 text-left font-semibold text-gray-600">Tanggal</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Nama Toko</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Deskripsi</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Kategori</th>
                                <th class="p-3 text-right font-semibold text-gray-600">Jumlah</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Status Bayar</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            ${buildMaterialTable(proyek.pengeluarans)}
                        </tbody>
                    </table>
                </div>
            </div>

            {{-- Tabel Rincian Tukang --}}
            <div class="bg-white rounded-lg shadow border">
                <h4 class="text-lg font-semibold p-4 border-b">Rincian Pembayaran Tukang</h4>
                 <div class="max-h-60 overflow-y-auto">
                    <table class="min-w-full text-sm">
                        <thead class="bg-gray-50 sticky top-0">
                            <tr>
                                <th class="p-3 text-left font-semibold text-gray-600">Nama Tukang</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Grup/Mandor</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Jatuh Tempo</th>
                                <th class="p-3 text-right font-semibold text-gray-600">Jumlah (Rp)</th>
                                <th class="p-3 text-left font-semibold text-gray-600">Status Bayar</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            ${buildTukangTable(proyek.tukangs)}
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        // 4. Set state Alpine
        root.modalTitle = titleHtml;
        root.modalContent = contentHtml;
        root.showModal = true;
    }

    // Helper untuk build tabel material
    function buildMaterialTable(materials) {
        if (!materials || materials.length === 0) {
            return '<tr><td colspan="6" class="p-4 text-center text-gray-500">Tidak ada data material.</td></tr>';
        }
        return materials.map(item => {
            const deskripsi = item.items ? item.items.replace(/\n/g, '<br>') : (item.deskripsi || '-');
            const statusClass = (item.status_bayar.toLowerCase() === 'sudah bayar' || item.status_bayar.toLowerCase() === 'lunas') ? 'text-green-600' : 'text-red-600';
            return `
                <tr class="hover:bg-gray-50">
                    <td class="p-3 whitespace-nowrap">${formatDate(item.tanggal_struk)}</td>
                    <td class="p-3">${item.toko || '-'}</td>
                    <td class="p-3 prose prose-sm max-w-xs">${deskripsi}</td>
                    <td class="p-3">${item.kategori || '-'}</td>
                    <td class="p-3 text-right font-medium whitespace-nowrap">${formatRupiah(item.total)}</td>
                    <td class="p-3 whitespace-nowrap font-medium ${statusClass}">
                        ${item.status_bayar}
                    </td>
                </tr>
            `}).join('');
    }

    // Helper untuk build tabel tukang
    function buildTukangTable(tukangs) {
        if (!tukangs || tukangs.length === 0) {
            return '<tr><td colspan="5" class="p-4 text-center text-gray-500">Tidak ada data tukang.</td></tr>';
        }
        return tukangs.map(item => {
            const statusClass = (item.status_pembayaran.toLowerCase() === 'lunas') ? 'text-green-600' : 'text-red-600';
            return `
                <tr class="hover:bg-gray-50">
                    <td class="p-3">${item.nama_tukang || 'N/A'}</td>
                    <td class="p-3">${item.nama_mandor || '-'}</td>
                    <td class="p-3 whitespace-nowrap">${formatDate(item.tanggal_jatuh_tempo)}</td>
                    <td class="p-3 text-right font-medium whitespace-nowrap">${formatRupiah(item.total_pembayaran)}</td>
                    <td class="p-3 whitespace-nowrap font-medium ${statusClass}">
                         ${item.status_pembayaran}
                    </td>
                </tr>
            `}).join('');
    }

    /**
     * Script Chart.js (Tetap Sama)
     */
    document.addEventListener('DOMContentLoaded', function () {
        
        const chartTooltipOptions = {
            callbacks: {
                label: function(context) {
                    let label = context.dataset.label || context.label || '';
                    if (label) { label += ': '; }
                    if (context.parsed.y !== null || context.parsed !== null) {
                        const value = context.parsed.y ?? context.parsed;
                        label += formatRupiah(value);
                    }
                    return label;
                }
            }
        };

        // 1. Diagram Pie
        const pieCtx = document.getElementById('financialPieChart');
        if (pieCtx) {
            const pieData = @json($pieChartData);
            new Chart(pieCtx, {
                type: 'pie',
                data: {
                    labels: pieData.labels,
                    datasets: [{
                        label: 'Jumlah',
                        data: pieData.values,
                        backgroundColor: ['rgba(54, 162, 235, 0.6)', 'rgba(255, 99, 132, 0.6)'],
                        borderColor: ['rgba(54, 162, 235, 1)', 'rgba(255, 99, 132, 1)'],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { 
                        legend: { position: 'top' },
                        tooltip: chartTooltipOptions
                    }
                }
            });
        }

        // 2. Diagram Batang
        const barCtx = document.getElementById('barChart');
        if (barCtx) {
            const barData = @json($barChartData);
            new Chart(barCtx, {
                type: 'bar',
                data: barData, 
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return formatRupiah(value);
                                }
                            }
                        }
                    },
                    plugins: {
                        legend: { display: false }, 
                        tooltip: chartTooltipOptions
                    }
                }
            });
        }

    });
</script>
@endpush