<style>
.form-card { background:#fff; border-radius:14px; border:1px solid #e9ecef; box-shadow:0 2px 12px rgba(0,0,0,0.06); padding:28px; margin-bottom:20px; }
.form-section-title { font-size:.88rem; font-weight:800; text-transform:uppercase; letter-spacing:.06em; color:#64748b; margin-bottom:14px; padding-bottom:8px; border-bottom:2px solid #f1f5f9; display:flex; align-items:center; gap:7px; }
.form-section-title i { color:#f59e0b; }
.ql-editor { min-height:240px; font-size:.95rem; }
.ql-toolbar.ql-snow, .ql-container.ql-snow { border-color:#dee2e6 !important; }
.ql-toolbar.ql-snow { border-radius:8px 8px 0 0; }
.ql-container.ql-snow { border-radius:0 0 8px 8px; }

.existing-gallery { display:flex; flex-wrap:wrap; gap:10px; margin-bottom:16px; }
.existing-item { position:relative; width:110px; height:110px; border-radius:10px; overflow:hidden; background:#f1f5f9; border:2px solid #e9ecef; }
.existing-item img { width:100%; height:100%; object-fit:cover; }
.existing-item .del-btn {
  position:absolute; top:4px; right:4px;
  width:24px; height:24px; border-radius:50%;
  background:rgba(239,68,68,.9); color:#fff; border:none;
  font-size:.75rem; display:flex; align-items:center; justify-content:center;
  cursor:pointer; text-decoration:none;
}
.existing-count { font-size:.78rem; color:#6b7280; }

.upload-zone {
  border:2px dashed #fcd34d; border-radius:12px;
  background:#fffbeb; padding:28px; text-align:center;
  cursor:pointer; transition:border-color .2s, background .2s;
}
.upload-zone:hover, .upload-zone.dragover { border-color:#f59e0b; background:#fef3c7; }
#preview-grid { display:flex; flex-wrap:wrap; gap:10px; margin-top:14px; }
.preview-thumb { position:relative; width:110px; height:110px; border-radius:10px; overflow:hidden; background:#f1f5f9; }
.preview-thumb img { width:100%; height:100%; object-fit:cover; }
.preview-thumb .remove-preview {
  position:absolute; top:4px; right:4px; width:22px; height:22px; border-radius:50%;
  background:rgba(239,68,68,.9); color:#fff; border:none; font-size:.7rem;
  display:flex; align-items:center; justify-content:center; cursor:pointer;
}
#thumb-preview { width:100%; max-height:220px; object-fit:cover; border-radius:10px; display:block; margin-top:10px; }
.btn-save { background:linear-gradient(135deg,#f59e0b,#f97316); color:#fff; border:none; border-radius:50px; padding:11px 36px; font-weight:700; font-size:.95rem; transition:all .2s; }
.btn-save:hover { opacity:.9; transform:translateY(-1px); }
</style>

<link href="https://cdn.quilljs.com/1.3.7/quill.snow.css" rel="stylesheet">

<!-- Back + Title -->
<div class="d-flex align-items-center gap-3 mb-4">
    <a href="<?php echo base_url('kegiatan/detail/'.$kegiatan->id); ?>"
       class="btn btn-sm btn-outline-secondary" style="border-radius:50px; padding:6px 16px;">
        <i class="bi bi-arrow-left me-1"></i>Kembali
    </a>
    <div>
        <h5 class="fw-bold mb-0 text-dark">Edit Kegiatan</h5>
        <small class="text-muted">Perbarui informasi kegiatan</small>
    </div>
</div>

<?php if($this->session->flashdata('error')): ?>
<div class="alert alert-danger alert-dismissible fade show" style="border-radius:10px;" role="alert">
    <i class="bi bi-exclamation-circle me-2"></i><?php echo $this->session->flashdata('error'); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<form method="post" action="<?php echo base_url('kegiatan/edit/'.$kegiatan->id); ?>" enctype="multipart/form-data" id="formEdit">

<div class="row g-3">
    <!-- LEFT -->
    <div class="col-lg-8">
        <div class="form-card">
            <div class="form-section-title"><i class="bi bi-pencil"></i>Informasi Kegiatan</div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">Judul <span class="text-danger">*</span></label>
                <input type="text" name="judul" class="form-control" style="border-radius:8px;"
                       value="<?php echo set_value('judul', $kegiatan->judul); ?>">
                <?php echo form_error('judul','<small class="text-danger">','</small>'); ?>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">Artikel / Isi <span class="text-danger">*</span></label>
                <div id="quill-editor"></div>
                <textarea name="isi" id="isi-hidden" style="display:none;"><?php echo set_value('isi', $kegiatan->isi); ?></textarea>
                <?php echo form_error('isi','<small class="text-danger">','</small>'); ?>
            </div>
        </div>

        <!-- Galeri Existing -->
        <?php if(!empty($galeri)): ?>
        <div class="form-card">
            <div class="form-section-title"><i class="bi bi-grid-3x3-gap"></i>
                Foto Galeri Saat Ini
                <span class="existing-count ms-1">(<?php echo count($galeri); ?> foto)</span>
            </div>
            <div class="existing-gallery">
                <?php foreach($galeri as $foto): ?>
                <div class="existing-item">
                    <img src="<?php echo base_url('uploads/kegiatan/galeri/'.$foto->nama_file); ?>" alt="">
                    <a href="<?php echo base_url('kegiatan/hapus_foto/'.$foto->id); ?>"
                       class="del-btn"
                       onclick="return confirm('Hapus foto ini?')"
                       title="Hapus foto">
                        <i class="bi bi-trash-fill" style="font-size:.6rem;"></i>
                    </a>
                </div>
                <?php endforeach; ?>
            </div>
            <small class="text-muted"><i class="bi bi-info-circle me-1"></i>Klik ikon hapus pada foto untuk menghapusnya</small>
        </div>
        <?php endif; ?>

        <!-- Upload Galeri Baru -->
        <div class="form-card">
            <div class="form-section-title"><i class="bi bi-plus-square"></i>Tambah Foto Galeri</div>
            <div class="upload-zone" id="dropzone" onclick="document.getElementById('galeri-input').click()">
                <div style="font-size:2rem;color:#fbbf24;margin-bottom:6px;">📸</div>
                <div class="fw-semibold text-muted mb-1">Tambah foto baru ke galeri</div>
                <small class="text-muted">JPG, PNG, WEBP — maks. 5 MB per foto</small>
                <input type="file" name="galeri[]" id="galeri-input" multiple accept="image/*" style="display:none;">
            </div>
            <div id="preview-grid"></div>
        </div>
    </div>

    <!-- RIGHT -->
    <div class="col-lg-4">
        <div class="form-card">
            <div class="form-section-title"><i class="bi bi-sliders"></i>Pengaturan</div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">Status</label>
                <select name="status" class="form-select" style="border-radius:8px;">
                    <option value="draft" <?php echo set_select('status','draft',($kegiatan->status=='draft')); ?>>📝 Draft</option>
                    <option value="publish" <?php echo set_select('status','publish',($kegiatan->status=='publish')); ?>>✅ Publish</option>
                </select>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">Kategori <span class="text-danger">*</span></label>
                <select name="kategori" class="form-select" style="border-radius:8px;">
                    <?php
                    $kats = ['sosial'=>'🤝 Sosial','olahraga'=>'⚽ Olahraga','kebersihan'=>'🧹 Kebersihan',
                             'keagamaan'=>'🕌 Keagamaan','pendidikan'=>'📚 Pendidikan',
                             'kesehatan'=>'❤️ Kesehatan','budaya'=>'🎭 Budaya','lainnya'=>'📌 Lainnya'];
                    foreach($kats as $k=>$v): ?>
                    <option value="<?php echo $k; ?>" <?php echo set_select('kategori',$k,($kegiatan->kategori==$k)); ?>><?php echo $v; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">Tanggal Mulai</label>
                <input type="date" name="tanggal_mulai" class="form-control" style="border-radius:8px;"
                       value="<?php echo set_value('tanggal_mulai', $kegiatan->tanggal_mulai); ?>">
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">Tanggal Selesai</label>
                <input type="date" name="tanggal_selesai" class="form-control" style="border-radius:8px;"
                       value="<?php echo set_value('tanggal_selesai', $kegiatan->tanggal_selesai); ?>">
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold small">Lokasi</label>
                <input type="text" name="lokasi" class="form-control" style="border-radius:8px;"
                       value="<?php echo set_value('lokasi', $kegiatan->lokasi); ?>">
            </div>

            <button type="submit" class="btn-save w-100">
                <i class="bi bi-check-lg me-2"></i>Simpan Perubahan
            </button>
        </div>

        <!-- Thumbnail -->
        <div class="form-card">
            <div class="form-section-title"><i class="bi bi-image"></i>Thumbnail</div>
            <?php if($kegiatan->thumbnail): ?>
            <img src="<?php echo base_url('uploads/kegiatan/'.$kegiatan->thumbnail); ?>"
                 id="thumb-preview" alt="Thumbnail saat ini">
            <?php else: ?>
            <img id="thumb-preview" src="" alt="" style="display:none;">
            <?php endif; ?>
            <div class="mt-2">
                <label class="form-label fw-semibold small">Ganti Thumbnail</label>
                <input type="file" name="thumbnail" accept="image/*" class="form-control"
                       style="border-radius:8px;" onchange="previewThumb(this)">
                <small class="text-muted">Kosongkan jika tidak ingin mengganti</small>
            </div>
        </div>
    </div>
</div>

</form>

<script src="https://cdn.quilljs.com/1.3.7/quill.min.js"></script>
<script>
var quill = new Quill('#quill-editor', {
    theme: 'snow',
    modules: {
        toolbar: [
            [{ header: [2, 3, false] }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ color: [] }, { background: [] }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote', 'code-block'],
            ['link', 'image'],
            ['clean']
        ]
    }
});
quill.root.innerHTML = <?php echo json_encode($kegiatan->isi); ?>;

document.getElementById('formEdit').addEventListener('submit', function() {
    document.getElementById('isi-hidden').value = quill.root.innerHTML;
});

function previewThumb(input) {
    var prev = document.getElementById('thumb-preview');
    if(input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) { prev.src = e.target.result; prev.style.display = 'block'; };
        reader.readAsDataURL(input.files[0]);
    }
}

var allFiles = [];
function renderPreviews() {
    var grid = document.getElementById('preview-grid');
    grid.innerHTML = '';
    allFiles.forEach(function(file, idx) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var div = document.createElement('div');
            div.className = 'preview-thumb';
            div.innerHTML = '<img src="'+e.target.result+'">' +
                '<button type="button" class="remove-preview" onclick="removeFile('+idx+')">&#x2715;</button>';
            grid.appendChild(div);
        };
        reader.readAsDataURL(file);
    });
    rebuildInput();
}
function rebuildInput() {
    var input = document.getElementById('galeri-input');
    var dt = new DataTransfer();
    allFiles.forEach(function(f) { dt.items.add(f); });
    input.files = dt.files;
}
function removeFile(idx) { allFiles.splice(idx, 1); renderPreviews(); }
document.getElementById('galeri-input').addEventListener('change', function(e) {
    Array.from(e.target.files).forEach(function(f) { allFiles.push(f); });
    renderPreviews();
});
var dz = document.getElementById('dropzone');
dz.addEventListener('dragover', function(e) { e.preventDefault(); dz.classList.add('dragover'); });
dz.addEventListener('dragleave', function() { dz.classList.remove('dragover'); });
dz.addEventListener('drop', function(e) {
    e.preventDefault(); dz.classList.remove('dragover');
    Array.from(e.dataTransfer.files).forEach(function(f) {
        if(f.type.startsWith('image/')) allFiles.push(f);
    });
    renderPreviews();
});
</script>