<?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;
}

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

if (!$data || !isset($data['property_id'])) {
    echo json_encode(['success' => false, 'message' => 'Missing property_id']);
    exit;
}

$property_id = intval($data['property_id']);
$staff_id = $_SESSION['user_id'];

// Only allow updating description and property_type (non-sensitive fields)
$allowed_fields = ['description', 'property_type'];
$updates = [];
$params = [];

foreach ($allowed_fields as $field) {
    if (isset($data[$field]) && $data[$field] !== null) {
        $updates[] = "$field = ?";
        $params[] = $data[$field];
    }
}

if (empty($updates)) {
    echo json_encode(['success' => false, 'message' => 'No valid fields to update']);
    exit;
}

$params[] = $property_id;

try {
    $updates[] = "updated_at = NOW()";
    $query = "UPDATE properties SET " . implode(', ', $updates) . " WHERE id = ?";
    
    $stmt = $conn->prepare($query);
    
    // Build type string dynamically
    $types = str_repeat('s', count($updates) - 1) . 'i';
    $stmt->bind_param($types, ...$params);
    
    if ($stmt->execute()) {
        $stmt->close();
        echo json_encode(['success' => true, 'message' => 'Property updated successfully']);
    } else {
        throw new Exception('Failed to update property');
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
