{{--
    Health Marketor Dashboard — Edit Machine Listing
    Authenticated page with <x-app-layout> + <x-module-hero>
    Requirements: 8.2, 8.4
--}}
<x-app-layout>

    <x-module-hero
        title="Edit Machine Listing"
        description="{{ $machine->name }}"
        icon="fa-cogs"
    >
        <x-slot name="backButton">
            <a href="{{ route('dashboard.machines.index') }}"
               class="inline-flex items-center gap-2 text-white/80 hover:text-white text-sm transition">
                <i class="fas fa-arrow-left"></i> Back to My Machines
            </a>
        </x-slot>
        <x-slot name="tabs">
            @can('view institutions')
                <a href="{{ route('dashboard.institutions.index') }}" class="module-hero-tab">
                    <i class="fas fa-hospital"></i> My Institutions
                </a>
            @endcan
            @can('view machines')
                <a href="{{ route('dashboard.machines.index') }}" class="module-hero-tab active-tab" aria-current="page">
                    <i class="fas fa-cogs"></i> My Machines
                </a>
            @endcan
            @can('view payments')
                <a href="{{ route('dashboard.payments.index') }}" class="module-hero-tab">
                    <i class="fas fa-credit-card"></i> Payment History
                </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        @if(session('success'))
            <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded-lg flex items-center">
                <i class="fas fa-check-circle mr-3"></i>{{ session('success') }}
            </div>
        @endif

        @if($errors->any())
            <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg">
                <div class="flex items-center mb-2">
                    <i class="fas fa-exclamation-circle mr-3"></i>
                    <strong>Please fix the following errors:</strong>
                </div>
                <ul class="list-disc list-inside ml-4 text-sm">
                    @foreach($errors->all() as $error)<li>{{ $error }}</li>@endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('dashboard.machines.update', $machine) }}"
              method="POST"
              enctype="multipart/form-data"
              x-data="{
                  step: 1,
                  totalSteps: 4,
                  existingImages: {{ json_encode($machine->images ?? []) }},
                  removeImages: [],
                  newPreviews: [],
                  handleNewImages(event) {
                      const files = Array.from(event.target.files);
                      files.forEach(file => {
                          if (file.type.startsWith('image/')) {
                              const reader = new FileReader();
                              reader.onload = (e) => this.newPreviews.push(e.target.result);
                              reader.readAsDataURL(file);
                          }
                      });
                  },
                  markForRemoval(index) {
                      if (!this.removeImages.includes(index)) this.removeImages.push(index);
                  }
              }">
            @csrf
            @method('PUT')

            {{-- Step Indicator --}}
            <div class="mb-6">
                <div class="flex justify-between text-sm text-gray-600 mb-2">
                    <span>Step <span x-text="step"></span> of 4</span>
                    <span x-text="Math.round((step / totalSteps) * 100) + '% Complete'"></span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2">
                    <div class="bg-blue-600 h-2 rounded-full transition-all duration-300"
                         :style="'width: ' + ((step / totalSteps) * 100) + '%'"></div>
                </div>
                <div class="flex justify-between mt-2">
                    @foreach(['Basic Info', 'Description', 'Images', 'Pricing'] as $i => $label)
                        <span class="text-xs font-medium"
                              :class="{{ $i + 1 }} <= step ? 'text-blue-600' : 'text-gray-400'">
                            {{ $label }}
                        </span>
                    @endforeach
                </div>
            </div>

            {{-- Step 1: Basic Information --}}
            <div x-show="step === 1" x-transition>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-4">
                    <h3 class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4">
                        <i class="fas fa-info-circle mr-2 text-blue-600"></i>Basic Information
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-1">
                                Machine Name <span class="text-red-500">*</span>
                            </label>
                            <input type="text" name="name" value="{{ old('name', $machine->name) }}" required
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 focus:ring-1 focus:ring-blue-500 transition">
                            @error('name')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                            <select name="category"
                                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                                <option value="">Select Category</option>
                                @foreach($categories as $key => $label)
                                    <option value="{{ $key }}" {{ old('category', $machine->category) == $key ? 'selected' : '' }}>{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Brand</label>
                            <input type="text" name="brand" value="{{ old('brand', $machine->brand) }}"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Model</label>
                            <input type="text" name="model" value="{{ old('model', $machine->model) }}"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Vendor</label>
                            <input type="text" name="vendor" value="{{ old('vendor', $machine->vendor) }}"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Manufacturer</label>
                            <input type="text" name="manufacturers" value="{{ old('manufacturers', $machine->manufacturers) }}"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                    </div>
                </div>
            </div>

            {{-- Step 2: Description & Specs --}}
            <div x-show="step === 2" x-transition>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-4">
                    <h3 class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4">
                        <i class="fas fa-file-alt mr-2 text-purple-600"></i>Description & Specifications
                    </h3>
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                            <textarea name="description" rows="5"
                                      class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">{{ old('description', $machine->description) }}</textarea>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Technical Specifications</label>
                            <textarea name="specifications" rows="4"
                                      class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">{{ old('specifications', is_array($machine->specifications) ? json_encode($machine->specifications) : $machine->specifications) }}</textarea>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Key Functionalities (one per line)</label>
                            <textarea name="functionalities" rows="3"
                                      class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">{{ old('functionalities', is_array($machine->functionalities) ? implode("\n", $machine->functionalities) : $machine->functionalities) }}</textarea>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Step 3: Images --}}
            <div x-show="step === 3" x-transition>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-4">
                    <h3 class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4">
                        <i class="fas fa-images mr-2 text-orange-600"></i>Images & Media
                    </h3>
                    <div class="space-y-4">
                        {{-- Existing Images --}}
                        @if($machine->images && count($machine->images) > 0)
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Current Images</label>
                                <div class="grid grid-cols-4 gap-3">
                                    @foreach($machine->images as $index => $image)
                                        <div class="relative aspect-square rounded-lg overflow-hidden border-2"
                                             :class="removeImages.includes({{ $index }}) ? 'border-red-500 opacity-50' : 'border-gray-200'">
                                            <img src="{{ asset('storage/' . $image) }}"
                                                 class="w-full h-full object-cover">
                                            <button type="button"
                                                    @click="markForRemoval({{ $index }})"
                                                    class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center hover:bg-red-600 text-xs">
                                                <i class="fas fa-times"></i>
                                            </button>
                                            <template x-if="removeImages.includes({{ $index }})">
                                                <div class="absolute inset-0 bg-red-500/50 flex items-center justify-center">
                                                    <span class="text-white text-xs font-medium">Remove</span>
                                                </div>
                                            </template>
                                        </div>
                                    @endforeach
                                </div>
                                <template x-for="(idx, i) in removeImages" :key="i">
                                    <input type="hidden" name="remove_images[]" :value="idx">
                                </template>
                            </div>
                        @endif

                        {{-- Add New Images --}}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Add New Images</label>
                            <input type="file" name="images[]" multiple accept="image/*"
                                   @change="handleNewImages($event)"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:border-blue-500 transition">
                            <div class="grid grid-cols-4 gap-3 mt-3">
                                <template x-for="(preview, index) in newPreviews" :key="'new-' + index">
                                    <div class="relative aspect-square">
                                        <img :src="preview" class="w-full h-full object-cover rounded-lg">
                                        <span class="absolute bottom-1 left-1 bg-green-500 text-white text-xs px-1.5 py-0.5 rounded">New</span>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {{-- Step 4: Pricing & Contact --}}
            <div x-show="step === 4" x-transition>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 mb-4">
                    <h3 class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4">
                        <i class="fas fa-dollar-sign mr-2 text-green-600"></i>Pricing & Contact
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Price (SSP)</label>
                            <input type="number" name="price_ssp" value="{{ old('price_ssp', $machine->price_ssp) }}"
                                   step="0.01" min="0"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Price (USD)</label>
                            <input type="number" name="price_usd" value="{{ old('price_usd', $machine->price_usd) }}"
                                   step="0.01" min="0"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm font-medium text-gray-700 mb-2">Price Visibility</label>
                            <div class="flex items-center gap-6">
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="price_publishable" value="1"
                                           {{ $machine->price_publishable ? 'checked' : '' }}
                                           class="h-4 w-4 text-blue-600">
                                    <span class="text-sm text-gray-700">Show Price</span>
                                </label>
                                <label class="flex items-center gap-2 cursor-pointer">
                                    <input type="radio" name="price_publishable" value="0"
                                           {{ !$machine->price_publishable ? 'checked' : '' }}
                                           class="h-4 w-4 text-blue-600">
                                    <span class="text-sm text-gray-700">Hide Price (Contact for Price)</span>
                                </label>
                            </div>
                        </div>
                        @php $contactInfo = $machine->contact_info ?? []; @endphp
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Contact Phone</label>
                            <input type="text" name="contact_phone"
                                   value="{{ old('contact_phone', $contactInfo['phone'] ?? '') }}"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Contact Email</label>
                            <input type="email" name="contact_email"
                                   value="{{ old('contact_email', $contactInfo['email'] ?? '') }}"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:border-blue-500 transition">
                        </div>
                    </div>
                </div>
            </div>

            {{-- Navigation --}}
            <div class="flex justify-between mt-4">
                <button type="button" @click="step--" x-show="step > 1"
                        class="inline-flex items-center gap-2 px-5 py-2.5 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition text-sm font-medium">
                    <i class="fas fa-arrow-left"></i> Previous
                </button>
                <button type="button" @click="step++" x-show="step < totalSteps"
                        class="inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition text-sm font-medium ml-auto">
                    Next <i class="fas fa-arrow-right"></i>
                </button>
                <button type="submit" x-show="step === totalSteps"
                        class="inline-flex items-center gap-2 px-6 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm font-medium ml-auto">
                    <i class="fas fa-save"></i> Save Changes
                </button>
            </div>
        </form>

    </div>

</x-app-layout>
