{{-- resources/views/admin/mesin/import/preview.blade.php --}}
@extends('layouts.app')
@section('title', 'Preview Import Absensi')
@section('content')
@php
use Carbon\Carbon;

$statusStyle = [
    'Hadir'     => ['bg'=>'#DCFCE7','c'=>'#166534','ic'=>'✅'],
    'Terlambat' => ['bg'=>'#FEF9C3','c'=>'#92400E','ic'=>'⏰'],
    'Alpa'      => ['bg'=>'#FEE2E2','c'=>'#991B1B','ic'=>'❌'],
    'Pulang'    => ['bg'=>'#FFF7ED','c'=>'#9A3412','ic'=>'🏠'],
    'Izin'      => ['bg'=>'#F3E8FF','c'=>'#6B21A8','ic'=>'📋'],
    'Sakit'     => ['bg'=>'#E0F2FE','c'=>'#0C4A6E','ic'=>'🏥'],
];

// ── 1. Kelompokkan data per tanggal → per santri ─────────────────────────────
$byTanggal = [];
foreach ($hasilEnriched as $h) {
    $tgl = $h['tanggal'];
    $byTanggal[$tgl][] = $h;
}
ksort($byTanggal);

// ── 2. Buat kolom kegiatan UNIK per tanggal, diurutkan waktu_mulai ───────────
$kegiatanByTanggal = [];
foreach ($byTanggal as $tgl => $santriList) {
    $cols = collect($santriList)
        ->flatMap(fn($h) => $h['rows'])
        ->unique('kegiatan_id')
        ->sortBy('waktu_mulai')
        ->values()
        ->map(fn($r) => [
            'kegiatan_id' => $r['kegiatan_id'],
            'nama'        => $r['nama_kegiatan'],
            'waktu_mulai' => $r['waktu_mulai'],
        ]);
    $kegiatanByTanggal[$tgl] = $cols;
}

// ── 3. Statistik global ──────────────────────────────────────────────────────
$allRows      = collect($hasilEnriched)->flatMap(fn($h) => $h['rows']);
$totalKonflik = $allRows->where('is_conflict', true)->count();
$hadirTotal   = $allRows->where('status_final','Hadir')->count();
$terlambatTotal = $allRows->where('status_final','Terlambat')->count();
$alpaTotal    = $allRows->where('status_final','Alpa')->count();
$notMapped    = collect($hasilEnriched)->where('match_status','NOT_MAPPED')->count();
$totalSantri  = collect($hasilEnriched)->unique(fn($h) => $h['id_santri'] ?? $h['id_mesin'])->count();
@endphp

<style>
/* ── Top sticky bar ───────────────────────────────── */
.top-bar {
    position: sticky; top: 0; z-index: 50;
    background: #0F172A; color: #F1F5F9;
    padding: 8px 16px; display: flex; align-items: center;
    gap: 10px; flex-wrap: wrap; box-shadow: 0 2px 8px rgba(0,0,0,.3);
    font-size: 13px;
}
.chip {
    border-radius: 8px; padding: 4px 10px;
    text-align: center; min-width: 56px;
    font-size: 11px; line-height: 1.3;
}
.chip .n { font-size: 17px; font-weight: 700; display: block }
.btn-act {
    border: none; border-radius: 6px; padding: 6px 12px;
    cursor: pointer; font-weight: 600; font-size: 12px;
    white-space: nowrap;
}
.btn-save {
    border: none; border-radius: 8px; padding: 8px 20px;
    cursor: pointer; font-weight: 700; font-size: 13px;
    color: #fff; white-space: nowrap; transition: background .2s;
}

/* ── Per-day block ────────────────────────────────── */
.day-block {
    margin: 14px 14px 0;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,.08);
    border: 1px solid #E5E7EB;
}
.day-block:last-child { margin-bottom: 14px; }

.day-header {
    background: #1E293B;
    color: #F1F5F9;
    padding: 10px 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}
