@extends('layouts.app')

@php
// Paksa role jadi admin biar dropdown nggak hilang-hilang
session(['user_role' => 'admin']);
@endphp

@section('konten')

<style>
    table th {
        background-color: #2a28a7 !important;
        /* Warna Hijau SJU */
        color: white;
        text-transform: uppercase;
        font-size: 13px;
    }

    table tr:hover {
        background-color: #f9f9f9;
        /* Efek highlight kalau kursor lewat */
    }
</style>

<style>
    /* Paksa nav pagination biar lurus ke samping dan nggak ada titiknya */
    .pagination-wrapper ul {
        display: flex !important;
        list-style: none !important;
        padding-left: 0 !important;
        justify-content: flex-end !important;
        /* Biar nempel ke kanan */
    }

    .pagination-wrapper li {
        margin: 0 2px !important;
    }

    .pagination-wrapper li a,
    .pagination-wrapper li span {
        padding: 8px 12px !important;
        border: 1px solid #dee2e6 !important;
        color: #007bff !important;
        text-decoration: none !important;
        background-color: #fff !important;
    }

    .pagination-wrapper li.active span {
        background-color: #007bff !important;
        color: white !important;
        border-color: #007bff !important;
    }

    /* Sembunyikan tulisan "Showing X to Y of Z results" yang bikin penuh layar */
    .pagination-wrapper .flex.items-center.justify-between {
        display: none !important;
    }
</style>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <h3>Daftar Laporan Kerusakan SJU</h3>
    @if(request()->get('role') != 'admin')
    <a href="{{ url('service/tambah') }}" style="background: #2a28a7; color: white; padding: 10px; text-decoration: none; border-radius: 5px;">+ Buat Laporan</a>
    @endif
</div>

<div class="row mb-1" style="justify-content: flex-end !important; display: flex !important;">
    <div class="col-md-4" style="display: flex !important; justify-content: flex-end !important;">
        <form action="{{ url()->current() }}" method="GET" style="margin: 0 !important;">
            @if(request('role'))
            <input type="hidden" name="role" value="{{ request('role') }}">
            @endif

            <div style="display: flex !important; width: 100% !important; align-items: stretch !important;">
                <!-- Input Cari: Kita paksa ambil sisa ruang (flex-grow) -->
                <input type="text" name="cari" class="form-control form-control-sm"
                    placeholder="Cari data..."
                    value="{{ request('cari') }}"
                    style="flex-grow: 1 !important; border-top-right-radius: 0 !important; border-bottom-right-radius: 0 !important; width: auto !important;">

                <!-- Tombol Cari -->
                <button class="btn btn-sm btn-primary" type="submit"
                    style="border-radius: 0 !important; white-space: nowrap !important; padding: 0 15px !important;">
                    Cari
                </button>

                <!-- Tombol Reset -->
                <a href="{{ url('service') }}{{ request('role') ? '?role='.request('role') : '' }}"
                    class="btn btn-sm btn-danger d-flex align-items-center justify-content-center text-white"
                    style="border-top-left-radius: 0 !important; border-bottom-left-radius: 0 !important; text-decoration: none; white-space: nowrap !important; padding: 0 15px !important;">
                    Reset
                </a>
            </div>
        </form>
    </div>
</div>

@php
$pendingCount = $laporan->where('status', 'Pending')->count();
@endphp

@if($pendingCount > 0)
<div class="alert alert-info d-inline-block py-1 px-3 mb-2" style="font-size: 0.85rem;">
    <i class="fas fa-exclamation-circle me-1"></i>
    Ada <strong>{{ $pendingCount }}</strong> laporan baru yang perlu diproses!
</div>
@endif

<style>
    th:last-child,
    td:last-child {
        white-space: nowrap;
        /* Biar tombolnya nggak turun ke bawah, tetep satu baris */
        width: 1%;
        /* Biar kolomnya pas selebar tombol saja */
    }
</style>

