<?php
require_once 'config.php';

checkAccess(['admin', 'programmer']);

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

try {
    if (isset($data['id'])) {
        // UPDATE
        $stmt = $pdo->prepare("UPDATE residents SET 
            property_id = ?, phone = ?, is_owner = ? 
            WHERE id = ?");
        $stmt->execute([
            $data['propertyId'], $data['phone'], $data['isOwner'] ? 1 : 0, $data['id']
        ]);
    } else {
        // INSERT
        if (!isset($data['userId'])) response(["error" => "ID de usuario requerido"], 400);
        
        // Validar si ya existe en esa propiedad
        $check = $pdo->prepare("SELECT id FROM residents WHERE user_id = ? AND property_id = ?");
        $check->execute([$data['userId'], $data['propertyId']]);
        if ($check->fetch()) {
            response(["error" => "Este usuario ya está asignado a esta propiedad"], 409);
        }

        $stmt = $pdo->prepare("INSERT INTO residents (user_id, property_id, phone, is_owner) VALUES (?, ?, ?, ?)");
        $stmt->execute([
            $data['userId'], $data['propertyId'], $data['phone'], $data['isOwner'] ? 1 : 0
        ]);
    }

    response(["success" => true]);
} catch (PDOException $e) {
    response(["error" => "Error al guardar residente: " . $e->getMessage()], 500);
}
?>