<?php
header('Content-Type: text/html; charset=UTF-8');

// Includi il file per la connessione al database
require_once 'class/db-functions.php';

// Inizializza la connessione al database
try {
    $dbHandler = DBHandlerSelect::getInstance();
    $pdo = $dbHandler->getConnection();
} catch (Exception $e) {
    echo '<select id="ownerSelect" name="owner_id" class="form-control"><option value="">-- Seleziona --</option><option value="new_owner">➕ Aggiungi nuovo proprietario</option></select>';
    error_log("Errore connessione database in get-available-owners.php: " . $e->getMessage());
    exit();
}

// Recupera l'ID dell'immobile e l'ID dell'utente
$iduserlogin = isset($_GET['iduser']) ? intval($_GET['iduser']) : 0;
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;

// Debug: logga i valori di $iduserlogin e $idhome
error_log("Valori iniziali - idhome: $idhome, iduserlogin: $iduserlogin");

// Controlla che i parametri siano validi
if ($idhome <= 0 || $iduserlogin <= 0) {
    echo '<select id="ownerSelect" name="owner_id" class="form-control"><option value="">-- Seleziona --</option><option value="new_owner">➕ Aggiungi nuovo proprietario</option></select>';
    error_log("Parametri non validi in get-available-owners.php: idhome=$idhome, iduserlogin=$iduserlogin");
    exit();
}

// Debug: verifica il numero di proprietari associati all'immobile
try {
    $stmt = $pdo->prepare("SELECT owner_id FROM home_owners WHERE home_id = ?");
    $stmt->execute([$idhome]);
    $associatedOwners = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
    error_log("Proprietari associati all'immobile (idhome=$idhome): " . json_encode($associatedOwners));
} catch (Exception $e) {
    error_log("Errore query associati in get-available-owners.php: " . $e->getMessage());
    $associatedOwners = [];
}

// Debug: verifica tutti i proprietari dell'utente
try {
    $stmt = $pdo->prepare("SELECT owner_id, first_name, last_name FROM property_owners WHERE user_id = ?");
    $stmt->execute([$iduserlogin]);
    $allOwners = $stmt->fetchAll(PDO::FETCH_ASSOC);
    error_log("Tutti i proprietari dell'utente (iduser=$iduserlogin): " . json_encode($allOwners));
} catch (Exception $e) {
    error_log("Errore query tutti i proprietari in get-available-owners.php: " . $e->getMessage());
    $allOwners = [];
}

// Recupera i proprietari disponibili
try {
    $stmt = $pdo->prepare("
        SELECT 
            po.owner_id, 
            po.first_name, 
            po.last_name, 
            po.company_name, 
            po.tax_code 
        FROM 
            property_owners po
        LEFT JOIN 
            home_owners ho ON po.owner_id = ho.owner_id AND ho.home_id = ?
        WHERE 
            po.user_id = ? 
            AND ho.owner_id IS NULL
    ");
    $stmt->execute([$idhome, $iduserlogin]);
    $availableOwners = $stmt->fetchAll(PDO::FETCH_ASSOC);
    error_log("Proprietari disponibili per idhome=$idhome e iduser=$iduserlogin: " . json_encode($availableOwners));
} catch (Exception $e) {
    echo '<select id="ownerSelect" name="owner_id" class="form-control"><option value="">-- Seleziona --</option><option value="new_owner">➕ Aggiungi nuovo proprietario</option></select>';
    error_log("Errore query in get-available-owners.php: " . $e->getMessage());
    exit();
}

?>
<select id="ownerSelect" name="owner_id" class="form-control">
    <option value="">-- Seleziona --</option>
    <?php if (!empty($availableOwners)) { ?>
        <?php foreach ($availableOwners as $availableOwner) { ?>
            <option value="<?php echo $availableOwner['owner_id']; ?>">
                <?php
                echo htmlspecialchars($availableOwner['first_name'] . ' ' . $availableOwner['last_name']);
                if ($availableOwner['company_name']) {
                    echo ' (' . htmlspecialchars($availableOwner['company_name']) . ')';
                }
                echo ' - ' . htmlspecialchars($availableOwner['tax_code']);
                ?>
            </option>
        <?php } ?>
    <?php } ?>
    <option value="new_owner">➕ Aggiungi nuovo proprietario</option>
</select>