<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>
        Add Listing
    </title>

    {% include 'admin/includes/imports.top.html' %}
    <style>
        .upload_svg {
            fill: #0576bd !important;
        }


        .upload_img {
            object-fit: contain !important;
            width: 120px !important;
        }

        canvas {
            border: 1px solid red !important;
        }

        .obj {
            width: 130px !important;
        }

        #dropzone {
            border: 1px solid blue !important;
            width: 100% !important;
            height: 200px !important;
        }

        .pointer- {
            cursor: pointer !important;
        }
    </style>
    <style>
        #progress-bar {
            margin: 0px;
            width: 100%;
            padding: 0px;
        }
    
        #drop-area {
            border: 2px dashed #ccc;
            overflow: hidden;
        }
    
        #drop-area.highlight {
            border-color: rgb(191, 27, 15);
        }
    
        #gallery {
            margin-top: 10px;
        }
    
        #fileElem {
            display: none;
        }
    
        label span {
            font-size: 12px;
        }
        .slow-spin {
            -webkit-animation: fa-spin 0.6s infinite linear;
            animation: fa-spin 0.6s infinite linear;
          }
          
        .drop-zone {
          border: 2px dashed #ccc;
          border-radius: 10px;
          padding: 30px;
          text-align: center;
          cursor: pointer;
          background: #f9f9f9;
          transition: border 0.3s;
        }
      
        .drop-zone.dragover {
          border-color: #007bff;
        }
      
        .preview-container {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          margin-top: 15px;
        }
      
        .preview-image {
          position: relative;
          width: 100px;
          height: 100px;
        }
      
        .preview-image img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 6px;
        }
      
        .preview-image button {
          position: absolute;
          top: -8px;
          right: -8px;
          background: red;
          border: none;
          color: white;
          border-radius: 50%;
          width: 20px;
          height: 20px;
          font-size: 12px;
          cursor: pointer;
        }
      </style>
</head>

