<?php
// ==========================================
// FILE: admin/lands.php
// ==========================================
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Lands Management';

if (!$auth->hasPermission('can_manage_properties') && !$auth->hasRole('super_admin')) {
    $_SESSION['error'] = "You don't have permission";
    header('Location: dashboard.php');
    exit;
}

// Similar to properties.php but for lands
// Filters and pagination
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$city_filter = $_GET['city'] ?? '';
$page_num = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page_num - 1) * $limit;

$where = [];
$params = [];

if ($search) {
    $where[] = "(title LIKE ? OR address LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $where[] = "status = ?";
    $params[] = $status_filter;
}

if ($city_filter) {
    $where[] = "city = ?";
    $params[] = $city_filter;
}

$where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';

$count_sql = "SELECT COUNT(*) as total FROM lands $where_sql";
$total = $db->fetchOne($count_sql, $params)['total'];
$total_pages = ceil($total / $limit);

$sql = "SELECT l.*, u.first_name, u.last_name
        FROM lands l
        LEFT JOIN users u ON l.created_by = u.id
        $where_sql
        ORDER BY l.created_at DESC
        LIMIT $limit OFFSET $offset";

$lands = $db->fetchAll($sql, $params);

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Lands Management</h1>
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
            <li class="breadcrumb-item active">Lands</li>
        </ol>
    </nav>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0"><i class="fas fa-map"></i> All Lands</h5>
        <?php if ($auth->hasPermission('can_create') || $auth->hasRole('super_admin')): ?>
        <a href="land-form.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> Add New Land
        </a>
        <?php endif; ?>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-4">
                    <input type="text" name="search" class="form-control" placeholder="Search..." 
                           value="<?php echo htmlspecialchars($search); ?>">
                </div>
                <div class="col-md-3">
                    <select name="status" class="form-select">
                        <option value="">All Status</option>
                        <option value="available" <?php echo $status_filter === 'available' ? 'selected' : ''; ?>>Available</option>
                        <option value="sold" <?php echo $status_filter === 'sold' ? 'selected' : ''; ?>>Sold</option>
                        <option value="reserved" <?php echo $status_filter === 'reserved' ? 'selected' : ''; ?>>Reserved</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <input type="text" name="city" class="form-control" placeholder="City..." 
                           value="<?php echo htmlspecialchars($city_filter); ?>">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                </div>
            </div>
        </form>
        
        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Location</th>
                        <th>Size (Sqft)</th>
                        <th>Price</th>
                        <th>Has Survey</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($lands)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No lands found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($lands as $land): ?>
                        <tr>
                            <td>
                                <?php 
                                $images = json_decode($land['images'], true);
                                $first_image = $images[0] ?? 'placeholder.jpg';
                                ?>
                                <img src="../<?php echo htmlspecialchars($first_image); ?>" 
                                     alt="Land" class="rounded" style="width: 60px; height: 60px; object-fit: cover;">
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($land['title']); ?></strong>
                                <?php if ($land['featured']): ?>
                                <span class="badge bg-warning text-dark ms-1">Featured</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <i class="fas fa-map-marker-alt text-primary"></i>
                                <?php echo htmlspecialchars($land['city']); ?>, <?php echo htmlspecialchars($land['state']); ?>
                            </td>
                            <td><?php echo number_format($land['size_sqft']); ?></td>
                            <td><strong>₦<?php echo number_format($land['price']); ?></strong></td>
                            <td>
                                <?php if ($land['has_survey']): ?>
                                <span class="badge bg-success"><i class="fas fa-check"></i> Yes</span>
                                <?php else: ?>
                                <span class="badge bg-warning">No</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php
                                $badge_class = [
                                    'available' => 'success',
                                    'sold' => 'danger',
                                    'reserved' => 'warning',
                                    'inactive' => 'secondary'
                                ][$land['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $badge_class; ?>">
                                    <?php echo ucfirst($land['status']); ?>
                                </span>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="land-form.php?id=<?php echo $land['id']; ?>" 
                                       class="btn btn-outline-success" data-bs-toggle="tooltip" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    
                                    <?php if ($auth->hasPermission('can_delete') || $auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-danger delete-btn" 
                                            data-id="<?php echo $land['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($land['title']); ?>"
                                            data-bs-toggle="tooltip" title="Delete">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <nav>
            <ul class="pagination justify-content-center">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <li class="page-item <?php echo $i === $page_num ? 'active' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
            </ul>
        </nav>
        <?php endif; ?>
    </div>
</div>

<script>
    $('.delete-btn').click(function() {
        const id = $(this).data('id');
        const name = $(this).data('name');
        
        Swal.fire({
            title: 'Delete Land?',
            html: `Delete <strong>${name}</strong>?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete'
        }).then((result) => {
            if (result.isConfirmed) {
                // Implement delete logic
                window.location.href = `lands.php?delete=${id}`;
            }
        });
    });
</script>

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




?>