casadoc/public/userportal/add-owner-to-home.php
2025-04-22 08:05:22 +02:00

49 lines
2.1 KiB
PHP

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/class/db-functions.php';
$dbHandler = DBHandlerSelect::getInstance();
$pdo = $dbHandler->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()]));
}