@extends('layouts.admin')

@section('title', 'Import Peserta CSV')
@section('header', 'Import Peserta CSV')

@section('breadcrumb')
<li class="breadcrumb-item"><a href="{{ route('admin.programs.index') }}">Program</a></li>
<li class="breadcrumb-item"><a href="{{ route('admin.programs.show', $program) }}">{{ Str::limit($program->title, 25) }}</a></li>
<li class="breadcrumb-item"><a href="{{ route('admin.programs.participants.index', $program) }}">Peserta</a></li>
<li class="breadcrumb-item active">Import CSV</li>
@endsection

@section('content')
<div class="row g-4 justify-content-center">
    <div class="col-lg-7">

        {{-- Import Result --}}
        @if(session('import_result'))
        @php $r = session('import_result'); @endphp

        {{-- Invalid headers --}}
        @if(!empty($r['invalid_headers']))
        <div class="card border-0 shadow-sm mb-4 border-start border-4 border-danger">
            <div class="card-body">
                <h6 class="fw-semibold mb-2 text-danger">
                    <i class="bi bi-x-circle me-2"></i>Format Header CSV Tidak Sah
                </h6>
                <p class="small text-muted mb-2">
                    Baris pertama fail CSV mesti mengandungi header yang betul mengikut susunan ini:
                </p>
                <code class="d-block bg-light p-2 rounded small mb-3">name,no_kp,email,phone,agency</code>
                @if(!empty($r['found_headers']))
                <p class="small text-muted mb-0">
                    <i class="bi bi-exclamation-triangle text-warning me-1"></i>
                    Header yang dijumpai: <code>{{ $r['found_headers'] }}</code>
                </p>
                @endif
            </div>
        </div>

        {{-- All IC empty — offer delete --}}
        @elseif(!empty($r['all_empty_ic']))
        <div class="card border-0 shadow-sm mb-4 border-start border-4 border-warning">
            <div class="card-body">
                <h6 class="fw-semibold mb-2 text-warning">
                    <i class="bi bi-exclamation-triangle me-2"></i>Semua No. K/P Kosong
                </h6>
                <p class="small text-muted mb-3">
                    Fail CSV yang dimuat naik tidak mengandungi sebarang No. K/P yang sah.
                    Tiada rekod diimport. Adakah anda ingin <strong>memadam semua peserta belum hadir</strong> dalam program ini?
                </p>
                <form method="POST" action="{{ route('admin.programs.participants.clear', $program) }}">
                    @csrf @method('DELETE')
                    <button type="submit" class="btn btn-danger btn-sm"
                            onclick="return confirm('Padam semua peserta yang belum hadir? Tindakan ini tidak boleh dibatalkan.')">
                        <i class="bi bi-trash me-1"></i> Padam Peserta Belum Hadir
                    </button>
                    <a href="{{ route('admin.programs.participants.import.form', $program) }}"
                       class="btn btn-outline-secondary btn-sm ms-2">Batal</a>
                </form>
            </div>
        </div>
        @else
        {{-- Normal import result --}}
        <div class="card border-0 shadow-sm mb-4 border-start border-4
            {{ $r['failed'] > 0 ? 'border-warning' : 'border-success' }}">
            <div class="card-body">
                <h6 class="fw-semibold mb-3">
                    <i class="bi bi-clipboard-check me-2 text-success"></i>Hasil Import
                </h6>
                <div class="row g-2 text-center mb-3">
                    <div class="col-4">
                        <div class="p-2 bg-success bg-opacity-10 rounded">
                            <div class="fs-4 fw-bold text-success">{{ $r['success'] }}</div>
                            <div class="small text-muted">Berjaya</div>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="p-2 bg-warning bg-opacity-10 rounded">
                            <div class="fs-4 fw-bold text-warning">{{ $r['duplicates'] }}</div>
                            <div class="small text-muted">Duplikasi</div>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="p-2 bg-danger bg-opacity-10 rounded">
                            <div class="fs-4 fw-bold text-danger">{{ $r['failed'] }}</div>
                            <div class="small text-muted">Gagal</div>
                        </div>
                    </div>
                </div>
                @if(!empty($r['errors']))
                <div class="mt-2">
                    <small class="text-muted fw-semibold">Ralat:</small>
                    <ul class="small text-danger mb-0 ps-3 mt-1">
                        @foreach(array_slice($r['errors'], 0, 10) as $err)
                        <li>{{ $err }}</li>
                        @endforeach
                        @if(count($r['errors']) > 10)
                        <li class="text-muted">...dan {{ count($r['errors']) - 10 }} ralat lagi.</li>
                        @endif
                    </ul>
                </div>
                @endif
            </div>
        </div>
        @endif
        @endif

        {{-- Upload Form --}}
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-bottom py-3">
                <span class="fw-semibold">
                    <i class="bi bi-upload me-2 text-primary"></i>Muat Naik Fail CSV
                </span>
            </div>
            <div class="card-body">
                <form method="POST" action="{{ route('admin.programs.participants.import', $program) }}"
                      enctype="multipart/form-data">
                    @csrf
                    <div class="mb-3">
                        <label class="form-label fw-medium">Fail CSV <span class="text-danger">*</span></label>
                        <input type="file" name="csv_file" accept=".csv,.txt"
                               class="form-control @error('csv_file') is-invalid @enderror">
                        <div class="form-text">Saiz maksimum: 5MB. Format: CSV (UTF-8)</div>
                        @error('csv_file')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-medium">Sesi Default</label>
                        <select name="session" class="form-select">
                            <option value="">— Ikut Tetapan Program —</option>
                            <option value="pagi"     {{ $program->default_staff_session === 'pagi'     ? 'selected' : '' }}>Pagi</option>
                            <option value="petang"   {{ $program->default_staff_session === 'petang'   ? 'selected' : '' }}>Petang</option>
                            <option value="full_day" {{ $program->default_staff_session === 'full_day' ? 'selected' : '' }}>Sehari Penuh</option>
                        </select>
                        <div class="form-text">Sesi yang akan digunakan untuk semua peserta dalam fail ini.</div>
                    </div>

                    @if($programEnded)
                    <div class="mb-4 p-3 bg-warning bg-opacity-10 rounded border border-warning-subtle">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="mark_attendance"
                                   value="1" id="markAttendance">
                            <label class="form-check-label fw-medium" for="markAttendance">
                                Tandakan sebagai Data Kehadiran
                            </label>
                        </div>
                        <div class="small text-muted mt-1 ms-4">
                            <i class="bi bi-info-circle me-1"></i>
                            Tempoh check-in telah tamat pada <strong>{{ ($program->checkin_end_at ?? $program->end_date->endOfDay())->format('d M Y, H:i') }}</strong>.
                            Jika ditanda, semua peserta dalam fail ini akan direkodkan sebagai <strong>hadir</strong>.
                            Peserta sedia ada dalam program akan dikemaskini status kehadirannya.
                        </div>
                    </div>
                    @endif

                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-upload me-2"></i>Mula Import
                    </button>
                </form>
            </div>
        </div>
    </div>

    {{-- Format Guide --}}
    <div class="col-lg-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-bottom py-3">
                <span class="fw-semibold">
                    <i class="bi bi-file-earmark-text me-2 text-primary"></i>Format CSV
                </span>
            </div>
            <div class="card-body">
                <p class="small text-muted mb-2">Header wajib (baris pertama):</p>
                <code class="d-block bg-light p-2 rounded small mb-3">name,no_kp,email,phone,agency</code>

                <p class="small text-muted mb-2">Contoh data:</p>
                <code class="d-block bg-light p-2 rounded small mb-3" style="font-size:.75rem; word-break:break-all;">
                    Ahmad Ali,900101011234,ahmad@mbip.gov.my,0123456789,IT<br>
                    Siti Binti Omar,850505055678,,0198765432,Kewangan
                </code>

                <div class="small text-muted">
                    <p class="mb-1"><i class="bi bi-info-circle text-info me-1"></i>No. K/P: 12 digit tanpa sempang.</p>
                    <p class="mb-1"><i class="bi bi-info-circle text-info me-1"></i>Emel, telefon, agensi: boleh kosong.</p>
                    <p class="mb-1"><i class="bi bi-shield-check text-success me-1"></i>Duplikasi dalam program akan dilangkau.</p>
                    <p class="mb-0"><i class="bi bi-shield-check text-success me-1"></i>Ralat satu baris tidak hentikan import keseluruhan.</p>
                </div>

                <div class="mt-3 pt-3 border-top">
                    <a href="{{ route('admin.programs.participants.export', $program) }}"
                       class="btn btn-outline-secondary btn-sm w-100">
                        <i class="bi bi-download me-1"></i> Muat Turun Senarai Semasa
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
