<?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']);
$land = null;

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

$errors = [];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    // Validate input
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $land_type = $_POST['land_type'];
    $size_sqm = !empty($_POST['size_sqm']) ? (float)$_POST['size_sqm'] : null;
    $price_per_sqm = !empty($_POST['price_per_sqm']) ? (float)$_POST['price_per_sqm'] : null;
    $total_price = (float)$_POST['total_price'];
    $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;
    $has_document = isset($_POST['has_document']) ? 1 : 0;
    $document_type = $has_document ? $_POST['document_type'] : null;
    $status = $_POST['status'];
    $featured = isset($_POST['featured']) ? 1 : 0;
    
    // Validate required fields
    if (empty($title)) $errors[] = "Title is required";
    if (empty($land_type)) $errors[] = "Land type is required";
    if ($total_price <= 0) $errors[] = "Valid total 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
    $features = isset($_POST['features']) ? array_filter($_POST['features']) : [];
    
    // Handle image uploads
    $images = [];
    $existing_images = $is_edit ? json_decode($land['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];
                
                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;
                }
                
                $extension = pathinfo($file_name, PATHINFO_EXTENSION);
                $new_filename = 'land_' . uniqid() . '_' . time() . '.' . $extension;
                $upload_path = LAND_UPLOAD_DIR . '/' . $new_filename;
                
                if (move_uploaded_file($file_tmp, $upload_path)) {
                    $images[] = 'uploads/lands/' . $new_filename;
                }
            }
        }
    }
    
    if ($is_edit) {
        $images = array_merge($existing_images, $images);
    }
    
    if (empty($images) && !$is_edit) {
        $errors[] = "At least one land image is required";
    }
    
    if (empty($errors)) {
        try {
            $slug = Security::generateSlug($title);
            
            // Check if slug exists
            $slug_check = $db->fetchOne("SELECT id FROM lands WHERE slug = ? AND id != ?", [$slug, $id ?? 0]);
            if ($slug_check) {
                $slug .= '-' . time();
            }
            
            if ($is_edit) {
                $sql = "UPDATE lands SET 
                        title = ?, slug = ?, description = ?, land_type = ?,
                        size_sqm = ?, price_per_sqm = ?, total_price = ?,
                        address = ?, city = ?, state = ?, location_area = ?,
                        latitude = ?, longitude = ?, has_document = ?,
                        document_type = ?, features = ?, images = ?,
                        status = ?, featured = ?, updated_at = NOW()
                        WHERE id = ?";
                
                $db->execute($sql, [
                    $title, $slug, $description, $land_type,
                    $size_sqm, $price_per_sqm, $total_price,
                    $address, $city, $state, $location_area,
                    $latitude, $longitude, $has_document,
                    $document_type, json_encode($features), json_encode($images),
                    $status, $featured, $id
                ]);
                
                $_SESSION['success'] = "Land updated successfully";
            } else {
                $sql = "INSERT INTO lands (
                        title, slug, description, land_type, size_sqm,
                        price_per_sqm, total_price, address, city, state,
                        location_area, latitude, longitude, has_document,
                        document_type, features, images, status, featured, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $db->execute($sql, [
                    $title, $slug, $description, $land_type, $size_sqm,
                    $price_per_sqm, $total_price, $address, $city, $state,
                    $location_area, $latitude, $longitude, $has_document,
                    $document_type, json_encode($features), json_encode($images),
                    $status, $featured, $current_user['id']
                ]);
                
                $_SESSION['success'] = "Land added successfully";
            }
            
            header('Location: lands.php');
            exit;
            
        } catch (Exception $e) {
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}

include 'includes/header.php';
?>

<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="lands.php">Lands</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">
    <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">Land Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" class="form-control" required
                               value="<?php echo htmlspecialchars($land['title'] ?? ''); ?>"
                               placeholder="e.g., 500 Sqm Land in Lekki">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="5"
                                  placeholder="Describe the land..."><?php echo htmlspecialchars($land['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Land Type <span class="text-danger">*</span></label>
                            <select name="land_type" class="form-select" required>
                                <option value="">Select Type</option>
                                <option value="residential" <?php echo ($land['land_type'] ?? '') === 'residential' ? 'selected' : ''; ?>>Residential</option>
                                <option value="commercial" <?php echo ($land['land_type'] ?? '') === 'commercial' ? 'selected' : ''; ?>>Commercial</option>
                                <option value="industrial" <?php echo ($land['land_type'] ?? '') === 'industrial' ? 'selected' : ''; ?>>Industrial</option>
                                <option value="agricultural" <?php echo ($land['land_type'] ?? '') === 'agricultural' ? 'selected' : ''; ?>>Agricultural</option>
                                <option value="mixed" <?php echo ($land['land_type'] ?? '') === 'mixed' ? 'selected' : ''; ?>>Mixed Use</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Size (Square Meters)</label>
                            <input type="number" name="size_sqm" class="form-control" min="0" step="0.01"
                                   value="<?php echo $land['size_sqm'] ?? ''; ?>"
                                   placeholder="e.g., 500">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Price per Sqm (₦)</label>
                            <input type="number" name="price_per_sqm" class="form-control" min="0" step="0.01"
                                   value="<?php echo $land['price_per_sqm'] ?? ''; ?>">
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Total Price (₦) <span class="text-danger">*</span></label>
                            <input type="number" name="total_price" class="form-control" required min="0" step="0.01"
                                   value="<?php echo $land['total_price'] ?? ''; ?>"
                                   placeholder="0.00">
                        </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($land['address'] ?? ''); ?>"
                               placeholder="Full 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($land['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($land['state'] ?? ''); ?>">
                        </div>
                        
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Area/Location</label>
                            <input type="text" name="location_area" class="form-control"
                                   value="<?php echo htmlspecialchars($land['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 $land['latitude'] ?? ''; ?>">
                        </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 $land['longitude'] ?? ''; ?>">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Land Images -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Land 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($land['images'])): ?>
                            <?php foreach (json_decode($land['images'], true) as $image): ?>
                            <div class="image-preview">
                                <img src="../<?php echo htmlspecialchars($image); ?>" alt="Land">
                            </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 ($land['status'] ?? 'available') === 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="sold" <?php echo ($land['status'] ?? '') === 'sold' ? 'selected' : ''; ?>>Sold</option>
                            <option value="reserved" <?php echo ($land['status'] ?? '') === 'reserved' ? 'selected' : ''; ?>>Reserved</option>
                            <option value="inactive" <?php echo ($land['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 ($land['featured'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="featured">
                            Featured Land
                        </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'; ?> Land
                    </button>
                    
                    <a href="lands.php" class="btn btn-outline-secondary w-100 mt-2">
                        <i class="fas fa-times"></i> Cancel
                    </a>
                </div>
            </div>
            
            <!-- Documentation -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Documentation</h5>
                </div>
                <div class="card-body">
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="has_document" id="hasDocument"
                               <?php echo ($land['has_document'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="hasDocument">
                            Has Title Document
                        </label>
                    </div>
                    
                    <div id="documentTypeDiv" style="display: <?php echo ($land['has_document'] ?? 0) ? 'block' : 'none'; ?>;">
                        <label class="form-label">Document Type</label>
                        <select name="document_type" class="form-select">
                            <option value="">Select Type</option>
                            <option value="C of O" <?php echo ($land['document_type'] ?? '') === 'C of O' ? 'selected' : ''; ?>>Certificate of Occupancy (C of O)</option>
                            <option value="Deed of Assignment" <?php echo ($land['document_type'] ?? '') === 'Deed of Assignment' ? 'selected' : ''; ?>>Deed of Assignment</option>
                            <option value="Survey Plan" <?php echo ($land['document_type'] ?? '') === 'Survey Plan' ? 'selected' : ''; ?>>Survey Plan</option>
                            <option value="Receipt" <?php echo ($land['document_type'] ?? '') === 'Receipt' ? 'selected' : ''; ?>>Receipt</option>
                        </select>
                    </div>
                </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 = ['Fenced', 'Gated Estate', 'Tarred Road', 'Electricity', 'Water Supply', 'Drainage', 'Corner Piece', 'Dry Land'];
                    $selected_features = $is_edit ? json_decode($land['features'], true) ?? [] : [];
                    
                    foreach ($all_features as $feature): ?>
                    <div class="form-check mb-2">
                        <input class="form-check-input" 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" for="feature_<?php echo str_replace(' ', '_', $feature); ?>">
                            <?php echo $feature; ?>
                        </label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</form>

<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,
    .image-upload-container.dragover {
        border-color: var(--primary);
        background: rgba(212, 160, 23, 0.05);
    }
    
    .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;
    }
</style>

<script>
    // Document type toggle
    $('#hasDocument').change(function() {
        if ($(this).is(':checked')) {
            $('#documentTypeDiv').slideDown();
        } else {
            $('#documentTypeDiv').slideUp();
        }
    });
    
    // Image upload (same as property-form.php)
    const uploadArea = document.getElementById('imageUploadArea');
    const imageInput = document.getElementById('imageInput');
    const imagePreview = document.getElementById('imagePreview');
    let uploadedFiles = [];
    
    uploadArea.addEventListener('click', function(e) {
        if (!e.target.classList.contains('remove-image') && 
            !e.target.closest('.remove-image')) {
            imageInput.click();
        }
    });
    
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, e => {
            e.preventDefault();
            e.stopPropagation();
        }, false);
    });
    
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.addEventListener(eventName, () => {
            uploadArea.classList.add('dragover');
        }, false);
    });
    
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.addEventListener(eventName, () => {
            uploadArea.classList.remove('dragover');
        }, false);
    });
    
    uploadArea.addEventListener('drop', function(e) {
        const files = e.dataTransfer.files;
        handleFiles(files);
    }, false);
    
    imageInput.addEventListener('change', function() {
        handleFiles(this.files);
    });
    
    function handleFiles(files) {
        Array.from(files).forEach(file => {
            if (!file.type.startsWith('image/')) {
                Swal.fire('Error', 'Please upload only images', 'error');
                return;
            }
            if (file.size > 5242880) {
                Swal.fire('Error', 'File size must be less than 5MB', 'error');
                return;
            }
            uploadedFiles.push(file);
            previewFile(file);
        });
        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);
            
            preview.querySelector('.remove-image').addEventListener('click', function(e) {
                e.stopPropagation();
                const idx = parseInt(this.dataset.index);
                uploadedFiles.splice(idx, 1);
                preview.remove();
                updateFileInput();
                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;
        }
    }
</script>

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