getConnection(); // Recupera i dati inviati tramite POST $idhome = isset($_POST['idhome']) ? (int)$_POST['idhome'] : 0; $owner_id = isset($_POST['owner_id']) ? (int)$_POST['owner_id'] : 0; $ownership_percentage = isset($_POST['ownership_percentage']) ? (float)$_POST['ownership_percentage'] : null; $notes = isset($_POST['notes']) ? htmlspecialchars($_POST['notes']) : null; // Verifica che tutti i dati siano presenti if ($idhome <= 0 || $owner_id <= 0 || is_null($ownership_percentage)) { die(json_encode(["success" => false, "message" => "Errore: Dati mancanti."])); } // Controlla se il proprietario è già associato alla casa $stmt = $pdo->prepare("SELECT 1 FROM home_owners WHERE home_id = ? AND owner_id = ?"); $stmt->execute([$idhome, $owner_id]); if ($stmt->fetch()) { die(json_encode(["success" => false, "message" => "Errore: Il proprietario è già associato a questa casa."])); } // Calcola la somma attuale delle percentuali di proprietà $stmt = $pdo->prepare("SELECT SUM(ownership_percentage) FROM home_owners WHERE home_id = ?"); $stmt->execute([$idhome]); $currentTotal = $stmt->fetchColumn() ?: 0; $totalAfterInsert = $currentTotal + $ownership_percentage; if ($totalAfterInsert > 100) { die(json_encode(["success" => false, "message" => "Errore: La somma totale dei proprietari supererebbe il 100%. Totale attuale: $currentTotal%, percentuale richiesta: $ownership_percentage%."])); } // Inserisce il nuovo proprietario nella tabella home_owners $stmt = $pdo->prepare(" INSERT INTO home_owners (home_id, owner_id, ownership_percentage, notes, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW()) "); try { $stmt->execute([$idhome, $owner_id, $ownership_percentage, $notes]); echo json_encode(["success" => true, "message" => "Proprietario aggiunto con successo."]); } catch (PDOException $e) { die(json_encode(["success" => false, "message" => "Errore nell'inserimento: " . $e->getMessage()])); }