<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

// Check permissions
if (!$auth->hasPermission('can_create') && !$auth->hasPermission('can_edit') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission to access this page";
    header('Location: dashboard.php');
    exit;
}

$current_user = $auth->getCurrentUser();
$is_edit = isset($_GET['id']);
$property = null;

if ($is_edit) {
    $id = (int)$_GET['id'];
    $property = $db->fetchOne("SELECT * FROM properties WHERE id = ?", [$id]);
    
    if (!$property) {
        $_SESSION['error'] = "Property not found";
        header('Location: properties.php');
        exit;
    }
    
    $page_title = 'Edit Property';
} else {
    $page_title = 'Add New Property';
}

// Get categories
$categories = $db->fetchAll("SELECT * FROM categories WHERE type = 'property' AND status = 'active' ORDER BY name");

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    $errors = [];
    
    // Validate input
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $category_id = (int)$_POST['category_id'];
    $property_type = $_POST['property_type'];
    $transaction_type = $_POST['transaction_type'];
    $price = (float)$_POST['price'];
    $yearly_rent = !empty($_POST['yearly_rent']) ? (float)$_POST['yearly_rent'] : null;
    $monthly_rent = !empty($_POST['monthly_rent']) ? (float)$_POST['monthly_rent'] : null;
    $size_sqft = !empty($_POST['size_sqft']) ? (int)$_POST['size_sqft'] : null;
    $bedrooms = !empty($_POST['bedrooms']) ? (int)$_POST['bedrooms'] : null;
    $bathrooms = !empty($_POST['bathrooms']) ? (int)$_POST['bathrooms'] : null;
    $address = trim($_POST['address']);
    $city = trim($_POST['city']);
    $state = trim($_POST['state']);
    $location_area = trim($_POST['location_area']);
    $latitude = !empty($_POST['latitude']) ? (float)$_POST['latitude'] : null;
    $longitude = !empty($_POST['longitude']) ? (float)$_POST['longitude'] : null;
    $status = $_POST['status'];
    $featured = isset($_POST['featured']) ? 1 : 0;
    
    // Validate required fields
    if (empty($title)) $errors[] = "Title is required";
    if (empty($property_type)) $errors[] = "Property type is required";
    if (empty($transaction_type)) $errors[] = "Transaction type is required";
    if ($price <= 0) $errors[] = "Valid price is required";
    if (empty($address)) $errors[] = "Address is required";
    if (empty($city)) $errors[] = "City is required";
    if (empty($state)) $errors[] = "State is required";
    
    // Handle features and amenities
    $features = isset($_POST['features']) ? array_filter($_POST['features']) : [];
    $amenities = isset($_POST['amenities']) ? array_filter($_POST['amenities']) : [];
    
    // Handle image uploads
    $images = [];
    $existing_images = $is_edit ? json_decode($property['images'], true) ?? [] : [];
    
    if (!empty($_FILES['images']['name'][0])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['images']['name'][$key];
                $file_size = $_FILES['images']['size'][$key];
                $file_tmp = $_FILES['images']['tmp_name'][$key];
                $file_type = $_FILES['images']['type'][$key];
                
                // Validate file
                if (!in_array($file_type, ALLOWED_IMAGE_TYPES)) {
                    $errors[] = "Invalid image type: $file_name";
                    continue;
                }
                
                if ($file_size > MAX_FILE_SIZE) {
                    $errors[] = "File too large: $file_name";
                    continue;
                }
                
                // Generate unique filename
                $extension = pathinfo($file_name, PATHINFO_EXTENSION);
                $new_filename = 'property_' . uniqid() . '_' . time() . '.' . $extension;
                $upload_path = PROPERTY_UPLOAD_DIR . '/' . $new_filename;
                
                if (move_uploaded_file($file_tmp, $upload_path)) {
                    $images[] = 'uploads/properties/' . $new_filename;
                }
            }
        }
    }
    
    // Combine with existing images if editing
    if ($is_edit) {
        $images = array_merge($existing_images, $images);
    }
    
    if (empty($images) && !$is_edit) {
        $errors[] = "At least one property image is required";
    }
    
    if (empty($errors)) {
        try {
            $slug = Security::generateSlug($title);
            
            // Check if slug exists
            $slug_check = $db->fetchOne("SELECT id FROM properties WHERE slug = ? AND id != ?", [$slug, $id ?? 0]);
            if ($slug_check) {
                $slug .= '-' . time();
            }
            
            if ($is_edit) {
                // Update property
                $sql = "UPDATE properties SET 
                        title = ?, slug = ?, description = ?, category_id = ?,
                        property_type = ?, transaction_type = ?, price = ?,
                        yearly_rent = ?, monthly_rent = ?, size_sqft = ?,
                        bedrooms = ?, bathrooms = ?, address = ?, city = ?,
                        state = ?, location_area = ?, latitude = ?, longitude = ?,
                        features = ?, amenities = ?, images = ?, status = ?,
                        featured = ?, updated_at = NOW()
                        WHERE id = ?";
                
                $db->execute($sql, [
                    $title, $slug, $description, $category_id,
                    $property_type, $transaction_type, $price,
                    $yearly_rent, $monthly_rent, $size_sqft,
                    $bedrooms, $bathrooms, $address, $city,
                    $state, $location_area, $latitude, $longitude,
                    json_encode($features), json_encode($amenities),
                    json_encode($images), $status, $featured, $id
                ]);
                
                $_SESSION['success'] = "Property updated successfully";
            } else {
                // Insert new property
                $sql = "INSERT INTO properties (
                        title, slug, description, category_id, property_type,
                        transaction_type, price, yearly_rent, monthly_rent,
                        size_sqft, bedrooms, bathrooms, address, city, state,
                        location_area, latitude, longitude, features, amenities,
                        images, status, featured, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $db->execute($sql, [
                    $title, $slug, $description, $category_id, $property_type,
                    $transaction_type, $price, $yearly_rent, $monthly_rent,
                    $size_sqft, $bedrooms, $bathrooms, $address, $city, $state,
                    $location_area, $latitude, $longitude, json_encode($features),
                    json_encode($amenities), json_encode($images), $status,
                    $featured, $current_user['id']
                ]);
                
                $_SESSION['success'] = "Property added successfully";
            }
            
            header('Location: properties.php');
            exit;
            
        } catch (Exception $e) {
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}

include 'includes/header.php';
?>

<style>
    .image-upload-container {
        border: 3px dashed #ddd;
        border-radius: 15px;
        padding: 40px;
        text-align: center;
        cursor: pointer;
        transition: all 0.3s;
        background: #f8f9fa;
    }
    
    .image-upload-container:hover {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.05);
    }
    
    .image-upload-container.dragover {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.1);
    }
    
    .upload-icon {
        font-size: 3rem;
        color: #ddd;
        margin-bottom: 15px;
    }
    
    .image-preview-container {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 15px;
        margin-top: 20px;
    }
    
    .image-preview {
        position: relative;
        border-radius: 10px;
        overflow: hidden;
        aspect-ratio: 1;
    }
    
    .image-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .image-preview .remove-image {
        position: absolute;
        top: 5px;
        right: 5px;
        background: rgba(255, 0, 0, 0.8);
        color: white;
        border: none;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    
    .feature-checkbox {
        display: flex;
        align-items: center;
        padding: 10px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: all 0.3s;
    }
    
    .feature-checkbox:hover {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.05);
    }
    
    .feature-checkbox input:checked + label {
        color: var(--primary);
        font-weight: 600;
    }
