<?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 = [];

// Fetch categories for the dropdown with their types
$categories = [];
$categoryTypes = [];
try {
    $sql = "SELECT id, name, IFNULL(type, 'other') as type FROM gallery_categories ORDER BY type, name";
    $stmt = $conn->query($sql);
    if ($stmt) {
        $categories = $stmt->fetch_all(MYSQLI_ASSOC);
        
        // Get unique category types for the filter
        foreach ($categories as $category) {
            if (!empty($category['type']) && !in_array($category['type'], $categoryTypes)) {
                $categoryTypes[] = $category['type'];
            }
        }
        
        // If no types found, use the default types
        if (empty($categoryTypes)) {
            $categoryTypes = ['interior', 'exterior', 'amenities', 'floor_plan', 'other'];
        }
    }
} catch (Exception $e) {
    $error = "Error fetching categories: " . $e->getMessage();
}

// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Basic property details
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $state = trim($_POST['state'] ?? '');
    $zip_code = trim($_POST['zip_code'] ?? '');
    $bedrooms = trim($_POST['bedrooms'] ?? '');
    $bathrooms = trim($_POST['bathrooms'] ?? '');
    $area = trim($_POST['area'] ?? '');
    $year_built = trim($_POST['year_built'] ?? '');
    $property_type = trim($_POST['property_type'] ?? '');
    $status = trim($_POST['status'] ?? 'draft');
    
    // Handle image uploads
    $upload_dir = '../images/properties/';
    
    // Create upload directory if it doesn't exist
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Insert property into database
        $sql = "INSERT INTO properties (
            title, description, price, address, city, state, zip_code,
            bedrooms, bathrooms, area, year_built, property_type, status, created_by, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $stmt = $conn->prepare($sql);
        $created_by = $_SESSION['id'];
        
        $stmt->bind_param("ssdssssssssssi", 
            $title, $description, $price, $address, $city, $state, $zip_code,
            $bedrooms, $bathrooms, $area, $year_built, $property_type, $status, $created_by
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Error saving property: " . $stmt->error);
        }
        
        $property_id = $conn->insert_id;
        $stmt->close();
        
        // Handle image uploads if any
        if (isset($_FILES['images']) && is_array($_FILES['images']['tmp_name'])) {
            $category_id = $_POST['category_id'] ?? null;
            
            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 type
                    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                    if (!in_array($file_type, $allowed_types)) {
                        throw new Exception("Invalid file type: $file_name");
                    }
                    
                    // Validate file size (max 5MB)
                    $max_size = 5 * 1024 * 1024; // 5MB
                    if ($file_size > $max_size) {
                        throw new Exception("File too large (max 5MB): $file_name");
                    }
                    
                    // Generate unique filename
                    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                    $new_filename = 'property_' . $property_id . '_' . uniqid() . '.' . $file_ext;
                    $destination = $upload_dir . $new_filename;
                    
                    // Move uploaded file
                    if (move_uploaded_file($file_tmp, $destination)) {
                        // Store the relative path from the root of the website
                        $relative_path = 'images/properties/' . $new_filename;
                        
                        // Insert into property_images table
                        $sql = "INSERT INTO property_images (property_id, image_path, is_featured, created_at) 
                                VALUES (?, ?, 0, NOW())";
                        
                        $stmt = $conn->prepare($sql);
                        $stmt->bind_param("is", $property_id, $relative_path);
                        
                        if (!$stmt->execute()) {
                            throw new Exception("Error saving image: " . $stmt->error);
                        }
                        
                        $stmt->close();
                    }
                }
            }
        }
        
        // If we got here, commit the transaction
        $conn->commit();
        $success = "Property added successfully!";
        
        // Redirect to properties list or show success message
        header("Location: properties.php?success=1");
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        $error = $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Property - Admin Panel</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: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
            --border-color: #e9ecef;
            --text-muted: #6c757d;
        }
        
        body {
            background-color: #f5f7fb;
            color: #333;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(180deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 1.5rem 0;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            position: fixed;
            width: 250px;
        }
        
        .sidebar-brand {
            padding: 0 1.5rem 1.5rem;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 1rem;
        }
        
        .sidebar-brand h3 {
            color: white;
            margin: 0;
            font-weight: 700;
            font-size: 1.5rem;
        }
        
        .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 0.75rem 1rem;
            margin: 0.25rem 0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            transition: all 0.3s;
        }
        
        .nav-link i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        
        .nav-link:hover, .nav-link.active {
            background-color: rgba(255, 255, 255, 0.1);
            color: white;
            text-decoration: none;
        }
        
        .main-content {
            margin-left: 250px;
            padding: 2rem;
            transition: all 0.3s;
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border-color);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin: 0;
            color: var(--dark-color);
        }
        
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            margin-bottom: 1.5rem;
            background-color: white;
        }
        
        .card-header {
            background-color: white;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            font-weight: 600;
            padding: 1rem 1.25rem;
            border-radius: 10px 10px 0 0 !important;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        .form-label {
            font-weight: 500;
            color: #495057;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 0.375rem;
            padding: 0.5rem 0.75rem;
            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.2rem rgba(67, 97, 238, 0.25);
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border: none;
            padding: 0.5rem 1.5rem;
            font-weight: 500;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            background-color: var(--secondary-color);
            transform: translateY(-1px);
        }
        
        .btn-outline-secondary {
            border-color: #dee2e6;
            color: #6c757d;
        }
        
        .btn-outline-secondary:hover {
            background-color: #f8f9fa;
            color: #6c757d;
        }
        
        .file-upload-container {
            border: 2px dashed #dee2e6;
            border-radius: 0.5rem;
            padding: 2rem;
            text-align: center;
            background-color: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 1.5rem;
        }
        
        .file-upload-container:hover {
            border-color: var(--primary-color);
            background-color: #f0f4ff;
        }
        
        .file-upload-container i {
            font-size: 2.5rem;
            color: #6c757d;
            margin-bottom: 1rem;
            display: block;
        }
        
        .file-upload-container p {
            color: #6c757d;
            margin-bottom: 0.5rem;
        }
        
        .file-upload-container small {
            color: #adb5bd;
            font-size: 0.875rem;
        }
        
        #file-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .preview-item {
            position: relative;
            width: 120px;
            height: 120px;
            border-radius: 0.5rem;
            overflow: hidden;
            border: 1px solid #dee2e6;
        }
        
        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .preview-item .remove-btn {
            position: absolute;
            top: 0.25rem;
            right: 0.25rem;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background-color: rgba(220, 53, 69, 0.8);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            border: none;
            padding: 0;
            font-size: 0.75rem;
        }
        
        .is-invalid {
            border-color: var(--danger-color) !important;
        }
        
        .invalid-feedback {
            color: var(--danger-color);
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }
        
        .alert {
            border: none;
            border-radius: 0.5rem;
            padding: 1rem 1.25rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
        }
        
        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .form-section {
            margin-bottom: 2rem;
            padding: 1.5rem;
            background-color: white;
            border-radius: 0.5rem;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.05);
        }
        
        .section-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 1px solid #e9ecef;
            color: var(--dark-color);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0 sidebar">
                <div class="sidebar-brand">
                    <h3>Admin</h3>
                </div>
                <ul class="nav flex-column mb-auto px-3">
                    <li class="nav-item">
                        <a href="index.php" class="nav-link">
                            <i class="fas fa-home"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="properties.php" class="nav-link active">
                            <i class="fas fa-building"></i>
                            Properties
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="categories.php" class="nav-link">
                            <i class="fas fa-tags"></i>
                            Categories
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="gallery.php" class="nav-link">
                            <i class="fas fa-images"></i>
                            Gallery
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="contacts.php" class="nav-link">
                            <i class="fas fa-envelope"></i>
                            Contacts
                        </a>
                    </li>
                </ul>
                <div class="dropdown px-3 mt-auto">
                    <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" data-bs-toggle="dropdown">
                        <i class="fas fa-user-circle me-2"></i>
                        <strong><?php echo htmlspecialchars($_SESSION["username"]); ?></strong>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-dark">
                        <li><a class="dropdown-item" href="profile.php">Profile</a></li>
                        <li><a class="dropdown-item" href="logout.php">Sign out</a></li>
                    </ul>
                </div>
            </div>
            
            <!-- Main Content -->
            <main class="main-content">
                <!-- Page Header -->
                <div class="page-header">
                    <h1 class="page-title">Add New Property</h1>
                    <a href="properties.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i> Back to Properties
                    </a>
                </div>
                
                <?php if (!empty($error)): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
                    </div>
                <?php endif; ?>
                
                <?php if (!empty($success)): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
                    </div>
                <?php endif; ?>
                
                <form action="" method="post" enctype="multipart/form-data" id="property-form">
                    <!-- Basic Information Section -->
                    <div class="form-section">
                        <h2 class="section-title">Basic Information</h2>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="title" class="form-label">Property Title <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="title" name="title" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="price" class="form-label">Price ($) <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="price" name="price" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">Description <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="description" name="description" rows="4" required></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="property_type" class="form-label">Property Type <span class="text-danger">*</span></label>
                                    <select class="form-select" id="property_type" name="property_type" required>
                                        <option value="">Select Type</option>
                                        <option value="House">House</option>
                                        <option value="Apartment">Apartment</option>
                                        <option value="Condo">Condo</option>
                                        <option value="Townhouse">Townhouse</option>
                                        <option value="Land">Land</option>
                                        <option value="Commercial">Commercial</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="status" class="form-label">Status <span class="text-danger">*</span></label>
                                    <select class="form-select" id="status" name="status" required>
                                        <option value="draft">Draft</option>
                                        <option value="published">Published</option>
                                        <option value="sold">Sold</option>
                                        <option value="rented">Rented</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Property Details Section -->
                    <div class="form-section">
                        <h2 class="section-title">Property Details</h2>
                        
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="bedrooms" class="form-label">Bedrooms <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="bedrooms" name="bedrooms" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="bathrooms" class="form-label">Bathrooms <span class="text-danger">*</span></label>
                                    <input type="number" step="0.1" class="form-control" id="bathrooms" name="bathrooms" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="area" class="form-label">Area (sq ft) <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="area" name="area" required>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="year_built" class="form-label">Year Built <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="year_built" name="year_built" required>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Location Section -->
                    <div class="form-section">
                        <h2 class="section-title">Location</h2>
                        
                        <div class="mb-3">
                            <label for="address" class="form-label">Address <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="address" name="address" required>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="city" class="form-label">City <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="city" name="city" required>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="state" class="form-label">State <span class="text-danger">*</span></label>
                                    <select class="form-select" id="state" name="state" required>
                                        <option value="">Select State</option>
                                        <option value="AL">Alabama</option>
                                        <option value="AK">Alaska</option>
                                        <option value="AZ">Arizona</option>
                                        <!-- Add more states as needed -->
                                        <option value="CA">California</option>
                                        <option value="NY">New York</option>
                                        <option value="TX">Texas</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="zip_code" class="form-label">ZIP Code <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="zip_code" name="zip_code" required>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Images Section -->
                    <div class="form-section">
                        <h2 class="section-title">Images</h2>
                        
                        <div class="mb-4">
                            <label class="form-label">Category Type</label>
                            <select class="form-select mb-3" id="category_type">
                                <option value="">All Types</option>
                                <?php foreach ($categoryTypes as $type): ?>
                                    <option value="<?php echo htmlspecialchars($type); ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', $type)); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            
                            <label class="form-label">Category</label>
                            <select class="form-select mb-3" id="category_id" name="category_id">
                                <option value="">Select a category</option>
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo $category['id']; ?>" data-type="<?php echo $category['type']; ?>">
                                        <?php echo htmlspecialchars($category['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            
                            <div class="mb-3">
                                <label for="image_description" class="form-label">Image Description (Optional)</label>
                                <textarea class="form-control" id="image_description" name="image_description" rows="2"></textarea>
                            </div>
                        </div>
                        
                        <!-- File Upload -->
                        <div class="file-upload-container" id="drop-zone">
                            <input type="file" id="file-input" name="images[]" multiple accept="image/*" style="display: none;">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <p>Drag & drop your files here or</p>
                            <button type="button" class="btn btn-outline-primary" id="browse-btn">Browse Files</button>
                            <small class="d-block mt-2">Supports JPG, PNG, GIF, WEBP (Max 5MB each)</small>
                        </div>
                        
                        <!-- File Preview -->
                        <div id="file-preview"></div>
                    </div>
                    
                    <!-- Form Actions -->
                    <div class="d-flex justify-content-between mt-4">
                        <button type="reset" class="btn btn-outline-secondary">
                            <i class="fas fa-undo me-2"></i> Reset
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i> Save Property
                        </button>
                    </div>
                </form>
            </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('property-form');
            const categoryTypeSelect = document.getElementById('category_type');
            const categorySelect = document.getElementById('category_id');
            
            // Filter categories based on selected type
            categoryTypeSelect.addEventListener('change', function() {
                const selectedType = this.value;
                const options = categorySelect.querySelectorAll('option');
                
                options.forEach(option => {
                    if (option.value === '') {
                        option.style.display = 'block';
                        return;
                    }
                    
                    if (selectedType === '' || option.dataset.type === selectedType) {
                        option.style.display = 'block';
                    } else {
                        option.style.display = 'none';
                    }
                });
                
                // Reset the category selection
                categorySelect.value = '';
            });
            
            // Handle file selection via button
            browseBtn.addEventListener('click', function() {
                fileInput.click();
            });
            
            // Handle drag and drop
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, preventDefaults, false);
            });
            
            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            ['dragenter', 'dragover'].forEach(eventName => {
                dropZone.addEventListener(eventName, highlight, false);
            });
            
            ['dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, unhighlight, false);
            });
            
            function highlight() {
                dropZone.classList.add('border-primary');
                dropZone.style.borderStyle = 'dashed';
            }
            
            function unhighlight() {
                dropZone.classList.remove('border-primary');
                dropZone.style.borderStyle = 'dashed';
            }
            
            // Handle dropped files
            dropZone.addEventListener('drop', handleDrop, false);
            
            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                handleFiles({ target: { files } });
            }
            
            // Handle file input change
            fileInput.addEventListener('change', handleFiles);
            
            function handleFiles(e) {
                const files = e.target.files;
                
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    
                    if (!file.type.match('image.*')) {
                        continue;
                    }
                    
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        const previewItem = document.createElement('div');
                        previewItem.className = 'preview-item';
                        
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        
                        const removeBtn = document.createElement('button');
                        removeBtn.type = 'button';
                        removeBtn.className = 'remove-btn';
                        removeBtn.innerHTML = '&times;';
                        removeBtn.addEventListener('click', function() {
                            previewItem.remove();
                            updateFileInput();
                        });
                        
                        previewItem.appendChild(img);
                        previewItem.appendChild(removeBtn);
                        previewContainer.appendChild(previewItem);
                    };
                    
                    reader.readAsDataURL(file);
                }
                
                updateFileInput();
            }
            
            // Update the file input with the selected files
            function updateFileInput() {
                // This is a simplified version - in a real app, you might want to use FormData
                // to handle the file uploads via AJAX
                console.log('Files selected:', fileInput.files.length);
            }
            
            // Form validation
            form.addEventListener('submit', function(e) {
                let isValid = true;
                const requiredFields = form.querySelectorAll('[required]');
                
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        field.classList.add('is-invalid');
                        isValid = false;
                    } else {
                        field.classList.remove('is-invalid');
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    alert('Please fill in all required fields.');
                }
            });
        });
    </script>
</body>
</html>
