@extends('layouts.app')

@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
    /* Optimized CSS - Combined selectors and removed unused styles */
    select[multiple] {
        min-height: 100px;
        max-height: 150px;
    }
    
    select[multiple] option {
        padding: 5px;
    }
    
    select[multiple] option:checked {
        background-color: #007bff;
        color: white;
    }
    
    .form-label small {
        display: block;
        margin-top: 2px;
    }
    
    .anggota-item {
        border-bottom: 1px solid #eee;
        padding: 8px 0;
    }
    
    .anggota-item:last-child {
        border-bottom: none;
    }
    
    .partisipan-checkbox {
        margin-right: 10px;
    }
    
    .selected-partisipan {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 10px;
    }
    
    /* Performance optimization - will-change for smooth scrolling */
    .anggota-item, .selected-partisipan {
        will-change: transform;
    }
</style>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card">
                <div class="card-header">
                    <h4><i class="fas fa-calendar-edit"></i> Update Kegiatan - {{ $kegiatan->nama_kegiatan }}</h4>
                </div>
                
                <div class="card-body">
                    @if($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    @if(session('error'))
                        <div class="alert alert-danger">{{ session('error') }}</div>
                    @endif
                    
                    <form action="{{ route('kegiatan.update', $kegiatan->id) }}" method="POST" id="kegiatanEditForm">
                        @csrf
                        @method('PUT')
                        
                        {{-- Info Kegiatan --}}
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="nama_kegiatan">Nama Kegiatan <span class="text-danger">*</span></label>
                                    <input type="text" name="nama_kegiatan" id="nama_kegiatan" 
                                           class="form-control @error('nama_kegiatan') is-invalid @enderror" 
                                           value="{{ old('nama_kegiatan', $kegiatan->nama_kegiatan) }}" required>
                                    @error('nama_kegiatan')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="form-group mb-3">
                                    <label for="ref_jenis_kegiatan_id">Jenis Kegiatan <span class="text-danger">*</span></label>
                                    <select name="ref_jenis_kegiatan_id" id="ref_jenis_kegiatan_id" 
                                            class="form-control @error('ref_jenis_kegiatan_id') is-invalid @enderror" 
                                            onchange="toggleJenisLainnya()" required>
                                        <option value="">-- Pilih Jenis --</option>
                                        @foreach($jenisKegiatans as $jenis)
                                            <option value="{{ $jenis->ref_jenis_kegiatan_id }}" 
                                                    {{ (old('ref_jenis_kegiatan_id', $kegiatan->ref_jenis_kegiatan_id) == $jenis->ref_jenis_kegiatan_id) ? 'selected' : '' }}>
                                                {{ $jenis->nama_jenis_kegiatan }}
                                            </option>
                                        @endforeach
                                        <option value="lainnya" {{ (old('ref_jenis_kegiatan_id') == 'lainnya' || $kegiatan->jenis_kegiatan_lainnya) ? 'selected' : '' }} class="text-warning fw-bold">
                                            <i class="fas fa-edit me-1"></i>Lainnya
                                        </option>
                                    </select>
                                    @error('ref_jenis_kegiatan_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    
                                    <!-- Input untuk jenis kegiatan lainnya -->
                                    <div id="jenis-lainnya-input" class="mt-2" style="display: {{ (old('ref_jenis_kegiatan_id') == 'lainnya' || $kegiatan->jenis_kegiatan_lainnya) ? 'block' : 'none' }};">
                                        <label for="jenis_kegiatan_lainnya" class="form-label text-warning">
                                            <i class="fas fa-pen me-1"></i>Tuliskan jenis kegiatan lainnya:
                                        </label>
                                        <input type="text" class="form-control @error('jenis_kegiatan_lainnya') is-invalid @enderror" 
                                               id="jenis_kegiatan_lainnya" 
                                               name="jenis_kegiatan_lainnya" 
                                               placeholder="Contoh: Rapat Koordinasi, Workshop, dll"
                                               value="{{ old('jenis_kegiatan_lainnya', $kegiatan->jenis_kegiatan_lainnya) }}">
                                        @error('jenis_kegiatan_lainnya')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="form-group mb-3">
                                    <label for="status_kegiatan">Status Kegiatan <span class="text-danger">*</span></label>
                                    <select name="status_kegiatan" id="status_kegiatan" 
                                            class="form-control @error('status_kegiatan') is-invalid @enderror" required>
                                        <option value="Direncanakan" {{ (old('status_kegiatan', $kegiatan->status_kegiatan) == 'Direncanakan') ? 'selected' : '' }}>Direncanakan</option>
                                        <option value="Berlangsung" {{ (old('status_kegiatan', $kegiatan->status_kegiatan) == 'Berlangsung') ? 'selected' : '' }}>Berlangsung</option>
                                        <option value="Selesai" {{ (old('status_kegiatan', $kegiatan->status_kegiatan) == 'Selesai') ? 'selected' : '' }}>Selesai</option>
                                        <option value="Dibatalkan" {{ (old('status_kegiatan', $kegiatan->status_kegiatan) == 'Dibatalkan') ? 'selected' : '' }}>Dibatalkan</option>
                                    </select>
                                    @error('status_kegiatan')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label for="deskripsi">Deskripsi Kegiatan</label>
                            <textarea name="deskripsi" id="deskripsi" class="form-control" rows="3" 
                                      placeholder="Jelaskan deskripsi kegiatan">{{ old('deskripsi', $kegiatan->deskripsi) }}</textarea>
                        </div>
                        
                        <!-- Event Type Toggle -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="form-group mb-3">
                                    <label class="form-label fw-semibold text-dark">
                                        <i class="fas fa-calendar-alt me-1 text-primary"></i>Jenis Kegiatan <span class="text-danger">*</span>
                                    </label>
                                    <div class="btn-group w-100" role="group" aria-label="Event type">
                                        @php
                                            $isSingleDay = $kegiatan->tanggal_mulai && $kegiatan->tanggal_selesai && 
                                                         $kegiatan->tanggal_mulai->format('Y-m-d') === $kegiatan->tanggal_selesai->format('Y-m-d') && 
                                                         $kegiatan->waktu_mulai;
                                            $eventType = old('event_type', $isSingleDay ? 'single' : 'multi');
                                        @endphp
                                        <input type="radio" class="btn-check" name="event_type" id="single_day" value="single" 
                                               {{ $eventType == 'single' ? 'checked' : '' }}>
                                        <label class="btn btn-outline-primary" for="single_day">
                                            <i class="fas fa-calendar-day me-1"></i>Satu Hari
                                        </label>
                                        
                                        <input type="radio" class="btn-check" name="event_type" id="multi_day" value="multi"
                                               {{ $eventType == 'multi' ? 'checked' : '' }}>
                                        <label class="btn btn-outline-primary" for="multi_day">
                                            <i class="fas fa-calendar-week me-1"></i>Lebih dari Satu Hari
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Single Day Event Fields -->
                        <div id="single_day_fields" style="{{ $eventType == 'single' ? 'display: block;' : 'display: none;' }}">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="tanggal_kegiatan" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-calendar me-1 text-primary"></i>Tanggal <span class="text-danger">*</span>
                                        </label>
                                        <input type="date" name="tanggal_kegiatan" id="tanggal_kegiatan" 
                                               class="form-control @error('tanggal_kegiatan') is-invalid @enderror" 
                                               value="{{ old('tanggal_kegiatan', $kegiatan->tanggal_kegiatan->format('Y-m-d')) }}" 
                                               style="border-radius: 6px;" required>
                                        @error('tanggal_kegiatan')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="waktu_mulai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Mulai <span class="text-danger">*</span>
                                        </label>
                                        <input type="time" name="waktu_mulai" id="waktu_mulai" 
                                               class="form-control @error('waktu_mulai') is-invalid @enderror" 
                                               value="{{ old('waktu_mulai', $kegiatan->waktu_mulai ? \Carbon\Carbon::parse($kegiatan->waktu_mulai)->format('H:i') : '') }}" 
                                               style="border-radius: 6px;" required>
                                        @error('waktu_mulai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="waktu_selesai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Akhir
                                        </label>
                                        <input type="time" name="waktu_selesai" id="waktu_selesai" 
                                               class="form-control @error('waktu_selesai') is-invalid @enderror" 
                                               value="{{ old('waktu_selesai', $kegiatan->waktu_selesai ? \Carbon\Carbon::parse($kegiatan->waktu_selesai)->format('H:i') : '') }}"
                                               style="border-radius: 6px;">
                                        @error('waktu_selesai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Multi Day Event Fields -->
                        <div id="multi_day_fields" style="{{ $eventType == 'multi' ? 'display: block;' : 'display: none;' }}">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="tanggal_mulai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-calendar me-1 text-primary"></i>Tanggal Mulai <span class="text-danger">*</span>
                                        </label>
                                        <input type="date" name="tanggal_mulai" id="tanggal_mulai" 
                                               class="form-control @error('tanggal_mulai') is-invalid @enderror" 
                                               value="{{ old('tanggal_mulai', $kegiatan->tanggal_mulai ? $kegiatan->tanggal_mulai->format('Y-m-d') : $kegiatan->tanggal_kegiatan->format('Y-m-d')) }}" 
                                               style="border-radius: 6px;">
                                        @error('tanggal_mulai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="waktu_mulai_multi" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Mulai <span class="text-danger">*</span>
                                        </label>
                                        <input type="time" name="waktu_mulai_multi" id="waktu_mulai_multi" 
                                               class="form-control @error('waktu_mulai_multi') is-invalid @enderror" 
                                               value="{{ old('waktu_mulai_multi', $kegiatan->waktu_mulai ? \Carbon\Carbon::parse($kegiatan->waktu_mulai)->format('H:i') : '') }}" 
                                               style="border-radius: 6px;">
                                        @error('waktu_mulai_multi')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="tanggal_selesai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-calendar-check me-1 text-primary"></i>Tanggal Akhir <span class="text-danger">*</span>
                                        </label>
                                        <input type="date" name="tanggal_selesai" id="tanggal_selesai" 
                                               class="form-control @error('tanggal_selesai') is-invalid @enderror" 
                                               value="{{ old('tanggal_selesai', $kegiatan->tanggal_selesai ? $kegiatan->tanggal_selesai->format('Y-m-d') : '') }}"
                                               style="border-radius: 6px;">
                                        @error('tanggal_selesai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="waktu_selesai_multi" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Akhir
                                        </label>
                                        <input type="time" name="waktu_selesai_multi" id="waktu_selesai_multi" 
                                               class="form-control @error('waktu_selesai_multi') is-invalid @enderror" 
                                               value="{{ old('waktu_selesai_multi', $kegiatan->waktu_selesai ? \Carbon\Carbon::parse($kegiatan->waktu_selesai)->format('H:i') : '') }}"
                                               style="border-radius: 6px;">
                                        @error('waktu_selesai_multi')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group mb-3">
                                    <label for="tempat">Tempat Kegiatan <span class="text-danger">*</span></label>
                                    <input type="text" name="tempat" id="tempat" 
                                           class="form-control @error('tempat') is-invalid @enderror" 
                                           value="{{ old('tempat', $kegiatan->tempat) }}" required>
                                    @error('tempat')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-group mb-3">
                                    <label for="target_peserta">Target Peserta</label>
                                    <input type="number" name="target_peserta" id="target_peserta" 
                                           class="form-control @error('target_peserta') is-invalid @enderror" 
                                           value="{{ old('target_peserta', $kegiatan->target_peserta) }}" min="1">
                                    @error('target_peserta')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="pic_anggota_id">Person in Charge (PIC)</label>
                                    <select name="pic_anggota_id" id="pic_anggota_id" class="form-control @error('pic_anggota_id') is-invalid @enderror">
                                        <option value="">-- Pilih PIC --</option>
                                        @foreach($anggotas as $anggota)
                                            <option value="{{ $anggota->id }}" 
                                                    {{ (old('pic_anggota_id', $kegiatan->pic_anggota_id) == $anggota->id) ? 'selected' : '' }}>
                                                {{ $anggota->nama_lengkap }} - {{ $anggota->refJenjang->jenjang ?? 'N/A' }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('pic_anggota_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="catatan">Catatan</label>
                                    <textarea name="catatan" id="catatan" class="form-control" rows="2" 
                                              placeholder="Catatan tambahan">{{ old('catatan', $kegiatan->catatan) }}</textarea>
                                </div>
                            </div>
                        </div>
                        
                        {{-- Pilih Partisipan --}}
                        <hr>
                        <h5 class="text-primary"><i class="fas fa-users"></i> Update Daftar Partisipan</h5>
                        
                        {{-- Filter Partisipan --}}
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-filter"></i> Filter Pemilihan Peserta</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-2">
                                                <label class="form-label">Jenis Kelamin</label>
                                                <select id="filter-jenis-kelamin" class="form-control">
                                                    <option value="">Semua</option>
                                                    <option value="L">Laki-laki</option>
                                                    <option value="P">Perempuan</option>
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label class="form-label">DPD</label>
                                                <select id="filter-dpd" class="form-control">
                                                    <option value="">Semua</option>
                                                    @php
                                                        $dpdList = cache()->remember('dpd_active_list', 600, function() {
                                                            return \App\Models\Dpd::active()->select(['dpd_id', 'nama_dpd'])->get();
                                                        });
                                                    @endphp
                                                    @foreach($dpdList as $dpd)
                                                        <option value="{{ $dpd->dpd_id }}">{{ $dpd->nama_dpd }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="col-md-2">
                                                <label class="form-label">DPC</label>
                                                <select id="filter-dpc" class="form-control" multiple disabled>
                                                    <option value="">Pilih DPD dulu</option>
                                                </select>
                                                <small class="text-muted">Pilih satu atau lebih DPC</small>
                                            </div>
                                            <div class="col-md-2">
                                                <label class="form-label">UPA</label>
                                                <select id="filter-upa" class="form-control" multiple disabled>
                                                    <option value="">Pilih DPC dulu</option>
                                                </select>
                                                <small class="text-muted">Pilih satu atau lebih UPA</small>
                                            </div>
                                            <div class="col-md-3">
                                                <label class="form-label">Nama Anggota</label>
                                                <input type="text" id="filter-nama" class="form-control" placeholder="Cari nama...">
                                            </div>
                                            <div class="col-md-1">
                                                <label class="form-label">&nbsp;</label>
                                                <button type="button" id="reset-filter" class="btn btn-outline-secondary btn-block">
                                                    <i class="fas fa-undo"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        {{-- Daftar Anggota dan Partisipan Terpilih --}}
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="text-primary"><i class="fas fa-list"></i> Pilih Anggota Partisipan</h6>
                                <div id="anggota-content" class="border p-3" style="max-height: 400px; overflow-y: auto;">
                                    {{-- Will be populated by JavaScript --}}
                                </div>
                                <small class="text-muted">Centang untuk memilih anggota sebagai partisipan kegiatan</small>
                            </div>
                            
                            <div class="col-md-6">
                                <h6 class="text-primary"><i class="fas fa-check-circle"></i> Partisipan Terpilih</h6>
                                <div id="selected-partisipan" class="selected-partisipan">
                                    @php
                                        $currentPartisipan = $kegiatan->partisipan->pluck('anggota_id')->toArray();
                                        $currentStatus = $kegiatan->partisipan->pluck('status_partisipasi', 'anggota_id')->toArray();
                                    @endphp
                                    @if($kegiatan->partisipan->count() > 0)
                                        @foreach($kegiatan->partisipan as $partisipan)
                                            <div class="anggota-item" data-anggota-id="{{ $partisipan->anggota_id }}">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <strong>{{ $partisipan->anggota->nama_lengkap }}</strong><br>
                                                        <small class="text-muted">{{ $partisipan->anggota->refJenjang->jenjang ?? 'N/A' }} - {{ $partisipan->anggota->no_telepon ?? 'N/A' }}</small>
                                                    </div>
                                                    <div>
                                                        <select name="status_partisipasi[]" class="form-control form-control-sm">
                                                            <option value="Wajib" {{ $partisipan->status_partisipasi == 'Wajib' ? 'selected' : '' }}>Wajib</option>
                                                            <option value="Opsional" {{ $partisipan->status_partisipasi == 'Opsional' ? 'selected' : '' }}>Opsional</option>
                                                            <option value="Undangan" {{ $partisipan->status_partisipasi == 'Undangan' ? 'selected' : '' }}>Undangan</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                        @endforeach
                                    @else
                                        <div class="text-center text-muted py-4">
                                            <i class="fas fa-user-plus fa-3x mb-3"></i>
                                            <p>Pilih anggota dari daftar sebelah kiri</p>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>

                        <div class="form-group mt-4">
                            <button type="submit" class="btn btn-primary" id="submitBtn">
                                <i class="fas fa-save"></i> <span class="btn-text">Update Kegiatan</span>
                            </button>
                            <a href="{{ route('kegiatan.show', $kegiatan->id) }}" class="btn btn-secondary">
                                <i class="fas fa-arrow-left"></i> Kembali
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const checkboxes = document.querySelectorAll('.partisipan-checkbox');
    const selectedContainer = document.getElementById('selected-partisipan');
    
    // Data partisipan yang sudah ada
    const currentStatus = @json($currentStatus);
    
    // Update selected partisipan display
    function updateSelectedPartisipan() {
        const selected = document.querySelectorAll('.partisipan-checkbox:checked');
        
        if (selected.length === 0) {
            selectedContainer.innerHTML = `
                <div class="text-muted text-center py-5">
                    <i class="fas fa-user-plus fa-2x mb-2"></i><br>
                    Pilih anggota dari daftar sebelah kiri
                </div>
            `;
            return;
        }
        
        let html = '<div class="mb-2"><strong>Partisipan Terpilih (' + selected.length + ' orang):</strong></div>';
        
        selected.forEach((checkbox, index) => {
            const label = document.querySelector(`label[for="${checkbox.id}"]`);
            const nama = label.querySelector('strong').textContent;
            const info = label.querySelector('small').textContent;
            const anggotaId = checkbox.value;
            const currentStatusValue = currentStatus[anggotaId] || 'Wajib';
            
            html += `
                <div class="border-bottom pb-2 mb-2">
                    <div class="row align-items-center">
                        <div class="col-8">
                            <strong>${nama}</strong><br>
                            <small class="text-muted">${info}</small>
                        </div>
                        <div class="col-4">
                            <select name="status_partisipasi[]" class="form-control form-control-sm">
                                <option value="Wajib" ${currentStatusValue === 'Wajib' ? 'selected' : ''}>Wajib</option>
                                <option value="Opsional" ${currentStatusValue === 'Opsional' ? 'selected' : ''}>Opsional</option>
                                <option value="Undangan" ${currentStatusValue === 'Undangan' ? 'selected' : ''}>Undangan</option>
                            </select>
                        </div>
                    </div>
                </div>
            `;
        });
        
        selectedContainer.innerHTML = html;
    }
    
    // Event listener untuk checkbox
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectedPartisipan);
    });
    
    // Initialize pada load
    updateSelectedPartisipan();
    
    // Event type toggle functionality
    const singleDayRadio = document.getElementById('single_day');
    const multiDayRadio = document.getElementById('multi_day');
    const singleDayFields = document.getElementById('single_day_fields');
    const multiDayFields = document.getElementById('multi_day_fields');
    
    function toggleEventFields() {
        if (singleDayRadio.checked) {
            singleDayFields.style.display = 'block';
            multiDayFields.style.display = 'none';
            
            // Set required attributes for single day fields
            document.getElementById('tanggal_kegiatan').required = true;
            document.getElementById('waktu_mulai').required = true;
            document.getElementById('waktu_selesai').required = false;
            
            // Clear multi-day fields
            document.getElementById('tanggal_mulai').required = false;
            document.getElementById('tanggal_selesai').required = false;
            document.getElementById('waktu_mulai_multi').required = false;
            document.getElementById('waktu_selesai_multi').required = false;
        } else if (multiDayRadio.checked) {
            singleDayFields.style.display = 'none';
            multiDayFields.style.display = 'block';
            
            // Set required attributes for multi-day fields
            document.getElementById('tanggal_mulai').required = true;
            document.getElementById('tanggal_selesai').required = true;
            document.getElementById('waktu_mulai_multi').required = true;
            document.getElementById('waktu_selesai_multi').required = false;
            
            // Clear single day fields
            document.getElementById('tanggal_kegiatan').required = false;
            document.getElementById('waktu_mulai').required = false;
            document.getElementById('waktu_selesai').required = false;
        }
    }
    
    // Add event listeners
    singleDayRadio.addEventListener('change', toggleEventFields);
    multiDayRadio.addEventListener('change', toggleEventFields);
    
    // Initialize on page load
    toggleEventFields();
    
    // Auto-fill tanggal selesai jika kosong (for multi-day events)
    document.getElementById('tanggal_mulai').addEventListener('change', function() {
        const tanggalMulai = this.value;
        const tanggalSelesai = document.getElementById('tanggal_selesai');
        
        if (tanggalMulai && !tanggalSelesai.value && multiDayRadio.checked) {
            tanggalSelesai.value = tanggalMulai;
        }
    });
});

// Function untuk toggle input jenis kegiatan lainnya
function toggleJenisLainnya() {
    const select = document.getElementById('ref_jenis_kegiatan_id');
    const inputDiv = document.getElementById('jenis-lainnya-input');
    const input = document.getElementById('jenis_kegiatan_lainnya');
    
    if (select.value === 'lainnya') {
        inputDiv.style.display = 'block';
        input.focus();
        input.required = true;
    } else {
        inputDiv.style.display = 'none';
        input.value = '';
        input.required = false;
    }
}

// JavaScript untuk filter dan partisipan (sama seperti di create)
document.addEventListener('DOMContentLoaded', function() {
    const checkboxes = document.querySelectorAll('.partisipan-checkbox');
    const selectedContainer = document.getElementById('selected-partisipan');
    
    // Data partisipan yang sudah ada
    const existingPartisipan = @json($kegiatan->partisipan->pluck('anggota_id')->toArray());
    const existingStatus = @json($kegiatan->partisipan->pluck('status_partisipasi', 'anggota_id')->toArray());
    
    // Filter elements
    const filterNama = document.getElementById('filter-nama');
    const filterJenisKelamin = document.getElementById('filter-jenis-kelamin');
    const filterDpd = document.getElementById('filter-dpd');
    const filterDpc = document.getElementById('filter-dpc');
    const filterUpa = document.getElementById('filter-upa');
    const resetFilter = document.getElementById('reset-filter');
    
    // State management
    let isLoading = false;
    let currentPage = 1;
    let filteredAnggotaItems = null;
    
    // Debounce function untuk optimasi performa
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    // Update selected partisipan display
    function updateSelectedPartisipan() {
        const selectedCheckboxes = Array.from(document.querySelectorAll('.partisipan-checkbox:checked'));
        const selectedIds = selectedCheckboxes.map(cb => cb.value);
        
        // Update hidden inputs untuk form submission
        updateHiddenInputs(selectedIds);
        
        // Update display
        if (selectedIds.length === 0) {
            selectedContainer.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="fas fa-user-plus fa-3x mb-3"></i>
                    <p>Pilih anggota dari daftar sebelah kiri</p>
                </div>
            `;
        } else {
            let html = '';
            selectedIds.forEach(id => {
                const checkbox = document.querySelector(`input[value="${id}"]`);
                const label = checkbox.nextElementSibling;
                const nama = label.querySelector('strong').textContent;
                const detail = label.querySelector('small').textContent;
                const status = existingStatus[id] || 'Wajib';
                
                html += `
                    <div class="anggota-item" data-anggota-id="${id}">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong>${nama}</strong><br>
                                <small class="text-muted">${detail}</small>
                            </div>
                            <div>
                                <select name="status_partisipasi[]" class="form-control form-control-sm">
                                    <option value="Wajib" ${status === 'Wajib' ? 'selected' : ''}>Wajib</option>
                                    <option value="Opsional" ${status === 'Opsional' ? 'selected' : ''}>Opsional</option>
                                    <option value="Undangan" ${status === 'Undangan' ? 'selected' : ''}>Undangan</option>
                                </select>
                            </div>
                        </div>
                    </div>
                `;
            });
            selectedContainer.innerHTML = html;
        }
    }
    
    // Update hidden inputs untuk form submission
    function updateHiddenInputs(selectedIds) {
        // Remove existing hidden inputs
        document.querySelectorAll('input[name="partisipan[]"]').forEach(input => {
            if (input.type === 'hidden') {
                input.remove();
            }
        });
        
        // Add new hidden inputs
        selectedIds.forEach(id => {
            const hiddenInput = document.createElement('input');
            hiddenInput.type = 'hidden';
            hiddenInput.name = 'partisipan[]';
            hiddenInput.value = id;
            document.getElementById('kegiatanEditForm').appendChild(hiddenInput);
        });
    }
    
    // Load DPC berdasarkan DPD
    function loadDpcByDpd(dpdId) {
        if (!dpdId) {
            filterDpc.innerHTML = '<option value="">Pilih DPD dulu</option>';
            filterDpc.disabled = true;
            return;
        }
        
        fetch(`/api/dpc-by-dpd/${dpdId}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            credentials: 'same-origin'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                filterDpc.innerHTML = '';
                data.forEach(dpc => {
                    filterDpc.innerHTML += `<option value="${dpc.dpc_id}">${dpc.nama_dpc}</option>`;
                });
                filterDpc.disabled = false;
            })
            .catch(error => {
                console.error('Error loading DPC:', error);
                filterDpc.innerHTML = '<option value="">Error loading DPC</option>';
            });
    }
    
    // Load UPA berdasarkan DPC
    function loadUpaByDpc(dpcIds) {
        if (!dpcIds || dpcIds.length === 0) {
            filterUpa.innerHTML = '<option value="">Pilih DPC dulu</option>';
            filterUpa.disabled = true;
            return;
        }
        
        fetch(`/api/upa-by-dpc/${dpcIds.join(',')}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            credentials: 'same-origin'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                filterUpa.innerHTML = '';
                data.forEach(upa => {
                    filterUpa.innerHTML += `<option value="${upa.ref_grup_upa_id}">${upa.nama_grup_upa}</option>`;
                });
                filterUpa.disabled = false;
            })
            .catch(error => {
                console.error('Error loading UPA:', error);
                filterUpa.innerHTML = '<option value="">Error loading UPA</option>';
            });
    }
    
    function resetFilters() {
        filterNama.value = '';
        filterJenisKelamin.value = '';
        filterDpd.value = '';
        filterDpc.innerHTML = '<option value="">Pilih DPD dulu</option>';
        filterDpc.disabled = true;
        filterUpa.innerHTML = '<option value="">Pilih DPC dulu</option>';
        filterUpa.disabled = true;
    }
    
    // Event listeners
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectedPartisipan);
    });
    
    // Debounced filter function untuk optimasi performa
    const debouncedFilterAnggota = debounce(() => {
        loadAnggotaPage(1); // Reset ke halaman 1 saat filter
    }, 300);
    
    // Filter event listeners dengan debouncing
    filterNama.addEventListener('input', debouncedFilterAnggota);
    filterJenisKelamin.addEventListener('change', () => loadAnggotaPage(1));
    filterDpd.addEventListener('change', function() {
        loadDpcByDpd(this.value);
        loadAnggotaPage(1);
    });
    filterDpc.addEventListener('change', function() {
        const selectedDpcIds = Array.from(this.selectedOptions).map(option => option.value);
        loadUpaByDpc(selectedDpcIds);
        loadAnggotaPage(1);
    });
    filterUpa.addEventListener('change', () => loadAnggotaPage(1));
    resetFilter.addEventListener('click', function() {
        resetFilters();
        loadAnggotaPage(1);
    });
    
    // Initialize pada load
    updateSelectedPartisipan();
    
    // Auto-fill tanggal selesai jika kosong
    document.getElementById('tanggal_mulai').addEventListener('change', function() {
        const tanggalMulai = this.value;
        const tanggalSelesai = document.getElementById('tanggal_selesai');
        
        if (tanggalMulai && !tanggalSelesai.value) {
            tanggalSelesai.value = tanggalMulai;
        }
    });
    
    // AJAX Pagination untuk data anggota
    function loadAnggotaPage(page) {
        if (isLoading) return;
        
        console.log('Loading anggota page:', page);
        isLoading = true;
        const loadingHtml = '<div class="text-center py-3"><i class="fas fa-spinner fa-spin"></i> Memuat data...</div>';
        document.getElementById('anggota-content').innerHTML = loadingHtml;
        
        // Get selected partisipan untuk maintain state
        const selectedPartisipan = Array.from(document.querySelectorAll('.partisipan-checkbox:checked')).map(cb => cb.value);
        
        const filters = {
            page: page,
            nama: filterNama.value,
            jenis_kelamin: filterJenisKelamin.value,
            dpd: filterDpd.value,
            dpc: Array.from(filterDpc.selectedOptions).map(option => option.value),
            upa: Array.from(filterUpa.selectedOptions).map(option => option.value),
            old_partisipan: selectedPartisipan
        };
        
        // Build query string for GET request
        const queryParams = new URLSearchParams();
        Object.keys(filters).forEach(key => {
            if (Array.isArray(filters[key])) {
                filters[key].forEach(value => queryParams.append(key + '[]', value));
            } else if (filters[key] !== null && filters[key] !== undefined && filters[key] !== '') {
                queryParams.append(key, filters[key]);
            }
        });
        
        fetch('/api/anggota-paginated?' + queryParams.toString(), {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            console.log('Response status:', response.status);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Response data:', data);
            // Check if there's an error in the response
            if (data.error) {
                throw new Error(data.error);
            }
            
            let html = '';
            if (data.data && data.data.length > 0) {
                data.data.forEach(anggota => {
                    const isChecked = selectedPartisipan.includes(anggota.id.toString());
                    const isExisting = existingPartisipan.includes(anggota.id);
                    const status = existingStatus[anggota.id] || 'Wajib';
                    
                    html += `
                        <div class="anggota-item">
                            <div class="form-check">
                                <input class="form-check-input partisipan-checkbox" type="checkbox" 
                                       value="${anggota.id}" id="anggota_${anggota.id}" 
                                       ${isChecked || isExisting ? 'checked' : ''}>
                                <label class="form-check-label" for="anggota_${anggota.id}">
                                    <strong>${anggota.nama_lengkap}</strong><br>
                                    <small class="text-muted">${anggota.ref_jenjang?.jenjang || 'N/A'} - ${anggota.jenis_kelamin} - ${anggota.ref_grup_upa?.nama_grup_upa || 'N/A'} - ${anggota.dpc?.nama_dpc || 'N/A'} - ${anggota.dpd?.nama_dpd || 'N/A'}</small>
                                </label>
                            </div>
                        </div>
                    `;
                });
                
                // Add pagination
                if (data.last_page > 1) {
                    html += `
                        <div class="d-flex justify-content-center mt-3">
                            <nav>
                                <ul class="pagination pagination-sm">
                                    ${data.current_page > 1 ? `<li class="page-item"><a class="page-link" href="#" data-page="${data.current_page - 1}">Previous</a></li>` : ''}
                                    ${Array.from({length: data.last_page}, (_, i) => i + 1).map(page => 
                                        `<li class="page-item ${page === data.current_page ? 'active' : ''}">
                                            <a class="page-link" href="#" data-page="${page}">${page}</a>
                                        </li>`
                                    ).join('')}
                                    ${data.current_page < data.last_page ? `<li class="page-item"><a class="page-link" href="#" data-page="${data.current_page + 1}">Next</a></li>` : ''}
                                </ul>
                            </nav>
                        </div>
                    `;
                }
            } else {
                html = '<div class="text-center py-3 text-muted">Tidak ada data anggota</div>';
            }
            
            document.getElementById('anggota-content').innerHTML = html;
            
            // Re-attach event listeners
            document.querySelectorAll('.partisipan-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectedPartisipan);
            });
            
            // Re-attach pagination listeners
            document.querySelectorAll('.pagination a').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    loadAnggotaPage(parseInt(this.dataset.page));
                });
            });
            
            filteredAnggotaItems = null;
            currentPage = page;
            isLoading = false;
        })
        .catch(error => {
            console.error('Error loading anggota:', error);
            document.getElementById('anggota-content').innerHTML = `
                <div class="text-center py-3 text-danger">
                    <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                    <div>Error memuat data</div>
                    <small>${error.message}</small>
                    <div class="mt-2">
                        <button class="btn btn-sm btn-outline-primary" onclick="loadAnggotaPage(1)">
                            <i class="fas fa-redo"></i> Coba Lagi
                        </button>
                    </div>
                </div>
            `;
            isLoading = false;
        });
    }
    
    // Event delegation untuk pagination
    document.addEventListener('click', function(e) {
        if (e.target.matches('.pagination a')) {
            e.preventDefault();
            const url = new URL(e.target.href);
            const page = url.searchParams.get('page') || 1;
            loadAnggotaPage(page);
        }
    });
    
    // Optimasi form submission dengan loading state
    const form = document.getElementById('kegiatanEditForm');
    const submitBtn = document.getElementById('submitBtn');
    const btnText = submitBtn.querySelector('.btn-text');
    
    form.addEventListener('submit', function() {
        submitBtn.disabled = true;
        btnText.textContent = 'Menyimpan...';
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span class="btn-text">Menyimpan...</span>';
    });
    
    // Load initial data
    loadAnggotaPage(1);
});
</script>
@endsection