@extends('admin.layouts.app')

@section('title', 'Edit Ad')

@section('content')
    <div class="card" style="margin-bottom: 24px;">
        <div class="card-header">
            <h3 style="margin: 0; font-size: 1.1rem; color: var(--text-primary);">Edit Ad: {{ $ad->title }}</h3>
            <div style="font-size: 0.875rem; color: var(--text-secondary);">Update ad details and custom attributes</div>
        </div>

        <div style="padding: 24px;">
            <form action="{{ route('admin.ads.update', $ad->id) }}" method="POST" enctype="multipart/form-data">
                @csrf
                @method('PUT')

                @if($errors->any())
                    <div style="background: #fef2f2; border: 1px solid #fee2e2; color: #ef4444; padding: 12px; border-radius: 8px; margin-bottom: 20px;">
                        <ul style="margin: 0; padding-left: 20px;">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <!-- User Info (Read Only) -->
                 <div style="margin-bottom: 24px;">
                    <h4 style="margin-bottom: 12px; font-size: 1rem; color: var(--text-primary); border-bottom: 1px solid var(--border-color); padding-bottom: 8px;">Seller Information</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Seller Name</label>
                            <input type="text" value="{{ $ad->user?->name ?? 'Unknown' }}" disabled style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; background: #f1f5f9;">
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Seller Email</label>
                            <input type="text" value="{{ $ad->user?->email ?? 'Unknown' }}" disabled style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; background: #f1f5f9;">
                        </div>
                    </div>
                </div>

                <!-- Basic Ad Details -->
                <div style="margin-bottom: 24px;">
                    <h4 style="margin-bottom: 12px; font-size: 1rem; color: var(--text-primary); border-bottom: 1px solid var(--border-color); padding-bottom: 8px;">Ad Details</h4>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div style="margin-bottom: 16px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Title</label>
                            <input type="text" name="title" value="{{ old('title', $ad->title) }}" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        </div>
                        <div style="margin-bottom: 16px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Category</label>
                            <select name="category_id" id="categorySelect" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                                @foreach(\App\Models\Category::all() as $cat)
                                    <option value="{{ $cat->id }}" {{ $ad->category_id == $cat->id ? 'selected' : '' }}>{{ $cat->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div style="margin-bottom: 16px;">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">Description</label>
                        <textarea name="description" rows="6" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">{{ old('description', $ad->description) }}</textarea>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <div style="margin-bottom: 16px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Price</label>
                            <input type="number" name="price" step="0.01" value="{{ old('price', $ad->price) }}" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        </div>
                        <div style="margin-bottom: 16px;">
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Currency</label>
                            <select name="currency" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                                <option value="USD" {{ $ad->currency == 'USD' ? 'selected' : '' }}>USD</option>
                                <option value="EUR" {{ $ad->currency == 'EUR' ? 'selected' : '' }}>EUR</option>
                                <option value="GBP" {{ $ad->currency == 'GBP' ? 'selected' : '' }}>GBP</option>
                                <option value="INR" {{ $ad->currency == 'INR' ? 'selected' : '' }}>INR</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Custom Fields Section -->
                <div style="margin-bottom: 24px;" id="customFieldsSection">
                    <h4 style="margin-bottom: 12px; font-size: 1rem; color: var(--text-primary); border-bottom: 1px solid var(--border-color); padding-bottom: 8px;">
                        Custom Specifications
                        <span style="font-size:0.8rem; color:var(--text-secondary); font-weight:400; margin-left:10px;">(Loaded for {{ $ad->category?->name ?? 'Category' }})</span>
                    </h4>
                    <div id="customFieldsContainer" style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px;">
                        <!-- Fields will be loaded here via JS -->
                        <div style="grid-column: span 2; text-align: center; color: var(--text-secondary); padding: 20px;">
                            Loading custom fields...
                        </div>
                    </div>
                </div>

                <!-- Location & Status -->
                <div style="margin-bottom: 24px;">
                    <h4 style="margin-bottom: 12px; font-size: 1rem; color: var(--text-primary); border-bottom: 1px solid var(--border-color); padding-bottom: 8px;">Location & Status</h4>
                     <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 16px;">
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">City</label>
                            <input type="text" name="city" value="{{ old('city', $ad->location_city ?? $ad->city) }}" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">State</label>
                            <input type="text" name="state" value="{{ old('state', $ad->location_state ?? $ad->state) }}" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Country</label>
                            <input type="text" name="country" value="{{ old('country', $ad->location_country ?? $ad->country) }}" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Latitude</label>
                            <input type="text" name="latitude" value="{{ old('latitude', $ad->location_latitude ?? $ad->latitude) }}" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        </div>
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Longitude</label>
                            <input type="text" name="longitude" value="{{ old('longitude', $ad->location_longitude ?? $ad->longitude) }}" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                        </div>
                    </div>
                     <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 16px;">
                        <div>
                            <label style="display: block; margin-bottom: 8px; font-weight: 600;">Status</label>
                            <select name="status" required style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">
                                <option value="Active" {{ $ad->status == 'Active' ? 'selected' : '' }}>Active</option>
                                <option value="Pending" {{ $ad->status == 'Pending' ? 'selected' : '' }}>Pending</option>
                                <option value="Sold" {{ $ad->status == 'Sold' ? 'selected' : '' }}>Sold</option>
                                <option value="Expired" {{ $ad->status == 'Expired' ? 'selected' : '' }}>Expired</option>
                                <option value="Rejected" {{ $ad->status == 'Rejected' ? 'selected' : '' }}>Rejected</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div style="display: flex; gap: 12px; justify-content: flex-end; margin-top: 32px;">
                    <a href="{{ route('admin.ads.index') }}" style="padding: 12px 24px; border: 1px solid var(--border-color); border-radius: 8px; background: white; text-decoration: none; color: inherit;">Cancel</a>
                    <button type="submit" style="padding: 12px 24px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer;">Update Ad</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const currentAttributes = @json($ad->attributes->pluck('value', 'category_field_id'));
        const categoryId = "{{ $ad->category_id }}";

        document.addEventListener('DOMContentLoaded', function() {
            loadCustomFields(categoryId);
        });

        // If category changes, reload fields (optional, but good for completeness)
        document.getElementById('categorySelect').addEventListener('change', function(e) {
            loadCustomFields(e.target.value);
        });

        async function loadCustomFields(catId) {
            const container = document.getElementById('customFieldsContainer');
            container.innerHTML = '<div style="grid-column: span 2;">Loading fields...</div>';

            try {
                const response = await fetch(`/admin/category-fields?category_id=${catId}&format=json`, {
                    headers: { 'Accept': 'application/json' }
                });
                
                if(!response.ok) throw new Error('Failed to load fields');
                
                const fields = await response.json();
                
                if (fields.length === 0) {
                    container.innerHTML = '<div style="grid-column: span 2; color: var(--text-secondary);">No custom fields available for this category.</div>';
                    return;
                }

                container.innerHTML = '';
                
                fields.forEach(field => {
                    const existingValue = currentAttributes[field.id] || '';
                    
                    let inputHtml = '';
                    
                    if (field.type === 'text' || field.type === 'number' || field.type === 'date') {
                        inputHtml = `<input type="${field.type}" name="attributes[${field.id}]" value="${existingValue.replace(/"/g, '&quot;')}" class="form-input" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">`;
                    } else if (field.type === 'textarea') {
                         inputHtml = `<textarea name="attributes[${field.id}]" rows="3" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">${existingValue}</textarea>`;
                    } else if (field.type === 'select' || field.type === 'dropdown') {
                        let optionsHtml = `<option value="">Select ${field.name}</option>`;
                        if (field.options) {
                            const opts = Array.isArray(field.options) ? field.options : JSON.parse(field.options);
                            opts.forEach(opt => {
                                const selected = (existingValue === opt) ? 'selected' : '';
                                optionsHtml += `<option value="${opt}" ${selected}>${opt}</option>`;
                            });
                        }
                        inputHtml = `<select name="attributes[${field.id}]" style="width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px;">${optionsHtml}</select>`;
                    } else if (field.type === 'radio') {
                         if (field.options) {
                            const opts = Array.isArray(field.options) ? field.options : JSON.parse(field.options);
                            inputHtml = `<div style="display: flex; gap: 12px; flex-wrap: wrap;">`;
                            opts.forEach(opt => {
                                const checked = (existingValue === opt) ? 'checked' : '';
                                inputHtml += `
                                    <label style="display: flex; align-items: center; gap: 6px;">
                                        <input type="radio" name="attributes[${field.id}]" value="${opt}" ${checked}> ${opt}
                                    </label>
                                `;
                            });
                            inputHtml += `</div>`;
                        }
                    } else if (field.type === 'checkbox') {
                         // Parse existing value if it is JSON array
                         let checkedValues = [];
                         try { checkedValues = JSON.parse(existingValue); } catch(e) { checkedValues = [existingValue]; }
                         if (!Array.isArray(checkedValues)) checkedValues = [];

                         if (field.options) {
                            const opts = Array.isArray(field.options) ? field.options : JSON.parse(field.options);
                            inputHtml = `<div style="display: flex; gap: 12px; flex-wrap: wrap;">`;
                            opts.forEach(opt => {
                                const checked = checkedValues.includes(opt) ? 'checked' : '';
                                inputHtml += `
                                    <label style="display: flex; align-items: center; gap: 6px;">
                                        <input type="checkbox" name="attributes[${field.id}][]" value="${opt}" ${checked}> ${opt}
                                    </label>
                                `;
                            });
                            inputHtml += `</div>`;
                        }
                    }

                    const div = document.createElement('div');
                    div.innerHTML = `
                        <label style="display: block; margin-bottom: 8px; font-weight: 600;">
                            ${field.icon ? field.icon + ' ' : ''}${field.name}
                            ${field.is_required ? '<span style="color: red;">*</span>' : ''}
                        </label>
                        ${inputHtml}
                    `;
                    container.appendChild(div);
                });

            } catch (err) {
                console.error(err);
                container.innerHTML = '<div style="color: red;">Error loading fields.</div>';
            }
        }
    </script>
@endsection
