@extends('layouts.app')

@section('content')
{{-- [DIUBAH] Tambahkan state untuk modal hapus ke x-data yang sudah ada --}}
<div x-data="{ 
    showModal: false, 
    modalContent: '', 
    modalTitle: '', 
    showDeleteModal: false, 
    deleteModalAction: '', 
    deleteModalMessage: '',
    deleteModalTitle: ''
}">

    <div class="space-y-8"> 
        {{-- Header halaman & notifikasi --}}
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Laporan Pengeluaran Proyek</h1>
                <p class="text-gray-500 mt-1">Lacak semua pengeluaran proyek Anda.</p>
            </div>
            <a href="{{ route('pengeluaran.create') }}" class="px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700">
                + Catat Pengeluaran
            </a>
        </div>
        @if(session('success'))
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded-lg mb-6" role="alert">
                <p>{{ session('success') }}</p>
            </div>
        @endif


        {{-- Panel Filter --}}
        <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-200">
            <form id="filter-form" action="{{ route('pengeluaran.index') }}" method="GET">
                <div class="grid grid-cols-1 md:grid-cols-12 gap-x-6 gap-y-4 items-end">
                    <div class="lg:col-span-2">
                        <label for="proyek_id" class="block text-sm font-medium text-gray-700">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 Proyek</option>
                            @foreach($proyeks as $proyek)
                                <option value="{{ $proyek->id_proyek }}" {{ request('proyek_id') == $proyek->id_proyek ? 'selected' : '' }}>
                                    {{ $proyek->nama_proyek }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="lg:col-span-2">
                        <label for="vendor" class="block text-sm font-medium text-gray-700">Toko / Vendor</label>
                        <select name="vendor" id="vendor" class="mt-1 block w-full p-2 border border-gray-300 rounded-lg">
                            <option value="">Semua Vendor</option>
                            @foreach($listVendor ?? [] as $vendor)
                                <option value="{{ $vendor }}" {{ request('vendor') == $vendor ? 'selected' : '' }}>{{ $vendor }}</option>
                            @endforeach
                        </select>
                    </div>
                    
                    {{-- Filter Kategori --}}
                    <div class="lg:col-span-2">
                        <label for="kategori" class="block text-sm font-medium text-gray-700">Kategori</label>
                        <select name="kategori" id="kategori" class="mt-1 block w-full p-2 border border-gray-300 rounded-lg">
                            <option value="">Semua Kategori</option>
                            @foreach($kategoriList as $kategori)
                                <option value="{{ $kategori }}" {{ request('kategori') == $kategori ? 'selected' : '' }}>{{ $kategori }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="lg:col-span-2">
                        <label for="jenis" class="block text-sm font-medium text-gray-700">Jenis</label>
                        <select name="jenis" id="jenis" class="mt-1 block w-full p-2 border border-gray-300 rounded-lg">
                            <option value="">Semua Jenis</option>
                            <option value="Pengeluaran" {{ request('jenis') == 'Pengeluaran' ? 'selected' : '' }}>Pengeluaran</option>
                            <option value="Tagihan" {{ request('jenis') == 'Tagihan' ? 'selected' : '' }}>Tagihan (Jatuh Tempo <= 5 Hari)</option>
                        </select>
                    </div>
                    
                    <div class="lg:col-span-2">
                        <label class="block text-sm font-medium text-gray-700">Tanggal</label>
                        <div class="flex items-center space-x-2 mt-1">
                            <input type="text" name="periode_mulai" value="{{ request('periode_mulai') }}" class="date-picker w-full p-2 border border-gray-300 rounded-lg" placeholder="Tgl Mulai">
                            <span class="text-gray-500">-</span>
                            <input type="text" name="periode_selesai" value="{{ request('periode_selesai') }}" class="date-picker w-full p-2 border border-gray-300 rounded-lg" placeholder="Tgl Selesai">
                        </div>
                    </div>
                    
                    <div class="lg:col-span-2">
                        <label for="status_bayar" class="block text-sm font-medium text-gray-700">Status Bayar</label>
                        <select name="status_bayar" id="status_bayar" class="mt-1 block w-full p-2 border border-gray-300 rounded-lg">
                            <option value="">Semua Status</option>
                            <option value="Sudah Bayar" {{ request('status_bayar') == 'Sudah Bayar' ? 'selected' : '' }}>Sudah Bayar</option>
                            <option value="Belum Bayar" {{ request('status_bayar') == 'Belum Bayar' ? 'selected' : '' }}>Belum Bayar</option>
                        </select>
                    </div>
                </div>
                
                <div class="flex justify-end items-center mt-6 pt-6 border-t border-gray-200 space-x-4">
                    <a href="{{ route('pengeluaran.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>
                    <a href="{{ route('pengeluaran.exportPdf', request()->query()) }}" target="_blank" class="py-2 px-6 rounded-lg text-white bg-green-600 hover:bg-green-700">Export PDF</a>
                </div>
            </form>
        </div>

        {{-- Panel Info Dana Proyek --}}
        @if(isset($selectedProyekData))
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="bg-blue-50 p-4 rounded-xl border border-blue-200">
                    <h3 class="text-sm font-medium text-blue-800">Proyek Dipilih</h3>
                    <p class="text-lg font-bold text-blue-900 mt-1 truncate" title="{{ $selectedProyekData['nama_proyek'] }}">
                        {{ $selectedProyekData['nama_proyek'] }}
                    </p>
                </div>
                <div class="bg-green-50 p-4 rounded-xl border border-green-200">
                    <h3 class="text-sm font-medium text-green-800">Total Dana Proyek (Kontrak)</h3>
                    <p class="text-lg font-bold text-green-900 mt-1">
                        Rp. {{ number_format($selectedProyekData['total_nilai_kontrak'], 0, ',', '.') }}
                    </p>
                </div>
                <div class="bg-orange-50 p-4 rounded-xl border border-orange-200">
                    <h3 class="text-sm font-medium text-orange-800">Sisa Dana Proyek</h3>
                    <p class="text-lg font-bold {{ $selectedProyekData['sisa_dana'] < 0 ? 'text-red-600' : 'text-orange-900' }} mt-1">
                        Rp. {{ number_format($selectedProyekData['sisa_dana'], 0, ',', '.') }}
                    </p>
                </div>
            </div>
        @endif

        {{-- Tabel Data --}}
        <div class="bg-white p-6 rounded-lg shadow-lg">
            <div class="overflow-x-auto">
                <table class="min-w-full bg-white">
                    <thead class="bg-gray-100">
                        <tr>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Proyek</th>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Toko / Vendor</th>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Kategori</th>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Tanggal Struk</th>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Nominal</th>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Jenis</th>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Status Bayar</th>
                            <th class="py-3 px-4 text-left text-sm font-semibold text-gray-600 uppercase whitespace-nowrap">Aksi</th>
                        </tr>
                    </thead>

            <tbody class="divide-y divide-gray-200">
                @forelse ($items as $item)
               @php
                    $jenis = 'Pengeluaran';
                    $jenisClass = 'bg-blue-100 text-blue-800';
                    $statusText = $item->status_bayar;
                    $statusClass = strtolower($item->status_bayar) == 'sudah bayar' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
                    if (strtolower($item->status_bayar) == 'belum bayar' && $item->tanggal_bayar) {
                        // Pastikan tanggal_bayar adalah objek Carbon
                        $dueDate = \Carbon\Carbon::parse($item->tanggal_bayar)->startOfDay();
                        $now = \Carbon\Carbon::now()->startOfDay();
                        $diff = $now->diffInDays($dueDate, false);
                        if ($diff < 0) {
                            $jenis = 'Jatuh Tempo';
                            $jenisClass = 'bg-red-200 text-red-900 font-bold';
                            $statusText = 'Jatuh Tempo';
                            $statusClass = 'bg-red-200 text-red-900 font-bold';
                        } elseif ($diff <= 5) {
                            $jenis = 'Tagihan';
                            $jenisClass = 'bg-orange-100 text-orange-800';
                            $statusText = 'Segera Jatuh Tempo';
                            $statusClass = 'bg-orange-100 text-orange-800';
                        }
                    }
                @endphp
                <tr>
                    <td class="py-3 px-4 font-medium whitespace-nowrap">{{ $item->proyek->nama_proyek ?? 'N/A' }}</td>
                    <td class="py-3 px-4">{{ $item->toko }}</td>
                    <td class="py-3 px-4">{{ $item->kategori ?? '-' }}</td>
                    <td class="py-3 px-4">{{ \Carbon\Carbon::parse($item->tanggal_struk)->format('d M Y') }}</td>
                    
                    <td class="py-3 px-4 font-semibold whitespace-nowrap">
                        <button @click="showModal = true; modalContent = `{{ nl2br(e($item->items)) }}`; modalTitle = 'Rincian Pengeluaran'" class="text-blue-600 hover:underline cursor-pointer text-left">
                            Rp. {{ number_format($item->total, 0, ',', '.') }}
                        </button>
                    </td>
                    
                    <td class="py-3 px-4">
                        <span class="px-2 py-1 text-xs font-semibold rounded-full {{ $jenisClass }}">
                            {{ $jenis }}
                        </span>
                    </td>
                    <td class="py-3 px-4">
                        <span class="px-2 py-1 text-xs font-semibold rounded-full {{ $statusClass }}">
                            {{ $statusText }}
                        </span>
                    </td>

                    <td class="py-3 px-4 flex items-center space-x-2 whitespace-nowrap">
                        
                        @if($item->bukti_struk)
                            <button 
                                type="button"
                                @click="
                                    showModal = true; 
                                    modalTitle = 'Bukti Struk: {{ e($item->toko) }}';
                                    modalContent = '<img src=\'{{ Storage::url($item->bukti_struk) }}\' alt=\'Bukti Struk\' class=\'w-full h-auto rounded-md\'>';
                                "
                                class="bg-blue-500 hover:bg-blue-600 text-white font-bold py-1 px-3 rounded text-xs">
                                Struk
                            </button>
                        @else
                            <button 
                                type="button"
                                @click="
                                    showModal = true; 
                                    modalTitle = 'Informasi Struk';
                                    modalContent = '<p class=\'text-gray-700\'>Tidak memiliki struk, mohon input terlebih dahulu.</p>';
                                "
                                class="bg-gray-400 hover:bg-gray-500 text-white font-bold py-1 px-3 rounded text-xs">
                                Struk
                            </button>
                        @endif
                        
                        <a href="{{ route('pengeluaran.edit', $item->id_pengeluaran) }}" class="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-1 px-3 rounded text-xs">Edit</a>
                        
                        {{-- [DIUBAH] Tombol Hapus memicu modal Hard Delete --}}
                        <button type="button" 
                            @click="
                                deleteModalAction = '{{ route('pengeluaran.destroy', $item->id_pengeluaran) }}';
                                deleteModalTitle = 'Hapus Pengeluaran?';
                                deleteModalMessage = 'Anda yakin ingin menghapus data ini: <br><ul class=\'list-disc list-inside mt-2\'><li>Toko: <strong>{{ e($item->toko) }}</strong></li><li>Nominal: <strong>Rp. {{ number_format($item->total, 0, ',', '.') }}</strong></li></ul><br><span class=\'font-bold text-red-600\'>Tindakan ini permanen dan tidak bisa dibatalkan.</span>';
                                showDeleteModal = true;
                            "
                            class="bg-red-500 hover:bg-red-600 text-white font-bold py-1 px-3 rounded text-xs">
                            Hapus
                        </button>
                        {{-- Akhir Perubahan --}}
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="8" class="text-center py-6 text-gray-500">Tidak ada data pengeluaran yang cocok.</td>
                </tr>
                @endforelse
            </tbody>
                </table>
            </div>
        </div>
    
    </div> 
    <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-white rounded-xl shadow-2xl w-full max-w-3xl p-6 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-center pb-3 border-b border-gray-200">
                <h3 class="text-xl font-bold text-gray-800" x-text="modalTitle"></h3>
                <button @click="showModal = false" class="text-gray-500 hover:text-gray-800 text-3xl font-light">&times;</button>
            </div>
            
            <div class="mt-4 prose max-w-none max-h-[80vh] overflow-y-auto text-gray-700 pr-2">
                <div x-html="modalContent"></div>
            </div>
            
            <div class="flex justify-end pt-4 mt-4 border-t border-gray-200">
                <button @click="showModal = false" class="px-4 py-2 bg-gray-600 text-white font-semibold rounded-lg hover:bg-gray-700">
                    Tutup
                </button>
            </div>
        </div>
    </div>
    <div x-show="showDeleteModal" 
     @keydown.escape.window="showDeleteModal = false"
     class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center p-4 z-[9999]" 
     style="display: none;">
    
        <form :action="deleteModalAction" method="POST"
              @click.stop class="bg-white rounded-xl shadow-2xl w-full max-w-md transform transition-all"
              x-show="showDeleteModal"
              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">
            
            @csrf
            @method('DELETE')

            <div class="p-6">
                <div class="flex">
                    {{-- Ikon Peringatan --}}
                    <div class="flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                        <svg class="h-6 w-6 text-red-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" aria-hidden="true">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                    </div>
                    
                    <div class="ml-4 text-left">
                        <h3 class="text-lg leading-6 font-bold text-gray-900" x-text="deleteModalTitle || 'Konfirmasi Hapus'">
                            Konfirmasi Hapus
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-600" x-html="deleteModalMessage">
                                Anda yakin ingin menghapus data ini?
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            
            {{-- [PERBAIKAN] Blok tombol ini dipindahkan ke dalam <form> --}}
            <div class="bg-gray-50 px-6 py-4 flex justify-end space-x-3 rounded-b-xl">
                <button type="button" 
                        @click="showDeleteModal = false" 
                        class="px-4 py-2 bg-white text-gray-700 font-semibold rounded-lg border border-gray-300 hover:bg-gray-50">
                    Batal
                </button>
                <button type="submit" 
                        class="px-4 py-2 bg-red-600 text-white font-semibold rounded-lg hover:bg-red-700">
                    Ya, Hapus
                </button>
            </div>
        </form>
    </div>
    {{-- Akhir dari blok modal --}}


</div> {{-- Ini adalah penutup dari <div x-data="..."> --}}
@endsection

@push('scripts')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        flatpickr('.date-picker', {
            altInput: true,
            altFormat: "d M Y", // Format yang akan dilihat pengguna
            dateFormat: "Y-m-d", // Format yang dikirim ke server
        });
    });
</script>
@endpush