@extends('layouts.admin')

@section('title', 'Edit Produk')
@section('page-title', 'Edit Produk')

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body">
                    {{-- Form Utama --}}
                    <form action="{{ route('petani.produk.update', $produk->id) }}" method="POST"
                        enctype="multipart/form-data">
                        @csrf
                        @method('PUT')

                        <div class="row">
                            {{-- DATA PRODUK --}}
                            <div class="col-lg-8">
                                <h5 class="mb-4">Informasi Produk</h5>
                                <div class="form-group mb-3">
                                    <label class="fw-bold">Nama Produk</label>
                                    <input type="text" name="nama_produk" class="form-control"
                                        value="{{ $produk->nama_produk }}" required>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="fw-bold">Kategori</label>
                                        <select name="kategori_id" class="form-select" required>
                                            <option value="" disabled>Pilih Kategori</option>
                                            @foreach($kategoris as $kat)
                                                <option value="{{ $kat->id }}" {{ (old('kategori_id', $produk->kategori_id) == $kat->id) ? 'selected' : '' }}>
                                                    {{ $kat->nama_kategori }}
                                                </option>
                                            @endforeach

                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="fw-bold">Stok</label>
                                        <input type="number" name="stok" class="form-control" value="{{ $produk->stok }}"
                                            required>
                                    </div>
                                </div>

                                <div class="form-group mb-3">
                                    <label class="fw-bold">Harga (Rp)</label>
                                    <input type="number" name="harga" class="form-control" value="{{ $produk->harga }}"
                                        required>
                                </div>

                                <div class="form-group mb-3">
                                    <label class="fw-bold">Deskripsi</label>
                                    <textarea name="deskripsi" class="form-control" rows="4"
                                        required>{{ $produk->deskripsi }}</textarea>
                                </div>
                            </div>

                            {{-- KELOLA GAMBAR --}}
                            <div class="col-lg-4">
                                <h5 class="mb-4">Kelola Gambar</h5>

                                {{-- FOTO UTAMA --}}
                                <div class="card bg-light border-0 mb-4">
                                    <div class="card-body">
                                        <label class="fw-bold mb-2">Foto Utama</label>

                                        {{-- AREA PREVIEW --}}
                                        <div class="mb-2 bg-white border rounded d-flex align-items-center justify-content-center position-relative overflow-hidden"
                                            style="height: 150px;">

                                            <div id="placeholder-utama"
                                                class="text-center text-muted {{ $produk->foto_produk ? 'd-none' : '' }}">
                                                <i class="bi bi-cloud-arrow-up fs-1"></i>
                                                <div class="small mt-1">Upload foto baru</div>
                                            </div>

                                            <img id="preview-utama"
                                                src="{{ $produk->foto_produk ? asset('storage/' . $produk->foto_produk) : '#' }}"
                                                class="img-fluid w-100 h-100 object-fit-contain {{ $produk->foto_produk ? '' : 'd-none' }}">
                                        </div>

                                        {{-- Input File --}}
                                        <input type="file" name="foto_produk" class="form-control form-control-sm"
                                            accept="image/*" onchange="previewMainImage(this)">
                                        <small class="text-muted">Biarkan kosong jika tidak ingin mengganti foto.</small>
                                    </div>
                                </div>

                                {{-- GALERI TAMBAHAN --}}
                                <div class="card bg-light border-0">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <label class="fw-bold m-0">Galeri Tambahan</label>
                                            <span class="badge bg-primary rounded-pill" id="count-badge">0/3</span>
                                        </div>

                                        {{-- CONTAINER PREVIEW --}}
                                        <div id="gallery-preview-container" class="row g-2 mb-3">

                                            {{-- Gambar Lama dari Database --}}
                                            @foreach($produk->images as $img)
                                                <div class="col-4 position-relative existing-image-wrapper"
                                                    id="existing-img-{{ $img->id }}">
                                                    <img src="{{ asset('storage/' . $img->foto) }}"
                                                        class="rounded w-100 border bg-white"
                                                        style="height: 70px; object-fit: cover;">

                                                    {{-- Tombol Hapus Gambar Lama --}}
                                                    <a href="javascript:void(0)"
                                                        class="position-absolute top-0 end-0 badge bg-danger text-white rounded-circle text-decoration-none m-1 shadow-sm"
                                                        onclick="if(confirm('Hapus foto ini?')) deleteExistingImage({{ $img->id }});"
                                                        style="cursor: pointer;">&times;</a>
                                                </div>
                                            @endforeach

                                        </div>

                                        {{-- INPUT FILE --}}
                                        <div class="mb-3">
                                            <input type="file" id="input-gallery-visual"
                                                class="form-control form-control-sm" accept="image/*" multiple>
                                        </div>

                                        {{-- INPUT FILE HIDDEN --}}
                                        <input type="file" name="foto_tambahan[]" id="real-input-gallery" class="d-none"
                                            multiple>

                                        <small class="text-muted d-block" style="font-size: 0.8rem;">
                                            <i class="bi bi-info-circle me-1"></i>Maksimal 3 foto tambahan total.
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="border-top pt-3 mt-4 text-end">
                            <a href="{{ route('petani.produk.index') }}" class="btn btn-secondary me-2">Batal</a>
                            <button type="submit" class="btn btn-primary px-4">Update Produk</button>
                        </div>
                    </form>

                    {{-- FORM TERSEMBUNYI UNTUK HAPUS GAMBAR LAMA --}}
                    @foreach($produk->images as $img)
                        <form id="form-del-img-{{ $img->id }}" action="{{ route('petani.produk.image.delete', $img->id) }}"
                            method="POST" style="display: none;">
                            @csrf @method('DELETE')
                        </form>
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    <script>
        // ----------------------------------------------------
        // PREVIEW FOTO UTAMA
        // ----------------------------------------------------
        function previewMainImage(input) {
        const preview = document.getElementById('preview-utama');
        const placeholder = document.getElementById('placeholder-utama');

        if (input.files && input.files[0]) {
            var reader = new FileReader();
            
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.classList.remove('d-none');
                placeholder.classList.add('d-none');
            }
            
            reader.readAsDataURL(input.files[0]);
        }
    }

        // ----------------------------------------------------
        // LOGIC HAPUS GAMBAR LAMA (DATABASE)
        // ----------------------------------------------------
        function deleteExistingImage(id) {
            document.getElementById('form-del-img-' + id).submit();
        }

        // ----------------------------------------------------
        // LOGIC PREVIEW + ACCUMULATE
        // ----------------------------------------------------
        const inputVisual = document.getElementById('input-gallery-visual');
        const inputReal = document.getElementById('real-input-gallery');
        const container = document.getElementById('gallery-preview-container');
        const countBadge = document.getElementById('count-badge');

        let dt = new DataTransfer();
        let existingCount = document.querySelectorAll('.existing-image-wrapper').length;
        updateBadge();

        inputVisual.addEventListener('change', function () {
            const newFiles = this.files;

            if (existingCount + dt.items.length + newFiles.length > 3) {
                alert('Maksimal total hanya boleh 3 gambar tambahan!');
                this.value = '';
                return;
            }

            // Loop file yang baru dipilih
            for (let i = 0; i < newFiles.length; i++) {
                const file = newFiles[i];

                // Tambahkan ke keranjang DataTransfer
                dt.items.add(file);

                // Buat Preview Element
                const reader = new FileReader();
                reader.onload = function (e) {
                    const col = document.createElement('div');
                    col.className = 'col-4 position-relative new-image-preview';

                    // HTML Preview
                    col.innerHTML = `
                                    <img src="${e.target.result}" class="rounded w-100 border bg-white" style="height: 70px; object-fit: cover;">
                                    <span class="position-absolute top-0 end-0 badge bg-secondary text-white rounded-circle m-1 shadow-sm remove-btn" 
                                          style="cursor: pointer;">&times;</span>
                                `;

                    // Event Hapus Preview
                    col.querySelector('.remove-btn').addEventListener('click', function () {
                        for (let j = 0; j < dt.items.length; j++) {
                            if (dt.files[j].name === file.name && dt.files[j].size === file.size) {
                                dt.items.remove(j);
                                break;
                            }
                        }
                        // Sinkronisasi ke Input Real
                        inputReal.files = dt.files;
                        col.remove();
                        updateBadge();
                    });

                    container.appendChild(col);
                };
                reader.readAsDataURL(file);
            }

            inputReal.files = dt.files;
            this.value = '';
            updateBadge();
        });

        function updateBadge() {
            let total = existingCount + dt.items.length;
            countBadge.innerText = total + '/3';

            if (total >= 3) {
                inputVisual.disabled = true;
                countBadge.classList.remove('bg-primary');
                countBadge.classList.add('bg-danger');
                inputVisual.setAttribute('title', 'Kapasitas penuh');
            } else {
                inputVisual.disabled = false;
                countBadge.classList.remove('bg-danger');
                countBadge.classList.add('bg-primary');
                inputVisual.removeAttribute('title');
            }
        }
    </script>
@endsection