<?php
// Start session and check if user is logged in
session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}

// Include config file
require_once 'includes/config.php';

// Initialize variables
$error = '';
$success = '';
$uploaded_files = [];

// Check if categories exist, if not create a default one
$check_categories = $conn->query("SELECT COUNT(*) as count FROM gallery_categories");
$has_categories = $check_categories && $check_categories->fetch_assoc()['count'] > 0;

if (!$has_categories) {
    // Create default category
    $default_category = [
        'name' => 'Properties',
        'description' => 'Default category for property images',
        'type' => 'property'
    ];
    
    $stmt = $conn->prepare("INSERT INTO gallery_categories (name, description, type) VALUES (?, ?, ?)");
    if ($stmt) {
        $stmt->bind_param("sss", 
            $default_category['name'],
            $default_category['description'],
            $default_category['type']
        );
        $stmt->execute();
        $stmt->close();
    }
}

// Initialize arrays
$propertyTypes = [];
$galleryCategories = [];
$categoryTypes = [
    'property' => 'Property Types',
    'gallery' => 'Gallery Categories'
];

try {
    // Fetch property types
    $property_sql = "SELECT id, name FROM property_types ORDER BY name";
    $property_result = $conn->query($property_sql);
    if ($property_result) {
        $propertyTypes = $property_result->fetch_all(MYSQLI_ASSOC);
    }
    
    // Fetch gallery categories with their types
    $category_sql = "SELECT id, name, IFNULL(type, 'other') as type FROM gallery_categories ORDER BY type, name";
    $category_result = $conn->query($category_sql);
    if ($category_result) {
        $galleryCategories = $category_result->fetch_all(MYSQLI_ASSOC);
        
        // Get unique category types for the filter
        foreach ($galleryCategories as $category) {
            if (!empty($category['type']) && !isset($categoryTypes[$category['type']])) {
                $categoryTypes[$category['type']] = ucfirst(str_replace('_', ' ', $category['type']));
            }
        }
    }
    
} catch (Exception $e) {
    $error = "Error fetching categories: " . $e->getMessage();
}

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["images"])) {
    $category_id = $_POST['category_id'] ?? null;
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $upload_dir = '../images/gallery/';
    
    // Create upload directory if it doesn't exist
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $uploaded_files = [];
    $errors = [];
    
    // Process each uploaded file
    foreach ($_FILES['images']['tmp_name'] as $key => $tmp_name) {
        $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 type
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        if (!in_array($file_type, $allowed_types)) {
            $errors[] = "File type not allowed: $file_name";
            continue;
        }
        
        // Validate file size (max 10MB)
        $max_size = 10 * 1024 * 1024; // 10MB
        if ($file_size > $max_size) {
            $errors[] = "File too large (max 10MB): $file_name";
            continue;
        }
        
        // Generate unique filename
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $new_filename = uniqid('img_') . '.' . $file_ext;
        $destination = $upload_dir . $new_filename;
        
        // Move uploaded file
        if (move_uploaded_file($file_tmp, $destination)) {
            $uploaded_files[] = [
                'filename' => $new_filename,
                'original_name' => $file_name
            ];
            
            // Insert into database
            try {
                // Check if it's a property type or gallery category
                if (strpos($category_id, 'prop_') === 0) {
                    // It's a property type
                    $prop_id = (int) str_replace('prop_', '', $category_id);
                    $check_property = $conn->prepare("SELECT id FROM property_types WHERE id = ?");
                    $check_property->bind_param("i", $prop_id);
                    $check_property->execute();
                    $property_exists = $check_property->get_result()->num_rows > 0;
                    $check_property->close();
                    
                    if (!$property_exists) {
                        throw new Exception("Selected property type does not exist");
                    }
                    
                    // Store the property type ID in the category_id field for reference
                    $category_id = $prop_id;
                    $is_property_type = true;
                } else if (strpos($category_id, 'cat_') === 0) {
                    // It's a gallery category
                    $cat_id = (int) str_replace('cat_', '', $category_id);
                    $check_category = $conn->prepare("SELECT id FROM gallery_categories WHERE id = ?");
                    $check_category->bind_param("i", $cat_id);
                    $check_category->execute();
                    $category_exists = $check_category->get_result()->num_rows > 0;
                    $check_category->close();
                    
                    if (!$category_exists) {
                        throw new Exception("Selected category does not exist");
                    }
                    
                    $category_id = $cat_id;
                    $is_property_type = false;
                } else {
                    throw new Exception("Invalid category selection");
                }
                
                // Store the relative path from the root of the website
                $relative_path = 'images/gallery/' . $new_filename;
                
                // Determine the table to insert into based on category type
                if ($is_property_type) {
                    $table_name = 'property_images';
                    $id_column = 'property_type_id';
                    
                    // Create property_images table if it doesn't exist
                    $create_table_sql = "CREATE TABLE IF NOT EXISTS `property_images` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `property_type_id` int(11) NOT NULL,
                        `image_path` varchar(255) NOT NULL,
                        `title` varchar(255) DEFAULT NULL,
                        `description` text DEFAULT NULL,
                        `created_at` datetime DEFAULT current_timestamp(),
                        PRIMARY KEY (`id`),
                        KEY `property_type_id` (`property_type_id`),
                        CONSTRAINT `fk_property_images_type` FOREIGN KEY (`property_type_id`) REFERENCES `property_types` (`id`) ON DELETE CASCADE
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
                    
                    $conn->query($create_table_sql);
                } else {
                    $table_name = 'gallery_images';
                    $id_column = 'category_id';
                }
                
                $sql = "INSERT INTO $table_name ($id_column, title, description, image_path, created_at) 
                        VALUES (?, ?, ?, ?, NOW())";
                        
                $stmt = $conn->prepare($sql);
                if ($stmt === false) {
                    throw new Exception("Failed to prepare statement: " . $conn->error);
                }
                
                $image_title = !empty($title) ? $title : pathinfo($file_name, PATHINFO_FILENAME);
                
                // Log the values being bound for debugging
                error_log("Binding values - Category ID: $category_id, Title: $image_title, Description: $description, Filename: $relative_path");
                
                $bind_result = $stmt->bind_param("isss", $category_id, $image_title, $description, $relative_path);
                
                if ($bind_result === false) {
                    throw new Exception("Failed to bind parameters: " . ($stmt->error ?? 'Unknown error'));
                }
                
                $execute_result = $stmt->execute();
                if ($execute_result === false) {
                    throw new Exception("Failed to execute query: " . $stmt->error);
                }
                
                $stmt->close();
            } catch (Exception $e) {
                $error_message = $e->getMessage();
                $errors[] = "Error saving to database: $error_message";
                error_log("Image upload error: $error_message");
                
                // Remove the uploaded file if database insert failed
                if (file_exists($destination)) {
                    unlink($destination);
                }
                
                // Log additional debug info
                $debug_title = $image_title ?? 'Not set';
                error_log("Category ID: " . ($category_id ?? 'Not set') . ", Title: $debug_title, Description: " . ($description ?? 'Not set'));
            }
        } else {
            $errors[] = "Failed to upload: $file_name";
        }
    }
    
    // Set success/error messages
    if (!empty($uploaded_files)) {
        $count = count($uploaded_files);
        $success = "Successfully uploaded $count file(s).";
    }
    if (!empty($errors)) {
        $error = implode("<br>", $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Images - Gallery Management</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Custom styles -->
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --dark-color: #1a1a2e;
            --light-color: #f8f9fa;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
        }

        body {
            background-color: #f5f7fb;
            color: #4a4a4a;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .sidebar {
            background: linear-gradient(180deg, var(--dark-color) 0%, #16213e 100%);
            min-height: 100vh;
            color: white;
            transition: all 0.3s;
        }

        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 0.5rem 1rem;
            margin: 0.2rem 0;
            border-radius: 0.25rem;
            transition: all 0.3s;
        }

        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background-color: rgba(255, 255, 255, 0.1);
            color: white;
        }

        .sidebar .nav-link i {
            width: 24px;
            text-align: center;
            margin-right: 8px;
        }

        .main-content {
            padding: 2rem 0;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e0e0e0;
        }

        .page-title {
            color: var(--dark-color);
            font-weight: 600;
            margin: 0;
        }

        .form-container {
            background: white;
            border-radius: 0.5rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            padding: 2rem;
            margin-bottom: 2rem;
        }

        .form-label {
            font-weight: 500;
            color: #495057;
        }

        .form-control, .form-select {
            border-radius: 0.375rem;
            padding: 0.5rem 1rem;
            border: 1px solid #ced4da;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 0.5rem 1.5rem;
            border-radius: 0.375rem;
            font-weight: 500;
            transition: all 0.3s;
        }

        .btn-primary:hover {
            background-color: var(--secondary-color);
            transform: translateY(-1px);
        }

        .btn-outline-secondary {
            border-color: #dee2e6;
        }

        .btn-outline-secondary:hover {
            background-color: #f8f9fa;
            border-color: #dee2e6;
        }

        .alert {
            border-radius: 0.375rem;
            border: none;
        }

        .alert-success {
            background-color: rgba(76, 201, 240, 0.1);
            color: #0d6efd;
            border-left: 4px solid var(--success-color);
        }

        .alert-danger {
            background-color: rgba(247, 37, 133, 0.1);
            color: #dc3545;
            border-left: 4px solid var(--danger-color);
        }

        #file-preview {
            margin-top: 1.5rem;
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 1rem;
        }
        .preview-item {
            position: relative;
            border: 1px solid #dee2e6;
            border-radius: 0.5rem;
            padding: 0.75rem;
            background: #fff;
            transition: all 0.2s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .preview-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .preview-item img {
            width: 100%;
            height: 120px;
            object-fit: cover;
            border-radius: 0.25rem;
            margin-bottom: 0.5rem;
        }
        .preview-info {
            padding: 0.25rem 0;
        }
        .preview-name {
            font-weight: 500;
            font-size: 0.85rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .preview-size {
            font-size: 0.75rem;
            color: #6c757d;
        }
        .remove-file {
            position: absolute;
            top: 5px;
            right: 5px;
            width: 24px;
            height: 24px;
            background: rgba(255, 0, 0, 0.8);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.2s;
        }
        .preview-item:hover .remove-file {
            opacity: 1;
        }
        .upload-status {
            margin-top: 1rem;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 0.5rem;
            display: none;
        }
        .upload-status.show {
            display: block;
        }
        .upload-count {
            font-size: 0.9rem;
            color: #495057;
            font-weight: 500;
        }
        .file-upload-container {
            border: 2px dashed #ced4da;
            border-radius: 0.5rem;
            padding: 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background-color: #f8f9fa;
            margin-bottom: 1.5rem;
        }
        .file-upload-container:hover {
            border-color: var(--primary-color);
            background-color: rgba(67, 97, 238, 0.05);
        }
        .file-upload-container i {
            font-size: 2.5rem;
            color: #6c757d;
            margin-bottom: 1rem;
            display: block;
        }
        .file-upload-container p {
            margin-bottom: 0.5rem;
            color: #6c757d;
        }
        .file-upload-container small {
            color: #adb5bd;
            font-size: 0.875rem;
        }
        #file-input {
            display: none;
        }

        @media (max-width: 768px) {
            .sidebar {
                min-height: auto;
                width: 100%;
            }
            
            .main-content {
                padding: 1rem;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0 sidebar d-md-block">
                <div class="d-flex flex-column flex-shrink-0 p-3 h-100">
                    <a href="index.php" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none">
                        <span class="fs-4">Admin Panel</span>
                    </a>
                    <hr>
                    <ul class="nav nav-pills flex-column mb-auto">
                        <li class="nav-item">
                            <a href="index.php" class="nav-link">
                                <i class="fas fa-tachometer-alt"></i>
                                Dashboard
                            </a>
                        </li>
                        <li>
                            <a href="gallery.php" class="nav-link active">
                                <i class="fas fa-images"></i>
                                Gallery
                            </a>
                        </li>
                        <li>
                            <a href="categories.php" class="nav-link">
                                <i class="fas fa-tags"></i>
                                Categories
                            </a>
                        </li>
                        <li>
                            <a href="#" class="nav-link">
                                <i class="fas fa-envelope"></i>
                                Messages
                            </a>
                        </li>
                    </ul>
                    <hr>
                    <div class="dropdown">
                        <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" id="dropdownUser1" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-user-circle me-2" style="font-size: 1.5rem;"></i>
                            <strong><?php echo htmlspecialchars($_SESSION["username"] ?? 'Admin'); ?></strong>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-dark text-small shadow" aria-labelledby="dropdownUser1">
                            <li><a class="dropdown-item" href="#">Profile</a></li>
                            <li><a class="dropdown-item" href="#">Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php">Sign out</a></li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 main-content">
                <!-- Page Header -->
                <div class="page-header">
                    <h1 class="page-title">Upload Images</h1>
                    <a href="gallery.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i> Back to Gallery
                    </a>
                </div>

                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if (!empty($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <div class="form-container">
                    <form action="" method="post" enctype="multipart/form-data" id="upload-form">
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <label for="category_type" class="form-label">Category Type</label>
                                <select class="form-select" id="category_type" name="category_type">
                                    <option value="">All Types</option>
                                    <?php foreach ($categoryTypes as $type => $label): ?>
                                        <option value="<?php echo htmlspecialchars($type); ?>">
                                            <?php echo htmlspecialchars($label); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                
                                <div class="mt-3">
                                    <label for="title" class="form-label">Title</label>
                                    <input type="text" class="form-control" id="title" name="title" 
                                           placeholder="Enter a title for these images">
                                    <div class="form-text">Leave blank to use the original filename as the title.</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <select class="form-select" id="category_id" name="category_id" required>
                                    <option value="">-- Select a category --</option>
                                    <?php if (!empty($propertyTypes)): ?>
                                        <optgroup label="Property Types">
                                            <?php foreach ($propertyTypes as $type): ?>
                                                <option value="prop_<?php echo $type['id']; ?>" data-type="property">
                                                    <?php echo htmlspecialchars($type['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($galleryCategories)): ?>
                                        <?php 
                                        $categoriesByType = [];
                                        foreach ($galleryCategories as $cat) {
                                            $categoriesByType[$cat['type']][] = $cat;
                                        }
                                        ?>
                                        <?php foreach ($categoriesByType as $type => $cats): ?>
                                            <optgroup label="<?php echo ucfirst(str_replace('_', ' ', $type)); ?> Categories" data-category-type="<?php echo htmlspecialchars($type); ?>">
                                                <?php foreach ($cats as $cat): ?>
                                                    <option value="cat_<?php echo $cat['id']; ?>" data-type="gallery" data-category-type="<?php echo htmlspecialchars($cat['type']); ?>">
                                                        <?php echo htmlspecialchars($cat['name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                                
                                <div class="mt-3">
                                    <label for="description" class="form-label">Description</label>
                                    <textarea class="form-control" id="description" name="description" 
                                             rows="3" placeholder="Enter a description (optional)"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Images <span class="text-danger">*</span></label>
                            <div class="file-upload-container" id="drop-zone">
                                <div class="upload-content text-center p-4">
                                    <i class="fas fa-cloud-upload-alt mb-3" style="font-size: 3rem; color: #4361ee;"></i>
                                    <h5 class="mb-2">Drag & drop images here</h5>
                                    <p class="text-muted mb-3">or</p>
                                    <button type="button" class="btn btn-primary" id="browse-btn">
                                        <i class="fas fa-folder-open me-2"></i>Browse Files
                                    </button>
                                    <input type="file" id="file-input" name="images[]" multiple accept="image/jpeg,image/png,image/gif,image/webp" style="display: none;">
                                    <div class="mt-3">
                                        <small class="text-muted">Supports JPG, PNG, GIF, WebP (Max 10MB per image)</small>
                                    </div>
                                </div>
                                <div class="upload-status d-none">
                                    <div class="progress mb-3">
                                        <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
                                    </div>
                                    <div class="upload-count text-center">
                                        <span id="selected-count">0</span> files selected
                                    </div>
                                </div>
                            </div>
                            
                            <div id="file-preview" class="preview-container">
                                <!-- Preview items will be added here -->
                            </div>
                        </div>

                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="reset" class="btn btn-outline-secondary me-md-2">
                                <i class="fas fa-undo me-1"></i> Reset
                            </button>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-upload me-1"></i> Upload Images
                            </button>
                        </div>
                    </form>
                </div>
            </main>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const dropZone = document.getElementById('drop-zone');
            const fileInput = document.getElementById('file-input');
            const browseBtn = document.getElementById('browse-btn');
            const previewContainer = document.getElementById('file-preview');
            const form = document.getElementById('upload-form');
            
            // Prevent default drag behaviors
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, preventDefaults, false);
                document.body.addEventListener(eventName, preventDefaults, false);
            });

            // Highlight drop zone when item is dragged over it
            ['dragenter', 'dragover'].forEach(eventName => {
                dropZone.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, unhighlight, false);
            });

            // Handle dropped files
            dropZone.addEventListener('drop', handleDrop, false);
            
            // Open file dialog when browse button is clicked
            browseBtn.addEventListener('click', () => {
                fileInput.click();
            });
            
            // Handle file selection via file input
            fileInput.addEventListener('change', function(e) {
                if (this.files.length > 0) {
                    processFiles(this.files);
                }
            });
            
            // Prevent form submission if no files are selected
            form.addEventListener('submit', function(e) {
                if (fileInput.files.length === 0) {
                    e.preventDefault();
                    showAlert('Please select at least one image to upload.', 'danger');
                    return false;
                }
                
                // Show loading state on submit button
                const submitBtn = form.querySelector('button[type="submit"]');
                const originalBtnText = submitBtn.innerHTML;
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Uploading...';
                
                // Re-enable the button after form submission (in case of validation error)
                setTimeout(() => {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalBtnText;
                }, 5000);
            });
            
            // Show alert message
            function showAlert(message, type = 'info') {
                // Remove any existing alerts
                const existingAlert = document.querySelector('.alert-dismissible');
                if (existingAlert) {
                    existingAlert.remove();
                }
                
                const alertDiv = document.createElement('div');
                alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
                alertDiv.role = 'alert';
                alertDiv.innerHTML = `
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                `;
                
                // Insert after the page header
                const pageHeader = document.querySelector('.page-header');
                if (pageHeader) {
                    pageHeader.insertAdjacentElement('afterend', alertDiv);
                } else {
                    document.querySelector('.form-container').prepend(alertDiv);
                }
                
                // Auto-dismiss after 5 seconds
                setTimeout(() => {
                    const alert = new bootstrap.Alert(alertDiv);
                    alert.close();
                }, 5000);
            }
            
            // Remove file from selection
            function removeFile(index) {
                const dt = new DataTransfer();
                const { files } = fileInput;
                
                for (let i = 0; i < files.length; i++) {
                    if (index !== i) {
                        dt.items.add(files[i]);
                    }
                }
                
                fileInput.files = dt.files;
                
                // Update preview and count
                if (fileInput.files.length > 0) {
                    updatePreviews(Array.from(fileInput.files));
                    document.getElementById('selected-count').textContent = fileInput.files.length;
                } else {
                    previewContainer.innerHTML = '';
                    document.querySelector('.upload-status').classList.remove('show');
                }
            }

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            function highlight() {
                dropZone.style.borderColor = '#4361ee';
                dropZone.style.backgroundColor = 'rgba(67, 97, 238, 0.05)';
            }

            function unhighlight() {
                dropZone.style.borderColor = '#ced4da';
                dropZone.style.backgroundColor = '#f8f9fa';
            }
            
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                handleFiles(files);
            }
            
            function handleFiles(files) {
                // Clear previous previews
                previewContainer.innerHTML = '';
                
                // Convert FileList to array and process each file
                Array.from(files).forEach(file => {
                    // Check file type
                    if (!file.type.match('image.*')) {
                        alert(`Skipping ${file.name}: Not an image file`);
                        return;
                    }
                    
                    // Check file size (10MB max)
                    const maxSize = 10 * 1024 * 1024; // 10MB
                    if (file.size > maxSize) {
                        alert(`Skipping ${file.name}: File is too large (max 10MB)`);
                        return;
                    }
                    
                    // Create preview
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const preview = document.createElement('div');
                        preview.className = 'preview-item';
                        preview.innerHTML = `
                            <div class="position-relative">
                                <img src="${e.target.result}" alt="${file.name}" class="img-fluid rounded">
                                <div class="remove-file" data-index="${Array.from(files).indexOf(file)}">
                                    <i class="fas fa-times"></i>
                                </div>
                            </div>
                            <div class="preview-info">
                                <div class="preview-name" title="${file.name}">${file.name}</div>
                                <div class="preview-size">${formatFileSize(file.size)} • ${file.type.split('/')[1].toUpperCase()}</div>
                            </div>
                        `;
                        previewContainer.appendChild(preview);
                    };
                    reader.readAsDataURL(file);
                });
                
                // Update file input
                fileInput.files = files;
            }
            
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            // Handle dropped files
            function handleDrop(e) {
                e.preventDefault();
                unhighlight();
                const files = e.dataTransfer.files;
                processFiles(files);
            }

            // Process selected files
            function processFiles(files) {
                if (!files || files.length === 0) return;
                
                // Filter out non-image files
                const imageFiles = Array.from(files).filter(file => 
                    file.type.match('image/(jpeg|png|gif|webp)')
                );
                
                if (imageFiles.length === 0) {
                    showAlert('Please upload only image files (JPG, PNG, GIF, WebP)', 'danger');
                    return;
                }
                
                // Check file sizes
                const maxSize = 10 * 1024 * 1024; // 10MB
                const oversizedFiles = imageFiles.filter(file => file.size > maxSize);
                if (oversizedFiles.length > 0) {
                    showAlert(`Skipped ${oversizedFiles.length} file(s) that exceed 10MB limit`, 'warning');
                }
                
                // Only keep files under size limit
                const validFiles = imageFiles.filter(file => file.size <= 10 * 1024 * 1024);
                
                if (validFiles.length === 0) return;
                
                // Update file input with valid files
                const dataTransfer = new DataTransfer();
                validFiles.forEach(file => dataTransfer.items.add(file));
                fileInput.files = dataTransfer.files;
                
                // Show upload status
                document.querySelector('.upload-status').classList.add('show');
                document.getElementById('selected-count').textContent = validFiles.length;
                
                // Update previews
                updatePreviews(validFiles);
            }
            
            // Update file previews
            function updatePreviews(files) {
                // Clear previous previews but keep the container
                previewContainer.innerHTML = '';
                
                files.forEach((file, index) => {
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                // Handle category type filter
            const categoryTypeSelect = document.getElementById('category_type');
            const categorySelect = document.getElementById('category_id');
            
            if (categoryTypeSelect && categorySelect) {
                // Function to filter categories based on selected type
                const filterCategories = (selectedType) => {
                    const options = categorySelect.querySelectorAll('option');
                    
                    // Show all options first
                    options.forEach(opt => {
                        if (opt.value) { // Skip the first empty option
                            opt.style.display = '';
                        }
                    });
                    
                    // If a type is selected, hide non-matching options
                    if (selectedType) {
                        options.forEach(opt => {
                            if (opt.value) { // Skip the first empty option
                                const dataType = opt.getAttribute('data-type');
                                const categoryType = opt.getAttribute('data-category-type');
                                
                                if (selectedType === 'property') {
                                    // Show only property types
                                    opt.style.display = (dataType === 'property') ? '' : 'none';
                                } else {
                                    // Show only gallery categories of the selected type
                                    opt.style.display = (dataType === 'gallery' && categoryType === selectedType) ? '' : 'none';
                                }
                            }
                        });
                    }
                    
                    // Reset the category selection if the current selection is hidden
                    if (categorySelect.value) {
                        const selectedOption = categorySelect.options[categorySelect.selectedIndex];
                        if (selectedOption.style.display === 'none') {
                            categorySelect.value = '';
                        }
                    }
                };
                
                // Initial filter on page load
                filterCategories(categoryTypeSelect.value);
                
                // Add event listener for category type changes
                categoryTypeSelect.addEventListener('change', function() {
                    filterCategories(this.value);
                });
                            // Show property types
                            const propertyOptgroup = categorySelect.querySelector('optgroup[label="Property Types"]');
                            if (propertyOptgroup) {
                                propertyOptgroup.style.display = '';
                                const propertyOptions = propertyOptgroup.querySelectorAll('option');
                                propertyOptions.forEach(opt => opt.style.display = '');
                            }
                        } else {
                            // Show gallery categories of the selected type
                            const allOptions = categorySelect.querySelectorAll('option[data-type]');
                            allOptions.forEach(opt => {
                                if (opt.getAttribute('data-type') === selectedType) {
                                    opt.style.display = '';
                                    // Show the parent optgroup
                                    let parent = opt.parentElement;
                                    if (parent.tagName === 'OPTGROUP') {
                                        parent.style.display = '';
                                    }
                                }
                            });
                        }
                    }
                    
                    // Reset selected category when type changes
                    categorySelect.selectedIndex = 0;
                });
            }
            
            function removeFile(index) {
                const dt = new DataTransfer();
                const { files } = fileInput;
                
                for (let i = 0; i < files.length; i++) {
                    if (index !== i) {
                        dt.items.add(files[i]);
                    }
                }
                
                fileInput.files = dt.files;
            }
        });
    </script>
    <script>
        // Handle category type change
        document.getElementById('category_type').addEventListener('change', function() {
            const selectedType = this.value;
            const categorySelect = document.getElementById('category_id');
            const selectedType = categoryTypeSelect ? categoryTypeSelect.value : '';
            
            if (!categorySelect) {
                console.error('Category select element not found');
                return;
            }
            
            // Reset the category dropdown
            categorySelect.innerHTML = '<option value="">-- Select a category --</option>';
            
            if (!selectedType) {
                for (let i = 0; i < options.length; i++) {
                    options[i].style.display = '';
                }
                return;
            }
            
            // Show/hide options based on selected type
            for (let i = 0; i < options.length; i++) {
                const option = options[i];
                const dataType = option.getAttribute('data-type');
                
                if (dataType === selectedType) {
                    option.style.display = '';
                } else {
                    option.style.display = 'none';
                }
            }
            
            // Reset the selected value if it's now hidden
            if (categorySelect.value && categorySelect.options[categorySelect.selectedIndex].style.display === 'none') {
                categorySelect.value = '';
            }
        });
    </script>
</body>
</html>
