<?php
require_once '../../config.php';
header('Content-Type: application/json');

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

try {
    // Get all properties for staff to view
    $stmt = $conn->prepare("
        SELECT 
            p.id,
            p.title,
            p.city,
            p.price,
            p.bedrooms,
            p.bathrooms,
            p.type,
            p.description,
            p.image_url,
            p.agent_id,
            u.full_name as agent_name,
            p.created_at,
            p.updated_at,
            COUNT(i.id) as inquiry_count
        FROM properties p
        LEFT JOIN users u ON p.agent_id = u.id
        LEFT JOIN inquiries i ON p.id = i.property_id
        GROUP BY p.id
        ORDER BY p.created_at DESC
        LIMIT 100
    ");
    
    $stmt->execute();
    $result = $stmt->get_result();

    $properties = [];
    while ($row = $result->fetch_assoc()) {
        $properties[] = [
            'id' => intval($row['id']),
            'title' => $row['title'],
            'city' => $row['city'],
            'price' => intval($row['price']),
            'bedrooms' => intval($row['bedrooms']),
            'bathrooms' => intval($row['bathrooms']),
            'type' => $row['type'],
            'description' => $row['description'],
            'image_url' => $row['image_url'],
            'agent_id' => $row['agent_id'] ? intval($row['agent_id']) : null,
            'agent_name' => $row['agent_name'],
            'inquiry_count' => intval($row['inquiry_count']),
            'created_at' => $row['created_at'],
            'updated_at' => $row['updated_at']
        ];
    }
    $stmt->close();

    echo json_encode(['success' => true, 'properties' => $properties, 'count' => count($properties)]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
