<?php
    $isEdit = isset($listing) && $listing;
    $formAction = $isEdit ? route('dealers.listings.update', $listing->id) : route('dealers.listings.store');
    $method = $isEdit ? 'PUT' : 'POST';

    // Get existing values for edit mode
    $spec = $isEdit ? $listing->specification : null;
    $existingFeatures = $isEdit ? $listing->features->pluck('id')->toArray() : [];
    $existingImages = $isEdit ? $listing->image_url ?? [] : [];
    $existingFinancing = $isEdit ? $listing->financing_options ?? [] : [];

    // Get features
    $safetyFeatures = \App\Models\VehicleFeature::where('category', 'safety')->get();
    $comfortFeatures = \App\Models\VehicleFeature::where('category', 'comfort')->get();
    $entertainmentFeatures = \App\Models\VehicleFeature::where('category', 'entertainment')->get();
?>

<form action="<?php echo e($formAction); ?>" method="POST" enctype="multipart/form-data" id="listing-form">
    <?php echo csrf_field(); ?>
    <?php if($isEdit): ?>
        <?php echo method_field('PUT'); ?>
    <?php endif; ?>

    
    <div class="card card-bordered mb-3">
        <div class="card-inner">
            <h5 class="card-title">1. Basic Information</h5>
            <div class="row g-4">
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="make">Make <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="make" name="make" value="<?php echo e(old('make', $spec?->make)); ?>" placeholder="e.g., Toyota"
                            required>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="model">Model <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="model" name="model" value="<?php echo e(old('model', $spec?->model)); ?>" placeholder="e.g., Camry"
                            required>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="year">Year <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="year" name="year" min="1900" max="<?php echo e(date('Y') + 1); ?>"
                            value="<?php echo e(old('year', $spec?->year)); ?>" placeholder="<?php echo e(date('Y')); ?>" required>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="form-group">
                        <label class="form-label" for="trim">Trim / Edition</label>
                        <input type="text" class="form-control" id="trim" name="trim" value="<?php echo e(old('trim', $spec?->trim)); ?>" placeholder="e.g., Limited, Sport">
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="form-group">
                        <label class="form-label" for="vin">VIN Code <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="vin" name="vin" maxlength="17" value="<?php echo e(old('vin', $spec?->vin)); ?>"
                            placeholder="17-character VIN" <?php echo e($isEdit ? 'readonly' : 'required'); ?>>
                        <?php if($isEdit): ?>
                            <small class="form-text text-muted">VIN cannot be changed after creation.</small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <div class="card card-bordered mb-3">
        <div class="card-inner">
            <h5 class="card-title">2. Technical Specifications</h5>
            <div class="row g-4">
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="engine_capacity">Engine Capacity (cc) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="engine_capacity" name="engine_capacity" value="<?php echo e(old('engine_capacity', $spec?->engine_capacity)); ?>"
                            placeholder="e.g., 2000" required>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="fuel_type">Fuel Type <span class="text-danger">*</span></label>
                        <select class="form-control" id="fuel_type" name="fuel_type" required>
                            <option value="">Select Fuel Type</option>
                            <option value="gasoline" <?php echo e(old('fuel_type', $spec?->fuel_type) == 'gasoline' ? 'selected' : ''); ?>>Gasoline</option>
                            <option value="diesel" <?php echo e(old('fuel_type', $spec?->fuel_type) == 'diesel' ? 'selected' : ''); ?>>Diesel</option>
                            <option value="hybrid" <?php echo e(old('fuel_type', $spec?->fuel_type) == 'hybrid' ? 'selected' : ''); ?>>Hybrid</option>
                            <option value="electric" <?php echo e(old('fuel_type', $spec?->fuel_type) == 'electric' ? 'selected' : ''); ?>>Electric</option>
                        </select>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="transmission">Transmission <span class="text-danger">*</span></label>
                        <select class="form-control" id="transmission" name="transmission" required>
                            <option value="">Select Transmission</option>
                            <option value="automatic" <?php echo e(old('transmission', $spec?->transmission) == 'automatic' ? 'selected' : ''); ?>>Automatic</option>
                            <option value="manual" <?php echo e(old('transmission', $spec?->transmission) == 'manual' ? 'selected' : ''); ?>>Manual</option>
                        </select>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="form-group">
                        <label class="form-label" for="drive_type">Drive Type <span class="text-danger">*</span></label>
                        <select class="form-control" id="drive_type" name="drive_type" required>
                            <option value="">Select Drive Type</option>
                            <option value="AWD" <?php echo e(old('drive_type', $spec?->drive_type) == 'AWD' ? 'selected' : ''); ?>>AWD (All-Wheel Drive)</option>
                            <option value="FWD" <?php echo e(old('drive_type', $spec?->drive_type) == 'FWD' ? 'selected' : ''); ?>>FWD (Front-Wheel Drive)</option>
                            <option value="RWD" <?php echo e(old('drive_type', $spec?->drive_type) == 'RWD' ? 'selected' : ''); ?>>RWD (Rear-Wheel Drive)</option>
                            <option value="4WD" <?php echo e(old('drive_type', $spec?->drive_type) == '4WD' ? 'selected' : ''); ?>>4WD (Four-Wheel Drive)</option>
                        </select>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="form-group">
                        <label class="form-label" for="mileage">Mileage (miles) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="mileage" name="mileage" value="<?php echo e(old('mileage', $spec?->mileage)); ?>"
                            placeholder="e.g., 50000" required>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <div class="card card-bordered mb-3">
        <div class="card-inner">
            <h5 class="card-title">3. Body and Exterior</h5>
            <div class="row g-4">
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="body_type">Body Type <span class="text-danger">*</span></label>
                        <select class="form-control" id="body_type" name="body_type" required>
                            <option value="">Select Body Type</option>
                            <option value="SUV" <?php echo e(old('body_type', $spec?->body_type) == 'SUV' ? 'selected' : ''); ?>>SUV</option>
                            <option value="sedan" <?php echo e(old('body_type', $spec?->body_type) == 'sedan' ? 'selected' : ''); ?>>Sedan</option>
                            <option value="pickup" <?php echo e(old('body_type', $spec?->body_type) == 'pickup' ? 'selected' : ''); ?>>Pickup</option>
                            <option value="coupe" <?php echo e(old('body_type', $spec?->body_type) == 'coupe' ? 'selected' : ''); ?>>Coupe</option>
                            <option value="hatchback" <?php echo e(old('body_type', $spec?->body_type) == 'hatchback' ? 'selected' : ''); ?>>Hatchback</option>
                            <option value="van" <?php echo e(old('body_type', $spec?->body_type) == 'van' ? 'selected' : ''); ?>>Van</option>
                            <option value="convertible" <?php echo e(old('body_type', $spec?->body_type) == 'convertible' ? 'selected' : ''); ?>>Convertible</option>
                        </select>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="exterior_color">Exterior Color <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="exterior_color" name="exterior_color"
                            value="<?php echo e(old('exterior_color', $spec?->exterior_color)); ?>" placeholder="e.g., Black" required>
                    </div>
                </div>
                <div class="col-lg-4">
                    <div class="form-group">
                        <label class="form-label" for="interior_color">Interior Color <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="interior_color" name="interior_color"
                            value="<?php echo e(old('interior_color', $spec?->interior_color)); ?>" placeholder="e.g., Beige" required>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="form-group">
                        <label class="form-label" for="seats">Number of Seats <span class="text-danger">*</span></label>
                        <select class="form-control" id="seats" name="seats" required>
                            <option value="">Select Seats</option>
                            <?php for($i = 2; $i <= 20; $i++): ?>
                                <option value="<?php echo e($i); ?>" <?php echo e(old('seats', $spec?->seats) == $i ? 'selected' : ''); ?>><?php echo e($i); ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div class="form-group">
                        <label class="form-label" for="doors">Number of Doors <span class="text-danger">*</span></label>
                        <select class="form-control" id="doors" name="doors" required>
                            <option value="">Select Doors</option>
                            <?php for($i = 2; $i <= 6; $i++): ?>
                                <option value="<?php echo e($i); ?>" <?php echo e(old('doors', $spec?->doors) == $i ? 'selected' : ''); ?>><?php echo e($i); ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <div class="card card-bordered mb-3">
        <div class="card-inner">
            <h5 class="card-title">4. Price and Financing</h5>
            <div class="row g-4 align-items-center">
                <div class="col-lg-6">
                    <div class="form-group">
                        <label class="form-label" for="price">Price ($) <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" class="form-control" id="price" name="price"
                            value="<?php echo e(old('price', $isEdit ? $listing->price : null)); ?>" placeholder="e.g., 25000" required>
                    </div>
                </div>
                <div class="col-lg-6">
                    <label class="form-label d-block">Financing Options</label>
                    <div class="d-flex flex-wrap gap-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="financing_loan" name="financing_options[]" value="loan"
                                <?php echo e(in_array('loan', old('financing_options', $existingFinancing)) ? 'checked' : ''); ?>>
                            <label class="form-check-label" for="financing_loan">Loan</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="financing_lease" name="financing_options[]" value="lease"
                                <?php echo e(in_array('lease', old('financing_options', $existingFinancing)) ? 'checked' : ''); ?>>
                            <label class="form-check-label" for="financing_lease">Lease</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="financing_cash" name="financing_options[]" value="cash"
                                <?php echo e(in_array('cash', old('financing_options', $existingFinancing)) ? 'checked' : ''); ?>>
                            <label class="form-check-label" for="financing_cash">Cash</label>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <div class="card card-bordered mb-3">
        <div class="card-inner">
            <h5 class="card-title">5. Features and Options</h5>
            <p class="text-soft">Select all features that apply to this vehicle</p>

            <div class="row g-4">
                <div class="col-lg-4">
                    <h6 class="mb-3">Safety Features</h6>
                    <?php $__currentLoopData = $safetyFeatures; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $feature): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="custom-control-input" id="feature_<?php echo e($feature->id); ?>" name="features[]" value="<?php echo e($feature->id); ?>"
                                <?php echo e(in_array($feature->id, old('features', $existingFeatures)) ? 'checked' : ''); ?>>
                            <label class="custom-control-label" for="feature_<?php echo e($feature->id); ?>"><?php echo e($feature->name); ?></label>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
                <div class="col-lg-4">
                    <h6 class="mb-3">Comfort Features</h6>
                    <?php $__currentLoopData = $comfortFeatures; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $feature): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="custom-control-input" id="feature_<?php echo e($feature->id); ?>" name="features[]" value="<?php echo e($feature->id); ?>"
                                <?php echo e(in_array($feature->id, old('features', $existingFeatures)) ? 'checked' : ''); ?>>
                            <label class="custom-control-label" for="feature_<?php echo e($feature->id); ?>"><?php echo e($feature->name); ?></label>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
                <div class="col-lg-4">
                    <h6 class="mb-3">Entertainment Features</h6>
                    <?php $__currentLoopData = $entertainmentFeatures; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $feature): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <div class="custom-control custom-checkbox mb-2">
                            <input type="checkbox" class="custom-control-input" id="feature_<?php echo e($feature->id); ?>" name="features[]" value="<?php echo e($feature->id); ?>"
                                <?php echo e(in_array($feature->id, old('features', $existingFeatures)) ? 'checked' : ''); ?>>
                            <label class="custom-control-label" for="feature_<?php echo e($feature->id); ?>"><?php echo e($feature->name); ?></label>
                        </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            </div>
        </div>
    </div>

    
    <div class="card card-bordered mb-3">
        <div class="card-inner">
            <h5 class="card-title">6. Additional Information</h5>
            <div class="row g-4">
                <div class="col-12">
                    <div class="form-group">
                        <label class="form-label" for="title">Listing Title <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" value="<?php echo e(old('title', $isEdit ? $listing->title : null)); ?>"
                            placeholder="e.g., 2023 Toyota Camry Limited" required>
                    </div>
                </div>
                <div class="col-12">
                    <div class="form-group">
                        <label class="form-label" for="location">Location <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="location" name="location" value="<?php echo e(old('location', $isEdit ? $listing->location : null)); ?>"
                            placeholder="e.g., New York, USA" required>
                    </div>
                </div>
                <div class="col-12">
                    <div class="form-group">
                        <label class="form-label" for="description">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="4" placeholder="Describe the vehicle condition, special features, history, etc."><?php echo e(old('description', $isEdit ? $listing->description : null)); ?></textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <div class="card card-bordered mb-3">
        <div class="card-inner">
            <h5 class="card-title">7. Vehicle Images <span class="text-danger">*</span></h5>
            <p class="text-soft">Upload clear photos of your vehicle (minimum 3 images required)</p>
            <div class="form-group">
                <input type="file" id="vehicle_images" name="vehicle_images[]" multiple accept="image/*" class="form-control">
                <input type="hidden" name="uploaded_images" id="uploaded_images" value='<?php echo e(json_encode($existingImages)); ?>'>
                <div id="existing-images-preview" class="mt-3"></div>
            </div>
        </div>
    </div>

    
    <div class="card card-bordered">
        <div class="card-inner">
            <div class="row g-4">
                <div class="col-12">
                    <button type="submit" class="btn btn-lg btn-primary">
                        <em class="icon ni ni-save"></em>
                        <span><?php echo e($isEdit ? 'Update Listing' : 'Create Listing'); ?></span>
                    </button>
                    <a href="<?php echo e(route('dealers.listings.index')); ?>" class="btn btn-lg btn-light">Cancel</a>
                </div>
            </div>
        </div>
    </div>
