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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$search = $_GET['search'] ?? '';
$property_id = $_GET['property_id'] ?? '';

$sql = "SELECT u.*, p.property_name, p.property_code, ut.name as unit_type_name
        FROM units u
        LEFT JOIN properties p ON u.property_id = p.property_id
        LEFT JOIN unit_types ut ON u.unit_type_id = ut.type_id
        WHERE u.is_for_sale = 1 AND u.status != 'SOLD'";

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

if (!empty($search)) {
    $sql .= " AND (u.unit_number LIKE ? OR p.property_name LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ss';
}

if (!empty($property_id)) {
    $sql .= " AND u.property_id = ?";
    $params[] = $property_id;
    $types .= 'i';
}

$sql .= " ORDER BY p.property_name, u.unit_number ASC";

// Get properties for filter
$sql_properties = "SELECT * FROM properties ORDER BY property_name";
$result_properties = $conn->query($sql_properties);

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' => 'Units for Sale')); ?>
    <?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' => 'Sales Management', 'title' => 'Units for Sale')); ?>

                    <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 unit number or property">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Property</label>
                                            <select class="form-select" name="property_id">
                                                <option value="">All Properties</option>
                                                <?php while($prop = $result_properties->fetch_assoc()): ?>
                                                    <option value="<?php echo $prop['property_id']; ?>" 
                                                            <?php echo $property_id == $prop['property_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($prop['property_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <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>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <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">Units Available for Sale</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Unit Number</th>
                                                    <th>Property</th>
                                                    <th>Type</th>
                                                    <th>Bedrooms</th>
                                                    <th>Bathrooms</th>
                                                    <th>Sale Price</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($unit = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($unit['unit_number']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($unit['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($unit['property_code'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($unit['unit_type_name'] ?? 'N/A'); ?></td>
                                                            <td><?php echo $unit['bedrooms'] ?? 0; ?></td>
                                                            <td><?php echo $unit['bathrooms'] ?? 0; ?></td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($unit['sale_price'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-warning text-warning">For Sale</span>
                                                            </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="unit_sale_details.php?id=<?php echo $unit['unit_id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="create_reservation.php?unit_id=<?php echo $unit['unit_id']; ?>">
                                                                                <i class="ri-bookmark-line align-bottom me-2 text-muted"></i>Create Reservation
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No units available for sale</p>
                                                            </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>
