@extends('layouts.app')

@section('content')
<style>
    select.form-control,
    select.form-select {
        color: #212529 !important;
        background-color: #ffffff !important;
    }

    select.form-control option,
    select.form-select option {
        color: #212529 !important;
        background-color: #ffffff !important;
    }

    select.form-control option:checked,
    select.form-select option:checked {
        color: #ffffff !important;
        background-color: #0d6efd !important;
    }
</style>

<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-header">
            <h5>Edit Animal</h5>
        </div>

        <div class="card-body">

            {{-- Main Update Form --}}
            <form 
                id="animal-update-form"
                action="{{ route('animals.update', $animal->id) }}" 
                method="POST" 
                enctype="multipart/form-data"
            >
                @csrf
                @method('PUT')

                <div class="row">

                    {{-- Category --}}
                    <div class="col-md-6 mb-3">
                        <label for="cattle_category_id" class="form-label">Category</label>

                        <select 
                            name="cattle_category_id" 
                            id="cattle_category_id" 
                            class="form-select @error('cattle_category_id') is-invalid @enderror" 
                            required
                        >
                            <option value="">Select Category</option>

                           @forelse($categories ?? [] as $category)
                                    <option 
                                        value="{{ $category->id }}"
                                        {{ old('cattle_category_id', $animal->cattle_category_id ?? '') == $category->id ? 'selected' : '' }}
                                    >
                                        {{ $category->title }}
                                    </option>
                                @empty
                                    <option value="" disabled>No category found</option>
                                @endforelse
                        </select>

                        @error('cattle_category_id')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Animal Name --}}
                    <div class="col-md-6 mb-3">
                        <label for="animal_name" class="form-label">Animal Name</label>

                        <input 
                            type="text"
                            name="animal_name"
                            id="animal_name"
                            class="form-control @error('animal_name') is-invalid @enderror"
                            value="{{ old('animal_name', $animal->animal_name ?? '') }}"
                            required
                        >

                        @error('animal_name')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Buy Date --}}
                    <div class="col-md-6 mb-3">
                        <label for="buy_date" class="form-label">Buy Date</label>

                        <input 
                            type="date"
                            name="buy_date"
                            id="buy_date"
                            class="form-control @error('buy_date') is-invalid @enderror"
                            value="{{ old('buy_date', $animal->buy_date ?? '') }}"
                        >

                        @error('buy_date')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Buy Price --}}
                    <div class="col-md-6 mb-3">
                        <label for="buy_price" class="form-label">Buy Price</label>

                        <input 
                            type="number"
                            step="0.01"
                            name="buy_price"
                            id="buy_price"
                            class="form-control @error('buy_price') is-invalid @enderror"
                            value="{{ old('buy_price', $animal->buy_price ?? '') }}"
                        >

                        @error('buy_price')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Sale Date --}}
                    <div class="col-md-6 mb-3">
                        <label for="sale_date" class="form-label">Sale Date</label>

                        <input 
                            type="date"
                            name="sale_date"
                            id="sale_date"
                            class="form-control @error('sale_date') is-invalid @enderror"
                            value="{{ old('sale_date', $animal->sale_date ?? '') }}"
                        >

                        @error('sale_date')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Sale Price --}}
                    <div class="col-md-6 mb-3">
                        <label for="sale_price" class="form-label">Sale Price</label>

                        <input 
                            type="number"
                            step="0.01"
                            name="sale_price"
                            id="sale_price"
                            class="form-control @error('sale_price') is-invalid @enderror"
                            value="{{ old('sale_price', $animal->sale_price ?? '') }}"
                        >

                        @error('sale_price')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Breed --}}
                    <div class="col-md-4 mb-3">
                        <label for="breed" class="form-label">Breed</label>

                        <input 
                            type="text"
                            name="breed"
                            id="breed"
                            class="form-control @error('breed') is-invalid @enderror"
                            value="{{ old('breed', $animal->breed ?? '') }}"
                        >

                        @error('breed')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Weight --}}
                    <div class="col-md-4 mb-3">
                        <label for="weight" class="form-label">Weight</label>

                        <input 
                            type="number"
                            step="0.01"
                            name="weight"
                            id="weight"
                            class="form-control @error('weight') is-invalid @enderror"
                            value="{{ old('weight', $animal->weight ?? '') }}"
                        >

                        @error('weight')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Tag Number --}}
                    <div class="col-md-4 mb-3">
                        <label for="tag_number" class="form-label">Tag Number</label>

                        <input 
                            type="text"
                            name="tag_number"
                            id="tag_number"
                            class="form-control @error('tag_number') is-invalid @enderror"
                            value="{{ old('tag_number', $animal->tag_number ?? '') }}"
                        >

                        @error('tag_number')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Notes --}}
                    <div class="col-md-12 mb-3">
                        <label for="notes" class="form-label">Notes</label>

                        <textarea 
                            name="notes"
                            id="notes"
                            class="form-control @error('notes') is-invalid @enderror"
                            rows="3"
                        >{{ old('notes', $animal->notes ?? '') }}</textarea>

                        @error('notes')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- Upload New Images --}}
                    <div class="col-md-12 mb-3">
                        <label for="images" class="form-label">Images</label>

                        <input 
                            type="file"
                            name="images[]"
                            id="images"
                            class="form-control @error('images.*') is-invalid @enderror"
                            multiple
                            accept="image/*"
                        >

                        @error('images.*')
                            <small class="text-danger">{{ $message }}</small>
                        @enderror
                    </div>

                    {{-- New Image Preview --}}
                    <div class="col-md-12 mb-3">
                        <div id="preview-area" class="d-flex flex-wrap gap-3"></div>
                    </div>
                </div>

                {{-- Already Uploaded Images --}}
                @if(isset($animal) && $animal->images && $animal->images->count() > 0)
                    <hr>

                    <h6>Uploaded Images</h6>

                    <div class="d-flex flex-wrap gap-3 mb-3">
                        @foreach($animal->images as $img)
                            <div class="border rounded p-2 text-center">
                                <img 
                                    src="{{ asset($img->image) }}"
                                    width="120"
                                    height="120"
                                    style="object-fit: cover; border-radius: 8px;"
                                    alt="Animal Image"
                                >

                                <div class="mt-2">
                                    <a 
                                        href="{{ asset($img->image) }}"
                                        target="_blank"
                                        class="btn btn-sm btn-info"
                                    >
                                        View
                                    </a>

                                    <button 
                                        type="submit"
                                        form="delete-image-form-{{ $img->id }}"
                                        class="btn btn-sm btn-danger"
                                        onclick="return confirm('Delete this image?')"
                                    >
                                        Delete
                                    </button>
                                </div>
                            </div>
                        @endforeach
                    </div>
                @endif

                <button type="submit" class="btn btn-primary mt-3">
                    Update
                </button>

                <a href="{{ route('animals.index') }}" class="btn btn-secondary mt-3">
                    Back
                </a>
            </form>

            {{-- Delete Image Forms - Main form ke bahar rakhe hain --}}
            @if(isset($animal) && $animal->images && $animal->images->count() > 0)
                @foreach($animal->images as $img)
                    <form 
                        id="delete-image-form-{{ $img->id }}"
                        action="{{ route('animal-images.destroy', $img->id) }}"
                        method="POST"
                        style="display: none;"
                    >
                        @csrf
                        @method('DELETE')
                    </form>
                @endforeach
            @endif

        </div>
    </div>
