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

$page_title = 'Properties';

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

$current_user = $auth->getCurrentUser();

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        
        // Delete property
        if ($action === 'delete' && ($auth->hasRole('super_admin') || $auth->hasPermission('can_delete'))) {
            $id = (int)$_POST['id'];
            
            try {
                // Get property images first
                $property = $db->fetchOne("SELECT images FROM properties WHERE id = ?", [$id]);
                
                // Delete images from server
                if ($property && $property['images']) {
                    $images = json_decode($property['images'], true);
                    foreach ($images as $image) {
                        $file_path = PROPERTY_UPLOAD_DIR . '/' . basename($image);
                        if (file_exists($file_path)) {
                            unlink($file_path);
                        }
                    }
                }
                
                // Delete property
                $sql = "DELETE FROM properties WHERE id = ?";
                $db->execute($sql, [$id]);
                
                $_SESSION['success'] = "Property deleted successfully";
                header('Location: properties.php');
                exit;
            } catch (Exception $e) {
                $_SESSION['error'] = "Failed to delete property";
            }
        }
        
        // Toggle status
        if ($action === 'toggle_status' && $auth->hasPermission('can_edit')) {
            $id = (int)$_POST['id'];
            $status = $_POST['status'];
            
            $sql = "UPDATE properties SET status = ? WHERE id = ?";
            $db->execute($sql, [$status, $id]);
            
            echo json_encode(['success' => true]);
            exit;
        }
    }
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$transaction_filter = $_GET['transaction'] ?? '';
$city_filter = $_GET['city'] ?? '';
$sort = $_GET['sort'] ?? 'created_at';
$order = $_GET['order'] ?? 'DESC';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Build query
$where = [];
$params = [];

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

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

if ($type_filter) {
    $where[] = "property_type = ?";
    $params[] = $type_filter;
}

if ($transaction_filter) {
    $where[] = "transaction_type = ?";
    $params[] = $transaction_filter;
}

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

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

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

// Get properties
$sql = "SELECT p.*, u.first_name, u.last_name, c.name as category_name
        FROM properties p
        LEFT JOIN users u ON p.created_by = u.id
        LEFT JOIN categories c ON p.category_id = c.id
        $where_sql
        ORDER BY $sort $order
        LIMIT $limit OFFSET $offset";

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

// Get distinct cities for filter
$cities = $db->fetchAll("SELECT DISTINCT city FROM properties ORDER BY city");

include 'includes/header.php';
?>

<div class="page-header">
    <h1>Properties 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">Properties</li>
        </ol>
    </nav>
</div>

<?php if (isset($_SESSION['success'])): ?>
<div class="alert alert-success alert-dismissible fade show">
    <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (isset($_SESSION['error'])): ?>
