<?php
session_start();
include 'layouts/dbconn.php';

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get filter parameters
$search = $_GET['search'] ?? '';
$type_filter = $_GET['type'] ?? '';
$status_filter = $_GET['status'] ?? '';

// Define property types from enum
$property_types = [
    'Apartment Complex',
    'Commercial Tower', 
    'Gated Community',
    'Mall',
    'Single Unit',
    'Land'
];

// Build query
$sql = "SELECT p.*, 
               COUNT(DISTINCT u.id) as total_units,
               COUNT(DISTINCT CASE WHEN u.status = 'occupied' THEN u.id END) as occupied_units,
               COUNT(DISTINCT CASE WHEN u.status = 'vacant' THEN u.id END) as vacant_units
        FROM properties p
        LEFT JOIN units u ON p.id = u.property_id
        WHERE 1=1";

$params = [];
$types = '';

if (!empty($search)) {
    $sql .= " AND (p.name LIKE ? OR p.location_area LIKE ? OR p.street_address LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'sss';
}

if (!empty($type_filter)) {
    $sql .= " AND p.type = ?";
    $params[] = $type_filter;
    $types .= 's';
}

$sql .= " GROUP BY p.id ORDER BY p.name ASC";

// Execute main query
if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Properties')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Property Management', 'title' => 'Properties')); ?>

                    <!-- Filters -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   value="<?php echo htmlspecialchars($search); ?>" 
                                                   placeholder="Search by name or location">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Property Type</label>
                                            <select class="form-select" name="type">
                                                <option value="">All Types</option>
                                                <?php foreach($property_types as $type): ?>
                                                    <option value="<?php echo $type; ?>" 
                                                            <?php echo $type_filter == $type ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($type); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line me-1"></i>Filter
                                                </button>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <a href="list_properties.php" class="btn btn-light w-100">
                                                    <i class="ri-refresh-line me-1"></i>Reset
                                                </a>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Properties Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">All Properties</h4>
                                    <div class="flex-shrink-0">
                                        <a href="add_property.php" class="btn btn-primary">
                                            <i class="ri-add-line align-bottom me-1"></i>Add Property
                                        </a>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Property Name</th>
                                                    <th>Type</th>
                                                    <th>Location</th>
                                                    <th>Units</th>
                                                    <th>Occupancy</th>
                                                    <th>Owner</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($property = $result->fetch_assoc()): ?>
                                                        <?php
                                                        $occupancy_rate = $property['total_units'] > 0 
                                                            ? round(($property['occupied_units'] / $property['total_units']) * 100, 1) 
                                                            : 0;
                                                        ?>
                                                        <tr>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <a href="property_details.php?id=<?php echo $property['id']; ?>" 
                                                                           class="text-dark">
                                                                            <?php echo htmlspecialchars($property['name']); ?>
                                                                        </a>
                                                                    </h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($property['street_address'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($property['type'] ?? 'N/A'); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($property['location_area'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo $property['total_units'] ?? 0; ?></span>
                                                            </td>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="flex-grow-1">
                                                                        <div class="progress progress-sm">
                                                                            <div class="progress-bar bg-success" role="progressbar" 
                                                                                 style="width: <?php echo $occupancy_rate; ?>%">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="flex-shrink-0 ms-2">
                                                                        <span class="text-muted fs-12"><?php echo $occupancy_rate; ?>%</span>
                                                                    </div>
                                                                </div>
                                                                <small class="text-muted">
                                                                    <?php echo $property['occupied_units'] ?? 0; ?> / <?php echo $property['total_units'] ?? 0; ?>
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                // Get owner name
                                                                $owner_sql = "SELECT CONCAT(first_name, ' ', last_name) as owner_name 
                                                                             FROM users WHERE id = ?";
                                                                $owner_stmt = $conn->prepare($owner_sql);
                                                                $owner_stmt->bind_param('i', $property['owner_id']);
                                                                $owner_stmt->execute();
                                                                $owner_result = $owner_stmt->get_result();
                                                                $owner = $owner_result->fetch_assoc();
                                                                echo htmlspecialchars($owner['owner_name'] ?? 'N/A');
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="property_details.php?id=<?php echo $property['id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="add_property.php?id=<?php echo $property['id']; ?>">
                                                                                <i class="ri-pencil-line align-bottom me-2 text-muted"></i>Edit
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="list_units.php?property_id=<?php echo $property['id']; ?>">
                                                                                <i class="ri-home-4-line align-bottom me-2 text-muted"></i>View Units
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No properties found</p>
                                                                <a href="add_property.php" class="btn btn-primary btn-sm mt-2">
                                                                    <i class="ri-add-line me-1"></i>Add First Property
                                                                </a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>