</style>

<div class="page-header">
    <h1><?php echo $page_title; ?></h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item"><a href="properties.php">Properties</a></li>
            <li class="breadcrumb-item active"><?php echo $is_edit ? 'Edit' : 'Add New'; ?></li>
        </ol>
    </nav>
</div>

<?php if (!empty($errors)): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <i class="fas fa-exclamation-circle"></i>
    <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
    </ul>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data" data-validate="true">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
    
    <div class="row">
        <div class="col-lg-8">
            <!-- Basic Information -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Basic Information</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Property Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control" required
                               value="<?php echo htmlspecialchars($property['title'] ?? ''); ?>"
                               placeholder="e.g., Luxury 3 Bedroom Apartment">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="5"
                                  placeholder="Describe the property..."><?php echo htmlspecialchars($property['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Category</label>
                            <select name="category_id" class="form-select">
                                <option value="">Select Category</option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"
                                        <?php echo ($property['category_id'] ?? '') == $cat['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Property Type <span class="text-danger">*</span></label>
                            <select name="property_type" class="form-select" required>
                                <option value="">Select Type</option>
                                <option value="house" <?php echo ($property['property_type'] ?? '') === 'house' ? 'selected' : ''; ?>>House</option>
                                <option value="apartment" <?php echo ($property['property_type'] ?? '') === 'apartment' ? 'selected' : ''; ?>>Apartment</option>
                                <option value="villa" <?php echo ($property['property_type'] ?? '') === 'villa' ? 'selected' : ''; ?>>Villa</option>
                                <option value="duplex" <?php echo ($property['property_type'] ?? '') === 'duplex' ? 'selected' : ''; ?>>Duplex</option>
                                <option value="bungalow" <?php echo ($property['property_type'] ?? '') === 'bungalow' ? 'selected' : ''; ?>>Bungalow</option>
                                <option value="commercial" <?php echo ($property['property_type'] ?? '') === 'commercial' ? 'selected' : ''; ?>>Commercial</option>
                                <option value="other" <?php echo ($property['property_type'] ?? '') === 'other' ? 'selected' : ''; ?>>Other</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Transaction Type <span class="text-danger">*</span></label>
                            <select name="transaction_type" class="form-select" required id="transactionType">
                                <option value="">Select Transaction</option>
                                <option value="sale" <?php echo ($property['transaction_type'] ?? '') === 'sale' ? 'selected' : ''; ?>>For Sale</option>
                                <option value="rent" <?php echo ($property['transaction_type'] ?? '') === 'rent' ? 'selected' : ''; ?>>For Rent</option>
                                <option value="lease" <?php echo ($property['transaction_type'] ?? '') === 'lease' ? 'selected' : ''; ?>>For Lease</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Price (₦) <span class="text-danger">*</span></label>
                            <input type="number" name="price" class="form-control" required min="0" step="0.01"
                                   value="<?php echo $property['price'] ?? ''; ?>"
                                   placeholder="0.00">
                        </div>
                    </div>
                    
                    <div class="row" id="rentFields" style="display: none;">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Yearly Rent (₦)</label>
                            <input type="number" name="yearly_rent" class="form-control" min="0" step="0.01"
                                   value="<?php echo $property['yearly_rent'] ?? ''; ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Monthly Rent (₦)</label>
                            <input type="number" name="monthly_rent" class="form-control" min="0" step="0.01"
                                   value="<?php echo $property['monthly_rent'] ?? ''; ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Property Details -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Property Details</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Size (Sqft)</label>
                            <input type="number" name="size_sqft" class="form-control" min="0"
                                   value="<?php echo $property['size_sqft'] ?? ''; ?>">
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Bedrooms</label>
                            <input type="number" name="bedrooms" class="form-control" min="0"
                                   value="<?php echo $property['bedrooms'] ?? ''; ?>">
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Bathrooms</label>
                            <input type="number" name="bathrooms" class="form-control" min="0"
                                   value="<?php echo $property['bathrooms'] ?? ''; ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Location -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Location Details</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Address <span class="text-danger">*</span></label>
                        <input type="text" name="address" class="form-control" required
                               value="<?php echo htmlspecialchars($property['address'] ?? ''); ?>"
                               placeholder="Full street address">
                    </div>
                    
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">City <span class="text-danger">*</span></label>
                            <input type="text" name="city" class="form-control" required
                                   value="<?php echo htmlspecialchars($property['city'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">State <span class="text-danger">*</span></label>
                            <input type="text" name="state" class="form-control" required
                                   value="<?php echo htmlspecialchars($property['state'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Area/Estate</label>
                            <input type="text" name="location_area" class="form-control"
                                   value="<?php echo htmlspecialchars($property['location_area'] ?? ''); ?>">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Latitude</label>
                            <input type="text" name="latitude" class="form-control"
                                   value="<?php echo $property['latitude'] ?? ''; ?>"
                                   placeholder="e.g., 4.8156">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Longitude</label>
                            <input type="text" name="longitude" class="form-control"
                                   value="<?php echo $property['longitude'] ?? ''; ?>"
                                   placeholder="e.g., 7.0498">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Property Images -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Property Images</h5>
                </div>
                <div class="card-body">
                    <div class="image-upload-container" id="imageUploadArea">
                        <i class="fas fa-cloud-upload-alt upload-icon"></i>
                        <h5>Drag and drop your images here</h5>
                        <p class="text-muted">or click to browse</p>
                        <input type="file" name="images[]" id="imageInput" multiple accept="image/*" style="display: none;">
                    </div>
                    
                    <div class="image-preview-container" id="imagePreview">
                        <?php if ($is_edit && !empty($property['images'])): ?>
                            <?php foreach (json_decode($property['images'], true) as $image): ?>
                            <div class="image-preview">
                                <img src="../<?php echo htmlspecialchars($image); ?>" alt="Property">
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- Publish -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Publish</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="available" <?php echo ($property['status'] ?? 'available') === 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="pending" <?php echo ($property['status'] ?? '') === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="sold" <?php echo ($property['status'] ?? '') === 'sold' ? 'selected' : ''; ?>>Sold</option>
                            <option value="rented" <?php echo ($property['status'] ?? '') === 'rented' ? 'selected' : ''; ?>>Rented</option>
                            <option value="inactive" <?php echo ($property['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="featured" id="featured"
                               <?php echo ($property['featured'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="featured">
                            Featured Property
                        </label>
                    </div>
                    
                    <button type="submit" name="submit" class="btn btn-primary w-100">
                        <i class="fas fa-save"></i> <?php echo $is_edit ? 'Update' : 'Publish'; ?> Property
                    </button>
                    
                    <a href="properties.php" class="btn btn-outline-secondary w-100 mt-2">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                </div>
            </div>
            
            <!-- Features -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Features</h5>
                </div>
                <div class="card-body">
                    <?php 
                    $all_features = ['Parking', 'Swimming Pool', 'Garden', 'Security', 'Elevator', 'Balcony', 'Gym', 'WiFi'];
                    $selected_features = $is_edit ? json_decode($property['features'], true) ?? [] : [];
                    
                    foreach ($all_features as $feature): ?>
                    <div class="feature-checkbox">
                        <input class="form-check-input me-2" type="checkbox" name="features[]" 
                               value="<?php echo $feature; ?>" id="feature_<?php echo str_replace(' ', '_', $feature); ?>"
                               <?php echo in_array($feature, $selected_features) ? 'checked' : ''; ?>>
                        <label class="form-check-label flex-grow-1" for="feature_<?php echo str_replace(' ', '_', $feature); ?>">
                            <?php echo $feature; ?>
                        </label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <!-- Amenities -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Amenities</h5>
                </div>
                <div class="card-body">
                    <?php 
                    $all_amenities = ['Air Conditioning', 'Heating', 'Laundry', 'Furnished', 'Pet Friendly', 'Fireplace'];
                    $selected_amenities = $is_edit ? json_decode($property['amenities'], true) ?? [] : [];
                    
                    foreach ($all_amenities as $amenity): ?>
                    <div class="feature-checkbox">
                        <input class="form-check-input me-2" type="checkbox" name="amenities[]" 
                               value="<?php echo $amenity; ?>" id="amenity_<?php echo str_replace(' ', '_', $amenity); ?>"
                               <?php echo in_array($amenity, $selected_amenities) ? 'checked' : ''; ?>>
                        <label class="form-check-label flex-grow-1" for="amenity_<?php echo str_replace(' ', '_', $amenity); ?>">
                            <?php echo $amenity; ?>
                        </label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</form>

<script>

    Swal.fire({
  title: "Good job!",
  text: "You clicked the button!",
  icon: "success"
});

$(document).ready(function() {
    // Show/hide rent fields based on transaction type
    function toggleRentFields() {
        const transactionType = $('#transactionType').val();
        if (transactionType === 'rent' || transactionType === 'lease') {
            $('#rentFields').show();
        } else {
            $('#rentFields').hide();
        }
    }
    
    $('#transactionType').change(toggleRentFields);
    toggleRentFields(); // Call on page load
    
    // Image upload handling - FIXED VERSION
    const uploadArea = document.getElementById('imageUploadArea');
    const imageInput = document.getElementById('imageInput');
    const imagePreview = document.getElementById('imagePreview');
    let uploadedFiles = [];
    
    // Click to upload
    uploadArea.addEventListener('click', function(e) {
        if (!e.target.classList.contains('remove-image') && 
            !e.target.closest('.remove-image')) {
            imageInput.click();
        }
    });
    
    // Prevent default drag behaviors
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, preventDefaults, false);
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    // Highlight drop area when item is dragged over it
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, highlight, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, unhighlight, false);
    });
    
    function highlight(e) {
        uploadArea.classList.add('dragover');
    }
    
    function unhighlight(e) {
        uploadArea.classList.remove('dragover');
    }
    
    // Handle dropped files
    uploadArea.addEventListener('drop', handleDrop, false);
    
    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }
    
    // Handle file input change
    imageInput.addEventListener('change', function() {
        const files = this.files;
        handleFiles(files);
    });
    
    function handleFiles(files) {
        // Convert FileList to Array
        const filesArray = Array.from(files);
        
        filesArray.forEach(file => {
            if (!file.type.startsWith('image/')) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid File',
                    text: 'Please upload only image files'
                });
                return;
            }
            
            if (file.size > 5242880) { // 5MB
                Swal.fire({
                    icon: 'error',
                    title: 'File Too Large',
                    text: 'File size must be less than 5MB'
                });
                return;
            }
            
            uploadedFiles.push(file);
            previewFile(file);
        });
        
        // Update the file input
        updateFileInput();
    }
    
    function previewFile(file) {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = function() {
            const index = uploadedFiles.indexOf(file);
            const preview = document.createElement('div');
            preview.className = 'image-preview';
            preview.innerHTML = `
                <img src="${reader.result}" alt="Preview">
                <button type="button" class="remove-image" data-index="${index}">
                    <i class="fas fa-times"></i>
                </button>
            `;
            
            imagePreview.appendChild(preview);
            
            // Add remove handler
            preview.querySelector('.remove-image').addEventListener('click', function(e) {
                e.stopPropagation();
                const idx = parseInt(this.dataset.index);
                uploadedFiles.splice(idx, 1);
                preview.remove();
                updateFileInput();
                
                // Update all remaining indices
                document.querySelectorAll('.remove-image').forEach((btn, i) => {
                    btn.dataset.index = i;
                });
            });
        };
    }
    
    function updateFileInput() {
        if (uploadedFiles.length > 0) {
            const dataTransfer = new DataTransfer();
            uploadedFiles.forEach(file => {
                dataTransfer.items.add(file);
            });
            imageInput.files = dataTransfer.files;
        }
    }
});





    // $(document).ready(function() {
    //     // Show/hide rent fields based on transaction type
    //     function toggleRentFields() {
    //         const transactionType = $('#transactionType').val();
    //         if (transactionType === 'rent' || transactionType === 'lease') {
    //             $('#rentFields').show();
    //         } else {
    //             $('#rentFields').hide();
    //         }
    //     }
        
    //     $('#transactionType').change(toggleRentFields);
    //     toggleRentFields(); // Call on page load
        
    //     // Image upload handling
    //     const uploadArea = $('#imageUploadArea');
    //     const imageInput = $('#imageInput');
    //     const imagePreview = $('#imagePreview');
        
    //     uploadArea.click(function() {
    //         imageInput.click();
    //     });
        
    //     // Drag and drop
    //     uploadArea.on('dragover', function(e) {
    //         e.preventDefault();
    //         $(this).addClass('dragover');
    //     });
        
    //     uploadArea.on('dragleave', function(e) {
    //         e.preventDefault();
    //         $(this).removeClass('dragover');
    //     });
        
    //     uploadArea.on('drop', function(e) {
    //         e.preventDefault();
    //         $(this).removeClass('dragover');
            
    //         const files = e.originalEvent.dataTransfer.files;
    //         handleFiles(files);
    //     });
        
    //     imageInput.change(function() {
    //         const files = this.files;
    //         handleFiles(files);
    //     });
        
    //     function handleFiles(files) {
    //         for (let i = 0; i < files.length; i++) {
    //             const file = files[i];
                
    //             if (!file.type.startsWith('image/')) continue;
                
    //             const reader = new FileReader();
    //             reader.onload = function(e) {
    //                 const preview = $(`
    //                     <div class="image-preview">
    //                         <img src="${e.target.result}" alt="Preview">
    //                         <button type="button" class="remove-image">
    //                             <i class="fas fa-times"></i>
    //                         </button>
    //                     </div>
    //                 `);
                    
    //                 imagePreview.append(preview);
                    
    //                 preview.find('.remove-image').click(function() {
    //                     $(this).parent().remove();
    //                 });
    //             };
    //             reader.readAsDataURL(file);
    //         }
    //     }
    // });
</script>

<?php include 'includes/footer.php'; ?>