.day-header .hari-nama {
    font-size: 10px; color: #64748B;
    text-transform: uppercase; letter-spacing: 1px;
}
.day-header .tgl-label {
    font-weight: 700; font-size: 16px; margin-top: 1px;
}
.day-badge {
    border-radius: 6px; padding: 3px 10px;
    font-size: 11px; font-weight: 700;
}

/* ── Tabel per hari ───────────────────────────────── */
.tbl-day { border-collapse: collapse; font-size: 12px; width: 100% }
.tbl-day th, .tbl-day td {
    border: 1px solid #E5E7EB;
    padding: 0;
}
.th-no   { width: 36px; text-align: center; padding: 8px 4px !important; }
.th-nama { min-width: 150px; padding: 8px 10px !important; text-align: left; }
.th-kelas { min-width: 80px; padding: 8px 10px !important; text-align: left; }
.th-keg   { min-width: 90px; vertical-align: bottom; }
.th-keg-inner {
    padding: 6px 8px 6px;
    display: flex; flex-direction: column; align-items: center;
    gap: 2px;
}

/* ── Status pill ──────────────────────────────────── */
.pill {
    display: inline-block; border-radius: 8px;
    padding: 2px 7px; font-size: 10px; font-weight: 700;
}

/* ── Konflik cell ─────────────────────────────────── */
.conf-wrap { display: flex; flex-direction: column; }
.conf-opt {
    padding: 4px 8px; cursor: pointer;
    font-size: 11px; display: flex; align-items: center; gap: 4px;
    border-bottom: 1px solid #F1F5F9; transition: background .12s;
}
.conf-opt:last-child { border-bottom: none }
.conf-opt:hover { background: #F8FAFC }
.sel-m { background: #DCFCE7 !important }
.sel-e { background: #DBEAFE !important }
</style>

<form action="{{ route('admin.mesin.import.store') }}" method="POST" id="frm">
@csrf
<input type="hidden" name="conflict_strategy" value="manual" id="stratInput">

@if(session('error'))
<div style="background:#FEE2E2;border:1px solid #FCA5A5;border-left:4px solid #DC2626;
            padding:12px 16px;font-size:13px;color:#991B1B">
    <strong>❌ Error:</strong> {{ session('error') }}
</div>
@endif

{{-- ══ TOP BAR ═════════════════════════════════════════════════════════════ --}}
<div class="top-bar">
    <div style="flex:1;min-width:200px">
        <div style="color:#64748B;font-size:10px;text-transform:uppercase;letter-spacing:1px">
            Preview Import
        </div>
        <div style="font-weight:700;font-size:14px;margin-top:1px">
            {{ $totalSantri }} santri ·
            {{ count($byTanggal) }} hari
            @if($totalKonflik > 0)
                · <span style="color:#FCA5A5" id="lbl">
                    ⚡ <span id="cnt">{{ $totalKonflik }}</span> konflik perlu diselesaikan
                  </span>
            @else
                · <span style="color:#86EFAC">✅ Siap disimpan</span>
            @endif
        </div>
    </div>

    {{-- Toleransi — tampilkan nilai DARI form, bukan hardcode --}}
    <div style="background:#1E3A5F;border:1px solid #2D5A8E;border-radius:8px;
                padding:5px 12px;font-size:11px;color:#93C5FD;white-space:nowrap">
        ⏱ Toleransi: <strong style="color:#BFDBFE">{{ $tolSebelum }}m</strong> sebelum
        / <strong style="color:#BFDBFE">{{ $tolSesudah }}m</strong> sesudah
    </div>

    {{-- Stat chips --}}
    <div class="chip" style="background:#DCFCE7;color:#166534">
        <span class="n">{{ $hadirTotal }}</span>Hadir
    </div>
    <div class="chip" style="background:#FEF9C3;color:#92400E">
        <span class="n">{{ $terlambatTotal }}</span>Telat
    </div>
    <div class="chip" style="background:#FEE2E2;color:#991B1B">
        <span class="n">{{ $alpaTotal }}</span>Alpa
    </div>
    @if($totalKonflik > 0)
    <div class="chip" style="background:#FEE2E2;color:#DC2626">
        <span class="n" id="chip">{{ $totalKonflik }}</span>Konflik
    </div>
    @endif
    @if($notMapped > 0)
    <div class="chip" style="background:#FFF3E8;color:#C05621">
        <span class="n">{{ $notMapped }}</span>Blm Map
    </div>
    @endif

    {{-- Konflik: bulk actions --}}
    @if($totalKonflik > 0)
    <div style="display:flex;flex-direction:column;gap:3px;font-size:11px;color:#94A3B8">
        Konflik:
    </div>
    <button type="button" class="btn-act" style="background:#DCFCE7;color:#166534"
            onclick="resolveAll('m');document.getElementById('stratInput').value='mesin'">
        👆 Semua Mesin
    </button>
    <button type="button" class="btn-act" style="background:#DBEAFE;color:#1D4ED8"
            onclick="resolveAll('e');document.getElementById('stratInput').value='exist'">
        🔒 Semua Lama
    </button>
    @endif

    {{-- Simpan --}}
    <button type="button" class="btn-save" id="saveBtn"
            style="background:{{ $totalKonflik > 0 ? '#64748B' : 'linear-gradient(135deg,#166534,#22C55E)' }}"
            {{ $totalKonflik > 0 ? 'disabled' : '' }}
            onclick="submitForm()">
        @if($totalKonflik > 0) ⏳ Selesaikan konflik dulu
        @else 💾 Simpan ke Database @endif
    </button>

    <a href="{{ route('admin.mesin.import.index') }}"
       class="btn-act" style="background:#374151;color:#F1F5F9;text-decoration:none">
        ← Kembali
    </a>
</div>

{{-- Legenda --}}
<div style="display:flex;gap:8px;flex-wrap:wrap;padding:8px 14px;
            background:#F8FAFC;border-bottom:1px solid #E5E7EB;font-size:11px">
    <span style="color:#6B7280;font-weight:600">Status:</span>
    @foreach($statusStyle as $st => $s)
    <span class="pill" style="background:{{$s['bg']}};color:{{$s['c']}}">
        {{ $s['ic'] }} {{ $st }}
    </span>
    @endforeach
    <span style="color:#9CA3AF;margin-left:4px">| — = tidak ada data</span>
    <span style="border:2px solid #FCA5A5;border-radius:4px;padding:1px 6px;color:#991B1B">⚡ Konflik</span>
    <span style="color:#9CA3AF">= pilih salah satu</span>
    @if($notMapped > 0)
    <span style="margin-left:auto">
        ⚠️ {{ $notMapped }} belum dipetakan →
        <a href="{{ route('admin.mesin.mapping-santri.index') }}" target="_blank">Lengkapi Mapping</a>
    </span>
    @endif
</div>

{{-- ══ TABEL PER HARI ══════════════════════════════════════════════════════ --}}
@foreach($byTanggal as $tgl => $santriListRaw)
@php
    // Urutkan santri berdasarkan nama
    $santriListSorted = collect($santriListRaw)
        ->sortBy(fn($h) => $h['nama_web'] ?? $h['nama_mesin'])
        ->values()
        ->all();

    $tglCarbon    = Carbon::parse($tgl);
    $namaHari     = $tglCarbon->locale('id')->isoFormat('dddd');
    $tglFormatted = $tglCarbon->locale('id')->isoFormat('D MMMM Y');

    $kegiatanHariIni = $kegiatanByTanggal[$tgl];

    // Statistik untuk hari ini
    $rowsHari    = collect($santriListSorted)->flatMap(fn($h) => $h['rows']);
    $hadirHari   = $rowsHari->where('status_final','Hadir')->count();
    $telambatHari = $rowsHari->where('status_final','Terlambat')->count();
    $alpaHari    = $rowsHari->where('status_final','Alpa')->count();
    $konflikHari = $rowsHari->where('is_conflict',true)->count();
@endphp

<div class="day-block">

    {{-- Header Tanggal --}}
    <div class="day-header">
        <div>
            <div class="hari-nama">{{ $namaHari }}</div>
            <div class="tgl-label">{{ $tglFormatted }}</div>
        </div>
        <div style="margin-left:auto;display:flex;gap:6px;flex-wrap:wrap;align-items:center">
            <span class="day-badge" style="background:#DCFCE7;color:#166534">✅ {{ $hadirHari }} Hadir</span>
            @if($telambatHari > 0)
            <span class="day-badge" style="background:#FEF9C3;color:#92400E">⏰ {{ $telambatHari }} Terlambat</span>
            @endif
            <span class="day-badge" style="background:#FEE2E2;color:#991B1B">❌ {{ $alpaHari }} Alpa</span>
            @if($konflikHari > 0)
            <span class="day-badge" style="background:#FEE2E2;color:#DC2626">⚡ {{ $konflikHari }} Konflik</span>
            @endif
            <span class="day-badge" style="background:#334155;color:#94A3B8">
                👥 {{ count($santriListSorted) }} santri
            </span>
        </div>
    </div>

    {{-- Tabel hari ini --}}
    <div style="overflow-x:auto">
    <table class="tbl-day">
        <thead>
            <tr style="background:#F1F5F9">
                <th class="th-no"
                    style="border:1px solid #E2E8F0;color:#6B7280;font-size:10px;font-weight:700">
                    No
                </th>
                <th class="th-nama"
                    style="border:1px solid #E2E8F0;color:#374151;font-size:11px;font-weight:700;border-right:2px solid #CBD5E1">
                    Nama Santri
                </th>
                <th class="th-kelas"
                    style="border:1px solid #E2E8F0;color:#374151;font-size:11px;font-weight:700;border-right:2px solid #CBD5E1">
                    Kelas
                </th>
                @foreach($kegiatanHariIni as $kg)
                <th class="th-keg" style="border:1px solid #E2E8F0">
                    <div class="th-keg-inner">
                        <span style="color:#1E293B;font-size:11px;font-weight:600;
                                     white-space:normal;text-align:center;line-height:1.3">
                            {{ $kg['nama'] }}
                        </span>
                        <span style="color:#64748B;font-size:9px">
                            {{ $kg['waktu_mulai'] }}
                        </span>
                    </div>
                </th>
                @endforeach
            </tr>
        </thead>
        <tbody>
            @foreach($santriListSorted as $idx => $h)
            @php
                $rowBg = ($idx % 2 === 0) ? '#ffffff' : '#F9FAFB';
                if ($h['match_status'] === 'NOT_MAPPED') $rowBg = '#FFF5F5';
            @endphp
            <tr style="background:{{ $rowBg }}">

                {{-- No --}}
                <td style="text-align:center;padding:6px 4px;
                            color:#9CA3AF;font-size:11px;border:1px solid #E5E7EB">
                    {{ $idx + 1 }}
                </td>

                {{-- Nama --}}
                <td style="padding:6px 10px;border:1px solid #E5E7EB;border-right:2px solid #CBD5E1">
                    @if($h['match_status'] === 'NOT_MAPPED')
                        <div style="font-weight:700;color:#DC2626;font-size:11px">⚠ BELUM MAP</div>
                        <div style="color:#9CA3AF;font-size:10px">{{ $h['nama_mesin'] }}</div>
                    @else
                        <div style="font-weight:600;color:#1F2937;font-size:12px">
                            {{ $h['nama_web'] ?? $h['nama_mesin'] }}
                        </div>
                        @if($h['is_pulang'] ?? false)
                        <div style="font-size:9px;color:#9A3412;background:#FFF7ED;
                                    border-radius:4px;padding:1px 5px;display:inline-block;margin-top:1px">
                            🏠 Sedang Pulang
                        </div>
                        @endif
                    @endif
                </td>

                {{-- Kelas --}}
                <td style="padding:6px 10px;border:1px solid #E5E7EB;border-right:2px solid #CBD5E1;
                            color:#6B7280;font-size:11px">
                    {{ $h['kelas'] ?? '-' }}
                </td>

                {{-- Kolom per kegiatan --}}
                @foreach($kegiatanHariIni as $kg)
                @php
                    $row    = collect($h['rows'])->firstWhere('kegiatan_id', $kg['kegiatan_id']);
                    $sf     = $row['status_final'] ?? null;
                    $st     = $sf ? ($statusStyle[$sf] ?? null) : null;
                    $isConf = $row['is_conflict'] ?? false;
                    $cKey   = "{$kg['kegiatan_id']}_{$h['id_santri']}_{$tgl}";
                @endphp

                <td style="padding:0;text-align:center;vertical-align:middle;
                            border:1px solid {{ $isConf ? '#FCA5A5' : '#E5E7EB' }};
                            {{ $isConf ? 'background:#FFF5F5;border-width:2px;' : '' }}">

                    @if(!$row || $sf === null)
                        {{-- Tidak ada data --}}
                        <span style="color:#D1D5DB;font-size:14px">—</span>

                    @elseif($isConf)
                        {{-- ── KONFLIK: 2 pilihan ────────── --}}
                        @php
                            $ex   = $row['existing'];
                            $exSt = $statusStyle[$ex['status']] ?? ['bg'=>'#F9FAFB','c'=>'#6B7280','ic'=>'?'];
                        @endphp
                        <div class="conf-wrap" data-key="{{ $cKey }}">
                            {{-- Pilihan: pakai data mesin --}}
                            <div class="conf-opt" data-ch="m"
                                 onclick="pick('{{ $cKey }}','m',this)">
                                <input type="radio" name="conflict_choices[{{ $cKey }}]"
                                       value="mesin" id="cm_{{ $cKey }}" style="display:none">
                                <span>👆</span>
                                <div>
                                    <span class="pill"
                                          style="background:{{$st['bg']}};color:{{$st['c']}}">
                                        {{$st['ic']}} {{$sf}}
                                    </span>
                                    <div style="font-size:9px;color:#6B7280;margin-top:1px">
                                        Mesin · {{ $row['jam_scan'] ?? '-' }}
                                    </div>
                                </div>
                            </div>
                            {{-- Pilihan: pertahankan data lama --}}
                            <div class="conf-opt" data-ch="e"
                                 onclick="pick('{{ $cKey }}','e',this)">
                                <input type="radio" name="conflict_choices[{{ $cKey }}]"
                                       value="exist" id="ce_{{ $cKey }}" style="display:none">
                                <span>🔒</span>
                                <div>
                                    <span class="pill"
                                          style="background:{{$exSt['bg']}};color:{{$exSt['c']}}">
                                        {{$exSt['ic']}} {{$ex['status']}}
                                    </span>
                                    <div style="font-size:9px;color:#6B7280;margin-top:1px">
                                        {{ $ex['metode'] ?? 'Manual' }}
                                        @if($ex['waktu']) · {{ substr($ex['waktu'],0,5) }} @endif
                                    </div>
                                </div>
                            </div>
                            <div style="background:#FEE2E2;padding:1px 4px;font-size:9px;
                                        color:#DC2626;font-weight:700;text-align:center">
                                ⚡ pilih
                            </div>
                        </div>

                    @else
                        {{-- ── Normal ─────────────────────── --}}
                        <div style="padding:6px 4px">
                            @if($st)
                            <span class="pill" style="background:{{$st['bg']}};color:{{$st['c']}}">
                                {{$st['ic']}} {{$sf}}
                            </span>
                            @endif
                            @if(!empty($row['jam_scan']))
                            <div style="font-size:9px;color:#9CA3AF;margin-top:2px">
                                {{ $row['jam_scan'] }}
                                @if(($row['selisih_menit'] ?? 0) > 0)
                                <span style="color:#F59E0B">+{{ $row['selisih_menit'] }}m</span>
                                @endif
                            </div>
                            @endif
                        </div>
                    @endif
                </td>
                @endforeach

            </tr>
            @endforeach
        </tbody>
    </table>
    </div>
    {{-- Footer per hari: ringkasan kegiatan --}}
    <div style="background:#F8FAFC;padding:6px 14px;font-size:10px;color:#6B7280;
                border-top:1px solid #E5E7EB;display:flex;gap:10px;flex-wrap:wrap">
        @foreach($kegiatanHariIni as $kg)
        <span>📌 {{ $kg['nama'] }} ({{ $kg['waktu_mulai'] }})</span>
        @endforeach
    </div>
</div>
{{-- end day-block --}}

@endforeach
{{-- end foreach $byTanggal --}}

{{-- ══ FOOTER GLOBAL ═══════════════════════════════════════════════════════ --}}
<div style="padding:10px 16px;background:#1E293B;
            font-size:11px;color:#94A3B8;display:flex;gap:14px;flex-wrap:wrap;
            margin-top:0;position:sticky;bottom:0;z-index:40;
            box-shadow:0 -2px 8px rgba(0,0,0,.2)">
    <span>📊 {{ $totalSantri }} santri · {{ count($byTanggal) }} hari</span>
    <span style="color:#86EFAC">✅ {{ $hadirTotal }} Hadir</span>
    <span style="color:#FDE68A">⏰ {{ $terlambatTotal }} Terlambat</span>
    <span style="color:#FCA5A5">❌ {{ $alpaTotal }} Alpa</span>
    @if($totalKonflik > 0)
    <span style="color:#F87171">⚡ <span id="footer-konflik">{{ $totalKonflik }}</span> Konflik</span>
    @endif
    {{-- Tampilkan toleransi dari form, bukan hardcode --}}
    <span style="margin-left:auto;color:#93C5FD">
        ⏱ Toleransi: {{ $tolSebelum }}m sebelum / {{ $tolSesudah }}m sesudah
    </span>
</div>

</form>

<script>
const totalK = {{ $totalKonflik }};
const done   = new Set();

function pick(key, ch, el) {
    const wrap = el.closest('.conf-wrap');
    wrap.querySelectorAll('.conf-opt').forEach(o => {
        o.classList.remove('sel-m','sel-e');
    });
    el.classList.add(ch === 'm' ? 'sel-m' : 'sel-e');
    const radio = document.getElementById((ch === 'm' ? 'cm_' : 'ce_') + key);
    if (radio) radio.checked = true;
    done.add(key);
    updateUI();
}

function resolveAll(ch) {
    document.querySelectorAll('.conf-wrap').forEach(wrap => {
        const key = wrap.dataset.key;
        const opt = wrap.querySelector('[data-ch="' + ch + '"]');
        if (opt) pick(key, ch, opt);
    });
}

function submitForm() {
    const btn = document.getElementById('saveBtn');
    btn.disabled = true;
    btn.style.background = '#64748B';
    btn.textContent = '⏳ Menyimpan...';
    document.getElementById('frm').submit();
}

function updateUI() {
    const rem  = totalK - done.size;
    const btn  = document.getElementById('saveBtn');
    const lbl  = document.getElementById('lbl');
    const chip = document.getElementById('chip');
    const fk   = document.getElementById('footer-konflik');

    if (rem <= 0) {
        btn.disabled = false;
        btn.style.background = 'linear-gradient(135deg,#166534,#22C55E)';
        btn.textContent = '💾 Simpan ke Database';
        if (lbl)  lbl.innerHTML = '<span style="color:#86EFAC">✅ Semua konflik selesai</span>';
        if (chip) chip.textContent = '0';
        if (fk)   fk.textContent = '0';
    } else {
        btn.disabled = true;
        btn.style.background = '#64748B';
        btn.textContent = '⏳ Selesaikan ' + rem + ' konflik';
        if (lbl)  lbl.innerHTML = '<span style="color:#FCA5A5">⚡ <span id="cnt">' + rem + '</span> konflik</span>';
        if (chip) chip.textContent = rem;
        if (fk)   fk.textContent = rem;
    }
}
</script>

@endsection