@if(session('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
    <strong>Mantap!</strong> {{ session('success') }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
@endif

<table border="1" cellpadding="10" style="width: 100%; border-collapse: collapse; margin-top: 20px;">
    <thead>
        <tr style="background-color: #f2f2f2; text-align: center;">
            <th>Pelapor</th> {{-- Kolom 1 --}}
            @if(request('role') == 'admin')
            <th>Unit</th>
            @endif
            <th>Lokasi</th> {{-- Kolom 2 --}}
            <th>Perangkat</th> {{-- Kolom 3 --}}
            <th>No. Inventaris</th> {{-- Kolom BARU --}}
            <th>Keluhan</th> {{-- Kolom 5 --}}
            @if(request('role') == 'admin')
            <th>Urgensi</th> {{-- Kolom 6 --}}
            {{--@if(request('role') == 'admin')--}}
            <th style="text-align: center;">FOTO</th>
            @endif {{-- Kolom 7 --}}
            <th>Status</th> {{-- Kolom 8 --}}

            @if(request()->query('role') == 'admin')
            <th>Aksi</th> {{-- Kolom 9 --}}
            @endif
        </tr>
    </thead>
    <tbody class="text-secondary">
        @foreach($laporan as $item)
        <tr class="{{ $item->status == 'Pending' ? 'table-warning' : '' }}">
            {{--<td>{{ $loop->iteration }}</td>--}}
            <td>{{ $item->pelapor }}</td>

            @if(request('role') == 'admin')
            <td class="
            @if(str_contains(strtolower($item->lokasi), 'retail'))
                bg-warning text-dark
            @elseif(str_contains(strtolower($item->lokasi), 'ruko'))
                bg-primary text-white
            @else
                bg-success text-white
            @endif
">
                @if(str_contains(strtolower($item->lokasi), 'retail'))
                Retail / Toko
                @elseif(str_contains(strtolower($item->lokasi), 'ruko'))
                Kantor (Ruko)
                @else
                Kantor (SJU)
                @endif
            </td>
            @endif

            <td>{{ $item->divisi}}</td>
            <td>{{ $item->perangkat }}</td>
            <td>{{ $item->no_inventaris ?? '-' }}</td>
            <td>{{ $item->keluhan }}</td>
            @php
            $urgensi = strtolower($item->urgensi);
            $bgcolor = '#28a745'; // Default Abu-abu
            $textColor = 'white';

            if (str_contains($urgensi, 'darurat')) {
            $bgcolor = '#ffee00'; // Hitam (Atau Merah Marun #8b0000) biar beda banget
            $textColor = 'black'; // Tulisan kuning biar kontras
            } elseif (str_contains($urgensi, 'penting') || str_contains($urgensi, 'high')) {
            $bgcolor = '#dc3545'; // Merah standar
            } elseif (str_contains($urgensi, 'menengah') || str_contains($urgensi, 'medium')) {
            $bgcolor = '#ffc107'; // Kuning Bootstrap
            $textColor = 'black';
            } elseif (str_contains($urgensi, 'rendah') || str_contains($urgensi, 'low')) {
            $bgcolor = '#28a745'; // Hijau
            }
            @endphp
            @if(request('role') == 'admin')
            <td style="background-color: {{ $bgcolor }}; color: {{ $textColor }};">
                {{ $item->urgensi }}
            </td>
            @endif

            @if(request('role') == 'admin')
            <td style="text-align: center;">
                @if($item->foto)
                <button type="button" class="btn btn-sm btn-info text-white" data-bs-toggle="modal" data-bs-target="#fotoModal{{ $item->id }}">
                    Lihat Foto
                </button>
                @else
                -
                @endif
            </td>
            @endif
            <td>{{ $item->status }}</td>

            @if(request()->query('role') == 'admin')
            <td style="vertical-align: middle !important; white-space: nowrap !important; text-align: center;">
                <div style="display: flex !important; flex-direction: row !important; align-items: center !important; justify-content: center !important; gap: 5px !important;">

                    {{--<form action="{{ url('/service/'.$l->id.'/update-status') }}" method="POST" style="margin: 0 !important; padding: 0 !important;">
                    @csrf @method('PATCH')
                    <select name="status" onchange="this.form.submit()"
                        style="display: block !important; width: 110px !important; padding: 4px !important; font-size: 11px !important; border-radius: 4px !important; border: 1px solid #ccc !important;">
                        <option value="Pending" {{ $l->status == 'Pending' ? 'selected' : '' }}>Pending</option>
                        <option value="On Proses" {{ $l->status == 'On Proses' ? 'selected' : '' }}>On Proses</option>
                        <option value="Selesai" {{ $l->status == 'Selesai' ? 'selected' : '' }}>Selesai</option>
                    </select>
                    </form>--}}

                    <form action="{{ url('/service/'.$item->id) }}" method="POST" style="margin: 0 !important; padding: 0 !important;">
                        @csrf @method('DELETE')
                        <button type="submit" onclick="return confirm('Yakin Hapus?')"
                            style="background-color: #dc3545 !important; color: white !important; border: none !important; padding: 5px 10px !important; font-size: 11px !important; border-radius: 4px !important; cursor: pointer !important;">
                            Hapus
                        </button>
                    </form>

                    @if(session('user_role') == 'admin')
                    <a href="{{ url('/service/'.$item->id.'/analisis') }}"
                        style="background-color: #0d6efd !important; color: white !important; text-decoration: none !important; padding: 5px 10px !important; font-size: 11px !important; border-radius: 4px !important; display: inline-block !important;">
                        Analisis
                    </a>

                    <!-- KODINGAN BARU (LANGSUNG COPAS DI TEMPAT TOMBOL LAMA) -->
                    <!-- TOMBOL CETAK BARU: UKURAN SERAGAM SAMA RATA -->
                    <!-- KODE MURNI POLOSAN - PASTIKAN KODE SEBELUMNYA DIHAPUS TOTAL YA MAS -->
                    <!-- UKURAN PENYESUAIAN: NAIK DIKIT BIAR PAS -->
                    <a href="javascript:void(0)" onclick="cetakTanpaNewTab('{{ url('/service/' . $item->id . '/print') }}')" class="btn btn-success" style="background-color: #198754 !important; color: white !important; text-decoration: none !important; padding: 4px 10px !important; font-size: 11px !important; border-radius: 4px !important; display: inline-block !important;">
                        <i class="fas fa-print"></i> Cetak
                    </a>

                    <script>
                        function cetakTanpaNewTab(urlPrint) {
                            // 1. Cari dulu apakah ada iframe gaib sisa sebelumnya, kalau ada hapus dulu biar gak numpuk
                            let iframeLama = document.getElementById('iframeCetakGaib');
                            if (iframeLama) {
                                iframeLama.remove();
                            }
                        
                            // 2. Buat elemen iframe gaib baru
                            let iframeGaib = document.createElement('iframe');
                            iframeGaib.id = 'iframeCetakGaib';
                        
                            // 3. Sembunyikan dari layar
                            iframeGaib.style.position = 'fixed';
                            iframeGaib.style.width = '0';
                            iframeGaib.style.height = '0';
                            iframeGaib.style.border = 'none';
                        
                            // 4. Masukkan URL halaman cetak
                            iframeGaib.src = urlPrint;
                        
                            // 5. [PERBAIKAN] Tunggu sampai konten cetak selesai di-load, lalu paksa print!
                            iframeGaib.onload = function() {
                                iframeGaib.contentWindow.focus();
                                iframeGaib.contentWindow.print();
                            };
                        
                            // 6. Masukkan ke dalam body halaman
                            document.body.appendChild(iframeGaib);
                        }
                    </script>
                    @endif
                </div>
            </td>
            @endif
        </tr>
        @endforeach
    </tbody>
</table>

@if(request()->get('role') == 'admin')
<div class="alert alert-success mt-2 d-flex justify-content-between align-items-center" role="alert" style="padding: 10px 20px;">
    <div>
        <i class="fa fa-users"></i>
        <strong>{{ count($userOnline) }} User Sedang Online</strong>
    </div>

    <div>
        <a href="{{ url('/service/export') }}" class="btn btn-success btn-sm">
            <i class="fa fa-file-excel-o"></i> Download Rekap Excel
        </a>
    </div>
</div>
@endif
</div>

<div class="pagination-wrapper mt-3">
    {{ $laporan->links('pagination::bootstrap-4') }}
</div>

@if(request()->get('role') == 'admin')
<div class="card mt-3">
    <div class="card-header bg-primary text-white" style="padding: 8px 12px; font-size: 14px;">
        <i class="fas fa-users"></i> Detil User Online (5 Menit Terakhir)
    </div>
    <ul class="list-group list-group-flush" style="font-size: 12px;">
        @foreach($userOnline as $user)
        @php
        // Trik sederhana menerjemahkan OS
        $agent = $user->user_agent;
        $os = "Unknown OS";
        if (preg_match('/win/i', $agent)) { $os = 'Windows'; }
        elseif (preg_match('/android/i', $agent)) { $os = 'Android'; }
        elseif (preg_match('/iphone|ipad/i', $agent)) { $os = 'iOS'; }
        elseif (preg_match('/mac/i', $agent)) { $os = 'MacOS'; }
        elseif (preg_match('/linux/i', $agent)) { $os = 'Linux'; }

        // Trik sederhana menerjemahkan Browser
        $browser = "Unknown Browser";
        if (preg_match('/chrome/i', $agent) && !preg_match('/edge/i', $agent)) { $browser = 'Chrome'; }
        elseif (preg_match('/firefox/i', $agent)) { $browser = 'Firefox'; }
        elseif (preg_match('/safari/i', $agent) && !preg_match('/chrome/i', $agent)) { $browser = 'Safari'; }
        elseif (preg_match('/edge/i', $agent)) { $browser = 'Edge'; }
        @endphp

        <li class="list-group-item d-flex justify-content-between align-items-center" style="padding: 8px 12px;">
            <div>
                <!-- Kalau belum login, tampilkan 'Tamu / Public User' -->
                <strong>{{ $user->user_name ?? 'Tamu (Public)' }}</strong>
                <small class="text-muted d-block">IP: {{ $user->ip_address }}</small>
            </div>
            <span class="badge bg-secondary text-white" style="font-size: 11px; padding: 4px 8px;">
                <i class="fas fa-laptop"></i> {{ $os }} - {{ $browser }}
            </span>
        </li>
        @endforeach
    </ul>
</div>
@endif

<style>
    /* Efek kedip-kedip biar kayak lampu indikator online */
    .blink {
        animation: blinker 1.5s linear infinite;
    }

    @keyframes blinker {
        50% {
            opacity: 0;
        }
    }
</style>



@if(request()->query('role') == 'admin')
<script>
    // Refresh otomatis cuma buat Admin tiap 30 detik
    setTimeout(function() {
        location.reload();
    }, 600000);
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

@foreach($laporan as $item)
<div class="modal fade" id="fotoModal{{ $item->id }}" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Foto Kendala - {{ $item->pelapor }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                @if($item->foto)
                <img src="{{ asset($item->foto) }}" class="img-fluid rounded">
                @else
                <p>Tidak ada foto</p>
                @endif
            </div>
        </div>
    </div>
</div>
@endforeach

@endif
@endsection