</form>

<!-- jQuery for preview -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        var uploadedImages = <?php echo json_encode($existingImages); ?> || [];

        function updateHiddenInput() {
            $('#uploaded_images').val(JSON.stringify(uploadedImages));
        }

        function displayImages() {
            var $preview = $('#existing-images-preview');
            $preview.empty();
            $.each(uploadedImages, function(index, img) {
                var imgHtml = `
                <div style="display:inline-block; margin-right:10px; position:relative;">
                    <img src="${img}" style="width:100px; height:100px; object-fit:cover; border:1px solid #ddd; border-radius:5px;">
                    <button type="button" class="btn btn-sm btn-danger remove-image" data-index="${index}" style="position:absolute; top:0; right:0;">×</button>
                </div>
            `;
                $preview.append(imgHtml);
            });
        }

        // Remove image handler
        $(document).on('click', '.remove-image', function() {
            var index = $(this).data('index');
            uploadedImages.splice(index, 1);
            displayImages();
            updateHiddenInput();
        });

        displayImages();

        // Preview newly selected images
        $('#vehicle_images').on('change', function() {
            var files = this.files;
            $.each(files, function(i, file) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    uploadedImages.push(e.target.result); // For preview only, you need to handle real upload on form submit
                    displayImages();
                    updateHiddenInput();
                }
                reader.readAsDataURL(file);
            });
            $(this).val(''); // Reset input
        });
    });
</script>
<?php /**PATH C:\Users\WB\Desktop\vehicle-listing-backend\resources\views/dealer/listings/partial/form.blade.php ENDPATH**/ ?>