<div class="alert alert-danger alert-dismissible fade show">
    <i class="fas fa-exclamation-circle"></i> <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fas fa-building"></i> All Properties
            <span class="badge bg-primary"><?php echo number_format($total); ?></span>
        </h5>
        <?php if ($auth->hasPermission('can_create') || $auth->hasRole('super_admin')): ?>
        <a href="property-form.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> Add New Property
        </a>
        <?php endif; ?>
    </div>
    
    <div class="card-body">
        <!-- Filters -->
        <form method="GET" class="mb-4">
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" name="search" class="form-control" placeholder="Search..." 
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                </div>
                
                <div class="col-md-2">
                    <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="rented" <?php echo $status_filter === 'rented' ? 'selected' : ''; ?>>Rented</option>
                        <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="inactive" <?php echo $status_filter === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <select name="type" class="form-select">
                        <option value="">All Types</option>
                        <option value="house" <?php echo $type_filter === 'house' ? 'selected' : ''; ?>>House</option>
                        <option value="apartment" <?php echo $type_filter === 'apartment' ? 'selected' : ''; ?>>Apartment</option>
                        <option value="villa" <?php echo $type_filter === 'villa' ? 'selected' : ''; ?>>Villa</option>
                        <option value="duplex" <?php echo $type_filter === 'duplex' ? 'selected' : ''; ?>>Duplex</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <select name="transaction" class="form-select">
                        <option value="">All Transactions</option>
                        <option value="sale" <?php echo $transaction_filter === 'sale' ? 'selected' : ''; ?>>For Sale</option>
                        <option value="rent" <?php echo $transaction_filter === 'rent' ? 'selected' : ''; ?>>For Rent</option>
                        <option value="lease" <?php echo $transaction_filter === 'lease' ? 'selected' : ''; ?>>For Lease</option>
                    </select>
                </div>
                
                <div class="col-md-2">
                    <select name="city" class="form-select">
                        <option value="">All Cities</option>
                        <?php foreach ($cities as $city): ?>
                        <option value="<?php echo htmlspecialchars($city['city']); ?>" 
                                <?php echo $city_filter === $city['city'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($city['city']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-1">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter"></i>
                    </button>
                </div>
            </div>
        </form>
        
        <!-- Properties Table -->
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th style="width: 80px;">Image</th>
                        <th>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['sort' => 'title', 'order' => $sort === 'title' && $order === 'ASC' ? 'DESC' : 'ASC'])); ?>">
                                Title <?php if ($sort === 'title') echo $order === 'ASC' ? '▲' : '▼'; ?>
                            </a>
                        </th>
                        <th>Type</th>
                        <th>Location</th>
                        <th>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['sort' => 'price', 'order' => $sort === 'price' && $order === 'ASC' ? 'DESC' : 'ASC'])); ?>">
                                Price <?php if ($sort === 'price') echo $order === 'ASC' ? '▲' : '▼'; ?>
                            </a>
                        </th>
                        <th>Status</th>
                        <th>Views</th>
                        <th>Created</th>
                        <th style="width: 150px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($properties)): ?>
                    <tr>
                        <td colspan="9" class="text-center py-4">
                            <i class="fas fa-inbox fa-3x text-muted mb-3 d-block"></i>
                            <p class="text-muted">No properties found</p>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($properties as $property): ?>
                        <tr>
                            <td>
                                <?php 
                                $images = json_decode($property['images'], true);
                                $first_image = $images[0] ?? 'placeholder.jpg';
                                ?>
                                <img src="../<?php echo htmlspecialchars($first_image); ?>" 
                                     alt="Property" class="rounded" style="width: 60px; height: 60px; object-fit: cover;">
                            </td>
                            <td>
                                <strong><?php echo htmlspecialchars($property['title']); ?></strong>
                                <?php if ($property['featured']): ?>
                                <span class="badge bg-warning text-dark ms-1">Featured</span>
                                <?php endif; ?>
                                <br>
                                <small class="text-muted"><?php echo htmlspecialchars($property['category_name'] ?? 'N/A'); ?></small>
                            </td>
                            <td>
                                <span class="badge bg-info">
                                    <?php echo ucfirst($property['property_type']); ?>
                                </span>
                                <br>
                                <small class="text-muted">
                                    <?php echo ucfirst($property['transaction_type']); ?>
                                </small>
                            </td>
                            <td>
                                <i class="fas fa-map-marker-alt text-primary"></i>
                                <?php echo htmlspecialchars($property['city']); ?>
                                <br>
                                <small class="text-muted"><?php echo htmlspecialchars($property['location_area'] ?? ''); ?></small>
                            </td>
                            <td>
                                <strong>₦<?php echo number_format($property['price']); ?></strong>
                            </td>
                            <td>
                                <?php
                                $status_badge = [
                                    'available' => 'success',
                                    'sold' => 'danger',
                                    'rented' => 'warning',
                                    'pending' => 'info',
                                    'inactive' => 'secondary'
                                ][$property['status']] ?? 'secondary';
                                ?>
                                <span class="badge bg-<?php echo $status_badge; ?>">
                                    <?php echo ucfirst($property['status']); ?>
                                </span>
                            </td>
                            <td>
                                <i class="fas fa-eye"></i> <?php echo number_format($property['views']); ?>
                            </td>
                            <td>
                                <?php echo date('M d, Y', strtotime($property['created_at'])); ?>
                                <br>
                                <small class="text-muted">by <?php echo htmlspecialchars($property['first_name'] . ' ' . $property['last_name']); ?></small>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="../property-details.php?id=<?php echo $property['id']; ?>" 
                                       class="btn btn-outline-primary" target="_blank" 
                                       data-bs-toggle="tooltip" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    
                                    <?php if ($auth->hasPermission('can_edit') || $auth->hasRole('super_admin')): ?>
                                    <a href="property-form.php?id=<?php echo $property['id']; ?>" 
                                       class="btn btn-outline-success"
                                       data-bs-toggle="tooltip" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php endif; ?>
                                    
                                    <?php if ($auth->hasPermission('can_delete') || $auth->hasRole('super_admin')): ?>
                                    <button type="button" class="btn btn-outline-danger delete-btn" 
                                            data-id="<?php echo $property['id']; ?>"
                                            data-name="<?php echo htmlspecialchars($property['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 aria-label="Properties pagination">
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>">
                        Previous
                    </a>
                </li>
                
                <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                        <?php echo $i; ?>
                    </a>
                </li>
                <?php endfor; ?>
                
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>">
                        Next
                    </a>
                </li>
            </ul>
        </nav>
        
        <p class="text-center text-muted">
            Showing <?php echo min($offset + 1, $total); ?> to <?php echo min($offset + $limit, $total); ?> 
            of <?php echo number_format($total); ?> properties
        </p>
        <?php endif; ?>
    </div>
</div>

<!-- Delete Form (Hidden) -->
<form method="POST" id="deleteForm" style="display: none;">
    <input type="hidden" name="action" value="delete">
    <input type="hidden" name="id" id="deleteId">
    <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
</form>

<script>
    $(document).ready(function() {
        // Delete button handler
        $('.delete-btn').click(function() {
            const id = $(this).data('id');
            const name = $(this).data('name');
            
            Swal.fire({
                title: 'Delete Property?',
                html: `Are you sure you want to delete <strong>${name}</strong>?<br><br>This action cannot be undone!`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, delete it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $('#deleteId').val(id);
                    $('#deleteForm').submit();
                }
            });
        });
        
        // Initialize tooltips
        $('[data-bs-toggle="tooltip"]').tooltip();
    });
</script>

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