@extends('layouts.app')

@section('content')
{{-- [PERUBAHAN 1] Tambahkan wrapper x-data untuk mengelola modal hapus --}}
<div x-data="{ 
    showDeleteModal: false, 
    deleteModalAction: '', 
    deleteModalMessage: '',
    deleteModalTitle: ''
}">

    {{-- 'div' ini adalah pembungkus konten Anda yang sudah ada --}}
    <div class="space-y-8">
        {{-- Header Halaman --}}
        <div class="flex justify-between items-center">
            <div>
                <h1 class="text-3xl font-bold text-gray-800">Daftar Pembayaran Tukang</h1>
                <p class="text-gray-500 mt-1">Kelola data pembayaran untuk semua mandor di berbagai proyek.</p>
            </div>
            <a href="{{ route('tukang.create') }}" class="px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700">
                + Tambah Pembayaran
            </a>
        </div>

        {{-- Notifikasi --}}
        @if(session('success'))
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded-lg" 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 action="{{ route('tukang.index') }}" method="GET">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    {{-- Filter by Proyek --}}
                    <div>
                        <label for="filter_id_proyek" class="block text-sm font-medium text-gray-700 mb-1">Filter Proyek</label>
                        <select id="filter_id_proyek" name="id_proyek" class="w-full border-gray-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            <option value="">-- Semua Proyek --</option>
                            @foreach ($proyeks as $proyek)
                                <option value="{{ $proyek->id_proyek }}" {{ request('id_proyek') == $proyek->id_proyek ? 'selected' : '' }}>
                                    {{ $proyek->nama_proyek }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    {{-- Filter by Mandor --}}
                    <div>
                        <label for="filter_nama_mandor" class="block text-sm font-medium text-gray-700 mb-1">Filter Mandor</label>
                        <select id="filter_nama_mandor" name="nama_mandor" class="w-full border-gray-300 rounded-lg shadow-sm focus:border-blue-500 focus:ring-blue-500">
                            <option value="">-- Semua Mandor --</option>
                            @foreach ($mandors as $mandor)
                                <option value="{{ $mandor->nama_mandor }}" {{ request('nama_mandor') == $mandor->nama_mandor ? 'selected' : '' }}>
                                    {{ $mandor->nama_mandor }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    {{-- Tombol Aksi Filter --}}
                    <div class="flex items-end space-x-2">
                        <button type="submit" class="w-full px-4 py-2 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 transition duration-150">
                            Filter
                        </button>
                        <a href="{{ route('tukang.index') }}" class="w-full text-center px-4 py-2 bg-gray-200 text-gray-800 font-bold rounded-lg hover:bg-gray-300 transition duration-150">
                            Reset
                        </a>
                    </div>
                </div>
            </form>
        </div>


        {{-- Tabel Data --}}
        <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-200">
             <div class="overflow-x-auto">
                <table class="min-w-full text-left table-auto">
                    <thead class="bg-gray-100">
                        <tr class="text-gray-600 text-sm uppercase">
                            <th class="p-3 font-semibold whitespace-nowrap">Proyek</th>
                            <th class="p-3 font-semibold whitespace-nowrap">Nama Mandor</th>
                            <th class="p-3 font-semibold whitespace-nowrap">Bukti Absensi</th>
                            <th class="p-3 font-semibold whitespace-nowrap">Total Pembayaran</th>
                            <th class="p-3 font-semibold whitespace-nowrap">Tgl. Jatuh Tempo</th>
                            <th class="p-3 font-semibold whitespace-nowrap">Tgl. Pembayaran</th>
                            <th class="p-3 font-semibold whitespace-nowrap">Bukti Pembayaran</th>
                            <th class="p-3 font-semibold whitespace-nowrap">Status</th>
                            <th class="p-3 font-semibold text-center whitespace-nowrap">Aksi</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        @forelse ($tukangs as $tukang)
                        <tr class="hover:bg-gray-50">
                            <td class="p-3 text-gray-600 whitespace-nowrap">{{ $tukang->proyek->nama_proyek ?? 'N/A' }}</td>
                            <td class="p-3 text-gray-600 whitespace-nowrap">{{ $tukang->nama_mandor }}</td>
                            <td class="p-3 text-gray-600">
                                {{-- Tombol untuk Popup Bukti Absensi --}}
                                @if($tukang->bukti_absensi)
                                    @php
                                        $fileUrl = asset('storage/'. $tukang->bukti_absensi);
                                        $fileType = pathinfo($tukang->bukti_absensi, PATHINFO_EXTENSION) == 'pdf' ? 'pdf' : 'image';
                                    @endphp
                                    <button onclick="openProofModal('{{ $fileUrl }}', '{{ $fileType }}')" class="text-blue-600 hover:underline cursor-pointer">
                                        Lihat
                                    </button>
                                @else
                                    N/A
                                @endif
                            </td>
                            <td class="p-3 text-gray-800 font-semibold whitespace-nowrap">Rp. {{ number_format($tukang->total_pembayaran, 0, ',', '.') }}</td>
                            <td class="p-3 text-gray-600 whitespace-nowrap">{{ \Carbon\Carbon::parse($tukang->tanggal_jatuh_tempo)->format('d M Y') }}</td>
                            <td class="p-3 text-gray-600 whitespace-nowrap">
                                {{ $tukang->tanggal_pembayaran ? \Carbon\Carbon::parse($tukang->tanggal_pembayaran)->format('d M Y') : '-' }}
                            </td>
                             <td class="p-3 text-gray-600">
                                {{-- Tombol untuk Popup Bukti Pembayaran --}}
                                @if($tukang->bukti_pembayaran)
                                    @php
                                        $fileUrl = asset('storage/' . $tukang->bukti_pembayaran);
                                        $fileType = pathinfo($tukang->bukti_pembayaran, PATHINFO_EXTENSION) == 'pdf' ? 'pdf' : 'image';
                                    @endphp
                                    <button onclick="openProofModal('{{ $fileUrl }}', '{{ $fileType }}')" class="text-blue-600 hover:underline cursor-pointer">
                                        Lihat
                                    </button>
                                @else
                                    N/A
                                @endif
                            </td>
                            <td class="p-3 whitespace-nowrap">
                                <span class="px-2.5 py-0.5 rounded-full text-xs font-semibold
                                    @if($tukang->status_pembayaran == 'Lunas') bg-green-100 text-green-800
                                    @else bg-red-100 text-red-800 @endif">
                                    {{ $tukang->status_pembayaran }}
                                </span>
                            </td>
                            <td class="p-3 flex items-center justify-center space-x-2 whitespace-nowrap">
                                @if($tukang->status_pembayaran !== 'Lunas')
                                    <button type="button" 
                                            onclick="openLunasModal('{{ route('tukang.lunas', $tukang->id_tukang) }}')" 
                                            class="bg-green-500 hover:bg-green-600 text-white font-bold py-1 px-3 rounded text-xs">
                                        Lunas
                                    </button>
                                @endif
                                
                                <a href="{{ route('tukang.edit', $tukang->id_tukang) }}" class="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-1 px-3 rounded text-xs">Edit</a>
                                
                                {{-- [PERUBAHAN 2] Ganti <form> Hapus dengan <button> Alpine.js --}}
                                <button type="button"
                                    @click="
                                        deleteModalAction = '{{ route('tukang.destroy', $tukang->id_tukang) }}';
                                        deleteModalTitle = 'Hapus Data Pembayaran?';
                                        deleteModalMessage = 'Anda yakin ingin menghapus data untuk <strong>{{ e($tukang->nama_mandor) }}</strong>? <br>Nominal: <strong>Rp. {{ number_format($tukang->total_pembayaran, 0, ',', '.') }}</strong><br><br><span class=\'font-bold text-red-600\'>Tindakan ini permanen dan akan menghapus file lampiran.</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="9" class="text-center p-6 text-gray-500">Tidak ada data pembayaran yang dapat ditampilkan.</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            <div class="mt-6">
                {{ $tukangs->links() }}
            </div>
        </div>

    </div> {{-- Ini adalah penutup dari <div class="space-y-8"> --}}


    {{-- ========================================================= --}}
    {{-- [PERUBAHAN 3] SEMUA MODAL DITEMPATKAN DI SINI --}}
    {{-- (Di luar 'space-y-8' tapi di dalam 'x-data') --}}
    {{-- ========================================================= --}}

    {{-- MODAL 1: Bukti (Sudah Ada) --}}
    <div id="proofModal" class="fixed inset-0 bg-black bg-opacity-70 flex justify-center items-center z-[9998] hidden p-4">
        <div class="bg-white p-4 rounded-lg max-w-3xl w-full max-h-[90vh] overflow-auto relative">
            <button onclick="closeProofModal()" class="absolute top-2 right-3 text-gray-500 hover:text-gray-800 text-3xl font-bold">&times;</button>
            <h3 class="text-xl font-bold mb-4">Bukti Lampiran</h3>
            <div id="modalContent" class="mt-4">
                {{-- Konten (Gambar atau PDF) akan dimasukkan di sini oleh JavaScript --}}
            </div>
        </div>
    </div>

    {{-- MODAL 2: Lunas (Sudah Ada) --}}
    <div id="lunasModal" class="fixed inset-0 bg-black bg-opacity-70 flex justify-center items-center z-[9998] hidden p-4">
        <div class="bg-white p-6 rounded-lg max-w-lg w-full max-h-[90vh] overflow-auto relative space-y-4">
            <button onclick="closeLunasModal()" class="absolute top-2 right-3 text-gray-500 hover:text-gray-800 text-3xl font-bold">&times;</button>
            <h3 class="text-xl font-bold text-gray-800">Tandai Lunas & Upload Bukti</h3>
            <p class="text-sm text-gray-600">Upload bukti pembayaran dan absensi (opsional) untuk menandai pembayaran ini sebagai lunas.</p>
            
            <form id="lunasForm" action="" method="POST" enctype="multipart/form-data" class="space-y-4">
                @csrf
                {{-- Input File Kustom untuk Bukti Absensi --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Upload Bukti Absensi (Opsional)</label>
                    <label for="bukti_absensi_lunas" class="relative cursor-pointer bg-white border border-gray-300 rounded-lg shadow-sm px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 flex items-center">
                        <svg class="w-5 h-5 mr-2 text-gray-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                        </svg>
                        <span id="file-name-absensi-lunas" class="truncate">Pilih file... (Max 2MB)</span>
                    </label>
                    <input type="file" id="bukti_absensi_lunas" name="bukti_absensi" class="hidden" onchange="updateFileName('bukti_absensi_lunas', 'file-name-absensi-lunas')">
                </div>
                
                {{-- Input File Kustom untuk Bukti Pembayaran --}}
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Upload Bukti Pembayaran (Opsional)</label>
                    <label for="bukti_pembayaran_lunas" class="relative cursor-pointer bg-white border border-gray-300 rounded-lg shadow-sm px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 flex items-center">
                        <svg class="w-5 h-5 mr-2 text-gray-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
                          <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" />
                        </svg>
                        <span id="file-name-pembayaran-lunas" class="truncate">Pilih file... (Max 2MB)</span>
                    </label>
                    <input type="file" id="bukti_pembayaran_lunas" name="bukti_pembayaran" class="hidden" onchange="updateFileName('bukti_pembayaran_lunas', 'file-name-pembayaran-lunas')">
                </div>

                {{-- Tombol Aksi Modal --}}
                <div class="mt-6 flex justify-end space-x-4 border-t border-gray-200 pt-4">
                    <button type="button" onclick="closeLunasModal()" class="px-4 py-2 bg-gray-200 text-gray-800 font-bold rounded-lg hover:bg-gray-300 transition duration-150">
                        Batal
                    </button>
                    <button type="submit" class="px-4 py-2 bg-green-600 text-white font-bold rounded-lg hover:bg-green-700 transition duration-150">
                        Konfirmasi Lunas
                    </button>
                </div>
            </form>
        </div>
    </div>

    {{-- =================================== --}}
    {{-- [PERUBAHAN 4] MODAL HAPUS (BARU) --}}
    {{-- =================================== --}}
    <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]" {{-- z-index tertinggi --}}
         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">
                    <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'"></h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-600" x-html="deleteModalMessage"></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <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>


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

@push('scripts')
{{-- Ini adalah script Anda yang sudah ada untuk modal 'proof' dan 'lunas' --}}
<script>
    const proofModal = document.getElementById('proofModal');
    const modalContent = document.getElementById('modalContent');

    function openProofModal(url, type) {
        modalContent.innerHTML = ''; // Bersihkan konten
        if (type === 'image') {
            const img = document.createElement('img');
            img.src = url;
            img.className = 'w-full h-auto rounded';
            modalContent.appendChild(img);
        } else if (type === 'pdf') {
            const iframe = document.createElement('iframe');
            iframe.src = url;
            iframe.className = 'w-full h-[70vh] border-0';
            modalContent.appendChild(iframe);
        }
        proofModal.classList.remove('hidden');
    }

    function closeProofModal() {
        proofModal.classList.add('hidden');
        modalContent.innerHTML = '';
    }

    proofModal.addEventListener('click', function(event) {
        if (event.target === proofModal) {
            closeProofModal();
        }
    });

    const lunasModal = document.getElementById('lunasModal');
    const lunasForm = document.getElementById('lunasForm');
    const lunasFileAbsensi = document.getElementById('file-name-absensi-lunas');
    const lunasFilePembayaran = document.getElementById('file-name-pembayaran-lunas');

    function openLunasModal(actionUrl) {
        // Set action form dinamis
        lunasForm.action = actionUrl;
        // Reset tampilan nama file
        lunasFileAbsensi.textContent = 'Pilih file... (Max 2MB)';
        lunasFilePembayaran.textContent = 'Pilih file... (Max 2MB)';
        // Reset input file (penting jika modal dibuka-tutup)
        document.getElementById('bukti_absensi_lunas').value = null;
        document.getElementById('bukti_pembayaran_lunas').value = null;
        // Tampilkan modal
        lunasModal.classList.remove('hidden');
    }

    function closeLunasModal() {
        lunasModal.classList.add('hidden');
        lunasForm.action = ''; // Kosongkan action
    }

    lunasModal.addEventListener('click', function(event) {
        if (event.target === lunasModal) {
            closeLunasModal();
        }
    });

    function updateFileName(inputId, spanId) {
        const input = document.getElementById(inputId);
        const span = document.getElementById(spanId);
        if (input.files && input.files.length > 0) {
            span.textContent = input.files[0].name;
        } else {
            span.textContent = 'Pilih file... (Max 2MB)';
        }
    }
</script>
@endpush