<body class="g-sidenav-show  bg-gray-100">
    {% include 'admin/includes/part.menu.html' %}
    <main class="main-content position-relative max-height-vh-100 h-100 border-radius-lg ">
        <!-- Navbar -->
        {% include 'admin/includes/part.header.html' %}
        <!-- End Navbar -->
        <div class="container-fluid py-4">
            <div class="row g-1">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header pb-0 px-3">
                            <div class="d-flex justify-content-between">
                                <h5 class="mb-0">Add Listing</h5>
                            </div>
                        </div>
                        <div class="card-body p-3">
                            <div class="col-lg-12">
                                <div class="add-listing-form">

                                    <form action="#" method="post" enctype="multipart/form-data">
                                        {{form.csrf_token}}
                                        <h6 class="badge badge-md bg-gradient-info mb-1">Basic Information</h6>
                                        <div class="row align-items-center">

                                            <div class="col-lg-8">
                                                <div class="form-group">
                                                    {{form.title.label}}
                                                    {{form.title(class_="form-control", placeholder='Enter title')}}
                                                </div>
                                                {% for error in form.title.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.status.label}}
                                                    {{form.status(class_="form-control")}}
                                                </div>
                                                {% for error in form.status.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.condition.label}}
                                                    {{form.condition(class_="form-control")}}
                                                </div>
                                                {% for error in form.condition.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.body_type.label}}
                                                    {{form.body_type(class_="form-control")}}
                                                </div>
                                                {% for error in form.body_type.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.make.label}}
                                                    {{form.make(class_="form-control make-value")}}
                                                </div>
                                                {% for error in form.make.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form2.model.label}}
                                                    {{form2.model(class_="form-control model-value")}}
                                                </div>
                                                {% for error in form2.model.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.price.label}}
                                                    {{form.price(class_="form-control", placeholder="Enter price")}}
                                                </div>
                                                {% for error in form.price.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.year.label}}
                                                    {{form.year(class_="form-control", placeholder="Enter Year")}}
                                                </div>
                                                {% for error in form.year.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.drive_type.label}}
                                                    {{form.drive_type(class_="form-control", placeholder="Enter Year")}}
                                                </div>
                                                {% for error in form.drive_type.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.transmission.label}}
                                                    {{form.transmission(class_="form-control", placeholder="Enter
                                                    Transmission")}}
                                                </div>
                                                {% for error in form.transmission.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.fuel_type.label}}
                                                    {{form.fuel_type(class_="form-control", placeholder="Enter Fuel
                                                    Type")}}
                                                </div>
                                                {% for error in form.fuel_type.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.mileage.label}}
                                                    {{form.mileage(class_="form-control", placeholder="Enter Mileage")}}
                                                </div>
                                                {% for error in form.mileage.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.engine_size.label}}
                                                    {{form.engine_size(class_="form-control", placeholder="Enter Engine Size")}}
                                                </div>
                                                {% for error in form.engine_size.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.cylinders.label}}
                                                    {{form.cylinders(class_="form-control", placeholder="Enter
                                                    Cylinders")}}
                                                    </select>
                                                </div>
                                                {% for error in form.cylinders.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.color.label}}
                                                    {{form.color(class_="form-control", placeholder="Enter Colour")}}
                                                </div>
                                                {% for error in form.color.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.doors.label}}
                                                    {{form.doors(class_="form-control", placeholder="Enter Doors")}}

                                                </div>
                                                {% for error in form.doors.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.VIN.label}}
                                                    {{form.VIN(class_="form-control", placeholder="Enter VIN")}}

                                                </div>
                                                {% for error in form.VIN.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <div class="col-lg-12">
                                                <div class="form-group">
                                                    {{form.tags_or_keyword.label}}
                                                    {{form.tags_or_keyword(class_="form-control",
                                                    placeholder="Enter tags ex: car,red")}}

                                                </div>
                                                {% for error in form.tags_or_keyword.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <!-- <div class="col-lg-4">
                                                <div class="form-group">
                                                    {{form.youtube.label}}
                                                    {{form.youtube(class_="form-control",
                                                    placeholder="Enter youtube link")}}

                                                </div>
                                                {% for error in form.youtube.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div> -->
                                        </div>


                                        <h6 class="badge badge-md bg-gradient-info fw-bold mt-4 mb-1">Detailed
                                            Information</h6>
                                        <div class="row align-items-center">

                                            <div class="col-lg-12">
                                                <div class="form-group">
                                                    {{form.description.label}}
                                                    {{form.description(class_="form-control",
                                                    placeholder="Write description",
                                                    cols="30", rows="5")}}

                                                </div>
                                                {% for error in form.description.errors %}
                                                <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                                {% endfor %}
                                            </div>
                                            <h6 class="fw-bold my-4">Features</h6>
                                            {{form.features}}
                                            {% for error in form.features.errors %}
                                            <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                            {% endfor %}
                                        </div>
                                        <h6 class="badge badge-md bg-gradient-info fw-bold mt-4 mb-1">Upload Images
                                        </h6>
                                        <div class="col-lg-12">
                                            <div class="mb-3">
                                                <label for="image-upload" class="fw-bold form-label">Upload Images</label>
                                                <div class="drop-zone" id="drop-zone">
                                                    <span>Drag & drop images here or click to select</span>
                                                    <input type="file" id="image-upload" name="images" accept="image/*" multiple hidden>
                                                
                                                </div>
                                                <div class="preview-container" id="preview-container"></div>
                                                </div>
                
                                        </div>
                                            
                                </div>
                                <h6 class="badge badge-md bg-gradient-info fw-bold mt-4 mb-1">Contact Information</h6>
                                <div class="row align-items-center">
                                    <div class="col-12 ">
                                        <div class="form-group">
                                            {{form.staff_handler.label(class_="form-check-label", for="staff_handler")}}
                                            {{form.staff_handler(class_="form-control", id="staff_handler")}}
                                            
                                        </div>
                                        {% for error in form.staff_handler.errors %}
                                        <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                        {% endfor %}
                                    </div>
                                </div>
                                <h6 class="badge badge-md bg-gradient-info fw-bold mt-4 mb-1">Terms and Conditions</h6>
                                <div class="row align-items-center">
                                    <div class="col-12 mt-4">
                                        <div class="form-check">
                                            {{form.terms_of_services(class_="form-check-input", id="agree")}}
                                            {{form.terms_of_services.label(class_="form-check-label",
                                            for="agree")}}
                                        </div>
                                        {% for error in form.terms_of_services.errors %}
                                        <small class='text-danger text-sm text-gradient'>{{ error }}</small>
                                        {% endfor %}
                                    </div>
                                    <div class="col-lg-12 my-4">
                                        <button type="submit" class="btn float-end btn-danger"><span
                                                class="far fa-save"></span>
                                            Save & Publish Listing</button>
                                    </div>
                                </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        {% include 'admin/includes/part.footer.html' %}
        </div>
    </main>

    <!--   Core JS Files   -->
    {% include 'admin/includes/imports.bottom.html' %}
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            var elements = document.getElementById("drop-input");
            elements.oninvalid = function (e) {
                e.target.setCustomValidity("");
                if (!e.target.validity.valid) {
                    $('.dropper').addClass('border-danger');
                    $('.images-error').removeClass('visually-hidden');
                    //e.target.setCustomValidity("Image(s) Required!");
                }
            };
            elements.oninput = function (e) {
                e.target.setCustomValidity("");
            };
        })
        $('#all_checkboxes').on('change', function () {
            var all = $("#preview :checkbox");
            if (this.checked) {
                all.each(function () {
                    $(this).prop('checked', true);
                });
            }
            else {
                all.each(function () {
                    $(this).prop('checked', false);
                });
            }
        });
        $(function () {
            $(".sortable").sortable({
                stop: function(evt, ui) {
                    var allFiles = $('.image_to_upload')
                    allFiles.each(function(index, file){
                        file.name = 'image_'+index
                    })
                    
                }
            });
        });
        $('#delete_all_images').on('click', function () {
            var all = $("#preview :checkbox");
            all.each(function () {
                if ($(this).is(':checked')) {
                    var id = $(this).val()
                    Deleteimage('file_' + id, id)
                }
            })
        });
        $('.make-value').on('change', function () {
            var make_id = $(this).val()
            $('.model-value').html('');
            $('.model-value').append(new Option('Choose...', ''));
            $.ajax({
                url: "/admin/utilities/update_model/update/" + make_id,
                method: 'POST',
                success: function (data) {
                    for (var option of data) {
                        $('.model-value').append(new Option(option.name, option.id));
                    }
                }
            })
        });

        function Uploadimage(identifier, id) {

        }
        function Deleteimage(identifier, id) {
            $('.' + identifier).remove();
            removeFileFromFileList(id)
        }

        var win = navigator.platform.indexOf('Win') > -1;
        if (win && document.querySelector('#sidenav-scrollbar')) {
            var options = {
                damping: '0.5'
            }
            Scrollbar.init(document.querySelector('#sidenav-scrollbar'), options);
        }

        const dropZone = document.getElementById('drop-zone');
	const fileInput = document.getElementById('image-upload');
	const previewContainer = document.getElementById('preview-container');
	
	dropZone.addEventListener('click', () => fileInput.click());
	
	dropZone.addEventListener('dragover', (e) => {
	  e.preventDefault();
	  dropZone.classList.add('dragover');
	});
	
	dropZone.addEventListener('dragleave', () => {
	  dropZone.classList.remove('dragover');
	});
	
	dropZone.addEventListener('drop', (e) => {
	  e.preventDefault();
	  dropZone.classList.remove('dragover');
	  handleFiles(e.dataTransfer.files);
	});
	
	fileInput.addEventListener('change', () => {
	  handleFiles(fileInput.files);
	  fileInput.value = '';
	});
	
	function handleFiles(files) {
	  [...files].forEach(file => {
		if (!file.type.startsWith('image/')) return;
	
		const reader = new FileReader();
		reader.onload = e => {
		  const imgWrapper = document.createElement('div');
		  imgWrapper.className = 'preview-image';
	
		  const img = document.createElement('img');
		  img.src = e.target.result;
	
		  const removeBtn = document.createElement('button');
		  removeBtn.innerHTML = '&times;';
		  removeBtn.onclick = () => {
			previewContainer.removeChild(imgWrapper);
		  };
	
		  imgWrapper.appendChild(img);
		  imgWrapper.appendChild(removeBtn);
		  previewContainer.appendChild(imgWrapper);
	
		  // Create and append file input for actual upload
		  const hiddenInput = document.createElement('input');
		  hiddenInput.type = 'file';
		  hiddenInput.name = 'images';
		  hiddenInput.files = createFileList([file]);
		  hiddenInput.style.display = 'none';
		  imgWrapper.appendChild(hiddenInput);
	
		  // Upload immediately
		  //uploadSingleFile(file);
		};
		reader.readAsDataURL(file);
	  });
	}
	
	function uploadSingleFile(file) {
	  const formData = new FormData();
	  formData.append('images', file);
	
	  fetch('/upload', {
		method: 'POST',
		body: formData
	  })
	  .then(res => res.json())
	  .then(data => {
		console.log('Uploaded:', data);
	  })
	  .catch(err => {
		console.error('Upload failed:', err);
	  });
	}
	
	// Helper to create a FileList from a single File
	function createFileList(files) {
	  const dataTransfer = new DataTransfer();
	  files.forEach(file => dataTransfer.items.add(file));
	  return dataTransfer.files;
	}
    </script>
</body>

</html>