@extends('layouts.admin')

@section('title', 'Tambah Produk')
@section('page-title', 'Tambah Produk Baru')

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

                        <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"
                                        placeholder="Contoh: Beras Pandan Wangi Super" 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 selected>Pilih Kategori</option>
                                            @foreach($kategoris as $kat)
                                                <option value="{{ $kat->id }}" {{ old('kategori_id') == $kat->id ? 'selected' : '' }}>
                                                    {{ $kat->nama_kategori }}
                                                </option>
                                            @endforeach

                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="fw-bold">Stok (Kg)</label>
                                        <input type="number" name="stok" class="form-control" placeholder="0" required
                                            min="0">
                                    </div>
                                </div>

                                <div class="form-group mb-3">
                                    <label class="fw-bold">Harga (Rp)</label>
                                    <input type="number" name="harga" class="form-control" placeholder="0" required min="0">
                                </div>

                                <div class="form-group mb-3">
                                    <label class="fw-bold">Deskripsi</label>
                                    <textarea name="deskripsi" class="form-control" rows="4"
                                        placeholder="Jelaskan kualitas produk Anda..." required></textarea>
                                </div>
                            </div>

                            {{-- UPLOAD GAMBAR --}}
                            <div class="col-lg-4">
                                <h5 class="mb-4">Media Produk</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;">

                                            {{-- Ikon Upload --}}
                                            <div id="placeholder-utama" class="text-center text-muted">
                                                <i class="bi bi-cloud-arrow-up fs-1"></i>
                                                <div class="small mt-1">Klik untuk upload</div>
                                            </div>

                                            {{-- Tampilan Gambar --}}
                                            <img id="preview-utama" src="#"
                                                class="img-fluid w-100 h-100 object-fit-contain d-none">
                                        </div>

                                        <input type="file" name="foto_produk" class="form-control form-control-sm"
                                            accept="image/*" required onchange="previewMainImage(this)">
                                        <small class="text-muted">Wajib. Tampil di halaman depan.</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 Grid --}}
                                        <div id="gallery-preview-container" class="row g-2 mb-3">
                                            {{-- Gambar preview --}}
                                        </div>

                                        {{-- Input File Visual --}}
                                        <div class="mb-2">
                                            <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. Bisa dihapus sebelum
                                            upload.
                                        </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">Simpan Produk</button>
                        </div>
                    </form>
                </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;

                    // Tampilkan Gambar, Sembunyikan Ikon
                    preview.classList.remove('d-none');
                    placeholder.classList.add('d-none');
                }

                reader.readAsDataURL(input.files[0]);
            } else {
                preview.src = '#';
                preview.classList.add('d-none');
                placeholder.classList.remove('d-none');
            }
        }

        // ----------------------------------------------------
        // LOGIC GALERI TAMBAHAN (KERANJANG UPLOAD)
        // ----------------------------------------------------
        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');

        // "Keranjang" virtual untuk menampung file
        let dt = new DataTransfer();

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

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

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

                dt.items.add(file);

                // Buat HTML Preview
                const reader = new FileReader();
                reader.onload = function (e) {
                    const col = document.createElement('div');
                    col.className = 'col-4 position-relative new-image-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 Listener Tombol Hapus (X)
                    col.querySelector('.remove-btn').addEventListener('click', function () {

                        // Hapus file dari keranjang berdasarkan nama & size
                        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;
                            }
                        }
                        inputReal.files = dt.files;
                        col.remove();
                        updateBadge();
                    });

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

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

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

            // Visual Feedback jika penuh
            if (total >= 3) {
                inputVisual.disabled = true;
                inputVisual.setAttribute('title', 'Slot penuh (Maks 3)');
                countBadge.className = 'badge bg-danger rounded-pill';
            } else {
                inputVisual.disabled = false;
                inputVisual.removeAttribute('title');
                countBadge.className = 'badge bg-primary rounded-pill';
            }
        }
    </script>
@endsection