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

if (!isset($_SESSION['user_id']) || empty($_SESSION['user_role'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

if ($_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized. Only admins can add properties']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$title = trim($data['title'] ?? '');
$description = trim($data['description'] ?? '');
$price = floatval($data['price'] ?? 0);
$type = trim($data['type'] ?? '');
$status = trim($data['status'] ?? 'active');
$address = trim($data['address'] ?? '');
$city = trim($data['city'] ?? '');
$state = trim($data['state'] ?? '');
$bedrooms = intval($data['bedrooms'] ?? 0);
$bathrooms = intval($data['bathrooms'] ?? 0);
$image_url = trim($data['image_url'] ?? '');
$broker_id = intval($data['broker_id'] ?? 0);

if ($title === '' || $type === '' || $price <= 0 || $address === '' || $city === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required fields: title, type, price, address, city']);
    exit;
}

try {
    $stmt = $mysqli->prepare("
        INSERT INTO properties (title, description, price, type, status, address, city, state, bedrooms, bathrooms, image_url, broker_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CASE WHEN ? > 0 THEN ? ELSE NULL END)
    ");
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $mysqli->error);
    }

    $stmt->bind_param(
        'ssdsssssiisii',
        $title,
        $description,
        $price,
        $type,
        $status,
        $address,
        $city,
        $state,
        $bedrooms,
        $bathrooms,
        $image_url,
        $broker_id,
        $broker_id
    );

    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    echo json_encode([
        'success' => true,
        'message' => 'Property added successfully',
        'property_id' => $stmt->insert_id
    ]);

    $stmt->close();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error adding property: ' . $e->getMessage()]);
}

$mysqli->close();
?>