</div>
@endsection

@push('script')
<script>
document.addEventListener('DOMContentLoaded', function () {
    let selectedFiles = [];

    const imageInput = document.getElementById('images');
    const previewArea = document.getElementById('preview-area');

    if (!imageInput || !previewArea) {
        return;
    }

    imageInput.addEventListener('change', function (event) {
        selectedFiles = Array.from(event.target.files);
        renderPreview();
    });

    function renderPreview() {
        previewArea.innerHTML = '';

        selectedFiles.forEach(function (file, index) {
            const reader = new FileReader();

            reader.onload = function (e) {
                const previewBox = document.createElement('div');
                previewBox.classList.add('border', 'rounded', 'p-2', 'text-center');

                previewBox.innerHTML = `
                    <img 
                        src="${e.target.result}"
                        width="120"
                        height="120"
                        style="object-fit: cover; border-radius: 8px;"
                        alt="Preview Image"
                    >

                    <div class="mt-2">
                        <a href="${e.target.result}" target="_blank" class="btn btn-sm btn-info">
                            View
                        </a>

                        <button 
                            type="button"
                            class="btn btn-sm btn-danger remove-image-btn"
                            data-index="${index}"
                        >
                            Delete
                        </button>
                    </div>
                `;

                previewArea.appendChild(previewBox);
            };

            reader.readAsDataURL(file);
        });
    }

    previewArea.addEventListener('click', function (event) {
        if (event.target.classList.contains('remove-image-btn')) {
            const index = event.target.getAttribute('data-index');
            removePreview(index);
        }
    });

    function removePreview(index) {
        selectedFiles.splice(index, 1);

        const dataTransfer = new DataTransfer();

        selectedFiles.forEach(function (file) {
            dataTransfer.items.add(file);
        });

        imageInput.files = dataTransfer.files;

        renderPreview();
    }
});
</script>
@endpush