<?php
session_start();
header('Content-Type: application/json');

// Include database connection
include '../layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get property ID from POST
$property_id = $_POST['property_id'] ?? null;

if (!$property_id) {
    echo json_encode(['success' => false, 'message' => 'Property ID is required']);
    exit();
}

try {
    // Get vacant units for the selected property
    $sql = "SELECT u.id, u.unit_number, u.bedrooms, u.bathrooms, u.rent_amount, 
                   ut.name as unit_type_name
            FROM units u
            LEFT JOIN unit_types ut ON u.unit_type_id = ut.id
            WHERE u.property_id = ? AND u.status = 'vacant'
            ORDER BY u.unit_number ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $property_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $units = [];
    while ($row = $result->fetch_assoc()) {
        $units[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'units' => $units,
        'count' => count($units)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}

$conn->close();
?>