<?php include('include/headscript.php'); ?>
<?php
// Verifica se la variabile GET 'editpage' è impostata su 'nochange'
$disableEditing = isset($_GET['editpage']) && $_GET['editpage'] === 'nochange';
?>
<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die("Errore di connessione: " . $conn->connect_error);
}

// Recupera l'id immobile (idhome) passato tramite GET
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;

// Recupera i dettagli dell'immobile
$queryHome = $conn->prepare("SELECT name, address, zip, city, country FROM home WHERE idhome = ?");
$queryHome->bind_param('i', $idhome);
$queryHome->execute();
$resultHome = $queryHome->get_result();
$homeDetails = $resultHome->fetch_assoc();

if (!$homeDetails) {
    die("Immobile non trovato o accesso non autorizzato.");
}

// Recupera i proprietari associati all'immobile
$queryOwners = $conn->prepare("
    SELECT 
        po.owner_id, 
        po.first_name, 
        po.last_name, 
        po.company_name, 
        po.tax_code, 
        po.email, 
        ho.ownership_percentage, 
        ho.notes
    FROM 
        home_owners AS ho
    INNER JOIN 
        property_owners AS po ON ho.owner_id = po.owner_id
    WHERE 
        ho.home_id = ?
");
$queryOwners->bind_param('i', $idhome);
$queryOwners->execute();
$resultOwners = $queryOwners->get_result();

// Recupera tutti i proprietari disponibili dell'utente per la selezione
$queryAvailableOwners = $conn->prepare("
    SELECT 
        owner_id, 
        first_name, 
        last_name, 
        company_name, 
        tax_code 
    FROM 
        property_owners 
    WHERE 
        user_id = ? 
        AND owner_id NOT IN (
            SELECT owner_id FROM home_owners WHERE home_id = ?
        )
");
$queryAvailableOwners->bind_param('ii', $iduserlogin, $idhome);
$queryAvailableOwners->execute();
$resultAvailableOwners = $queryAvailableOwners->get_result();
?>
<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title>Assegna Proprietari</title>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/css/icons.css" rel="stylesheet" type="text/css">
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</head>

<body class="fixed-left">
    <div id="wrapper">
        <?php include('include/navigationbar.php'); ?>

        <div class="content-page">
            <div class="content">
                <?php include('include/topbar.php'); ?>
                <br>
                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <!-- Dettagli dell'immobile -->
                        <div class="card mb-4">
                            <div class="card-header bg-warning text-white">
                                <h4 class="mb-0"><?php echo htmlspecialchars($homeDetails['name']); ?></h4>
                                <span class="badge bg-info text-primary">
                                    <?php echo htmlspecialchars($homeDetails['address'] . ', ' . $homeDetails['zip'] . ', ' . $homeDetails['city'] . ', ' . $homeDetails['country']); ?>
                                </span>
                            </div>
                        </div>
                        <!-- Proprietari associati -->
                        <div class="card mb-4">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">Proprietari</h5>
                            </div>
                            <div class="card-body">
                                <?php if ($resultOwners->num_rows > 0) { ?>
                                    <div id="ownersTable">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Nome</th>
                                                    <th>Codice Fiscale</th>
                                                    <th>%</th>
                                                    <th>Note</th>
                                                    <th>Azioni</th>
                                                </tr>
                                            </thead>
                                            <tbody id="ownersTableBody">
                                                <?php
                                                $totalPercentage = 0;
                                                while ($owner = $resultOwners->fetch_assoc()) {
                                                    $totalPercentage += $owner['ownership_percentage'];
                                                    echo "<tr>
                    <td>" . htmlspecialchars($owner['first_name'] . ' ' . $owner['last_name']) . "</td>
                    <td>" . htmlspecialchars($owner['tax_code']) . "</td>
                    <td class='ownership-percentage'>" . htmlspecialchars($owner['ownership_percentage']) . "</td>
                    <td>" . htmlspecialchars($owner['notes']) . "</td>
                    <td>
                        <button class='btn btn-danger btn-sm remove-owner-btn' data-id='" . $owner['owner_id'] . "'>
                            <i class='fas fa-trash-alt'></i> Rimuovi
                        </button>
                    </td>
                </tr>";
                                                }
                                                ?>
                                            </tbody>
                                            <tfoot>
                                                <tr>
                                                    <td colspan="2"><strong>Totale % Proprietà:</strong></td>
                                                    <td id="totalOwnership" class="font-weight-bold text-center"><?php echo $totalPercentage; ?>%</td>
                                                    <td colspan="2"></td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>

                                <?php } else { ?>
                                    <p class="text-muted">Nessun proprietario associato.</p>
                                <?php } ?>
                            </div>
                        </div>

                        <!-- Aggiungi proprietari -->
                        <?php if (!$disableEditing) { ?>
                            <div class="card mb-4">
                                <div class="card-header bg-info text-white">
                                    <h5 class="mb-0">Assegna Proprietari</h5>
                                </div>
                                <div class="card-body">
                                    <form id="addOwnerForm" method="POST" action="add-owner-to-home.php">
                                        <input type="hidden" name="idhome" value="<?php echo $idhome; ?>">
                                        <div class="form-group">
                                            <label for="ownerSelect">Seleziona Proprietario</label>
                                            <select class="form-control" id="ownerSelect" name="owner_id" required>
                                                <option value="">-- Seleziona --</option>
                                                <?php while ($availableOwner = $resultAvailableOwners->fetch_assoc()) { ?>
                                                    <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 } ?>
                                                <option value="new_owner">➕ Aggiungi nuovo proprietario</option>
                                            </select>
                                        </div>


                                        <div class="form-group">
                                            <label for="ownershipPercentage">Percentuale di Proprietà</label>
                                            <input type="number" step="0.01" class="form-control" id="ownershipPercentage"
                                                name="ownership_percentage" placeholder="Inserisci la percentuale (es. 50.00)"
                                                oninput="validatePercentage()" required>
                                        </div>
                                        <div class="form-group">
                                            <label for="notes">Note</label>
                                            <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Aggiungi eventuali note"></textarea>
                                        </div>
                                        <!-- Messaggio di errore -->
                                        <small id="percentageError" class="text-danger" style="display:none;">La somma totale non può superare il 100%.</small>
                                        <button type="submit" id="addOwnerBtn" class="btn btn-success mt-3">Aggiungi</button>
                                    </form>
                                </div>
                            </div>
                        <?php } ?>

                        <div class="mb-3">
                            <button onclick="history.back()" class="btn btn-dark">
                                <i class="fas fa-arrow-left"></i> Torna indietro
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <?php include('include/footer.php'); ?>
        </div>
    </div>
    <!-- Modal Aggiungi Nuovo Proprietario -->
    <div class="modal fade" id="newOwnerModal" tabindex="-1" aria-labelledby="newOwnerModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg"> <!-- Più largo per migliorare la leggibilità -->
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="newOwnerModalLabel">Aggiungi Nuovo Proprietario</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="newOwnerForm">
                        <input type="hidden" name="user_id" value="<?php echo $iduserlogin; ?>">

                        <div class="row">
                            <!-- Tipo Proprietario -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="ownerType">Tipo Proprietario</label>
                                    <select class="form-control" id="ownerType" name="owner_type" required>
                                        <option value="individual">Persona Fisica</option>
                                        <option value="company">Azienda</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Codice Fiscale / P. IVA -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="taxCode">Codice Fiscale / Partita IVA</label>
                                    <input type="text" class="form-control" id="taxCode" name="tax_code" required>
                                </div>
                            </div>

                            <!-- Nome -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="firstName">Nome</label>
                                    <input type="text" class="form-control" id="firstName" name="first_name">
                                </div>
                            </div>

                            <!-- Cognome -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="lastName">Cognome</label>
                                    <input type="text" class="form-control" id="lastName" name="last_name">
                                </div>
                            </div>

                            <!-- Nome Azienda -->
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="companyName">Nome Azienda</label>
                                    <input type="text" class="form-control" id="companyName" name="company_name" disabled>
                                </div>
                            </div>

                            <!-- Email -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email">Email</label>
                                    <input type="email" class="form-control" id="email" name="email" required>
                                </div>
                            </div>

                            <!-- Telefono -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="phone">Telefono</label>
                                    <input type="text" class="form-control" id="phone" name="phone">
                                </div>
                            </div>

                            <!-- Indirizzo -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="address">Indirizzo</label>
                                    <input type="text" class="form-control" id="address" name="address">
                                </div>
                            </div>

                            <!-- CAP -->
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="postalCode">CAP</label>
                                    <input type="text" class="form-control" id="postalCode" name="postal_code">
                                </div>
                            </div>

                            <!-- Città -->
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="city">Città</label>
                                    <input type="text" class="form-control" id="city" name="city">
                                </div>
                            </div>

                            <!-- Provincia -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="province">Provincia</label>
                                    <input type="text" class="form-control" id="province" name="province">
                                </div>
                            </div>

                            <!-- Nazione (Select2) -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="country">Nazione</label>
                                    <select class="form-control" id="country" name="country">
                                        <option value="">-- Seleziona --</option>
                                        <?php
                                        $queryCountries = $conn->query("SELECT id, name FROM auth_countries ORDER BY name");
                                        while ($country = $queryCountries->fetch_assoc()) {
                                            echo "<option value='{$country['id']}'>" . htmlspecialchars($country['name']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>

                            <!-- Ruolo -->
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="role">Ruolo</label>
                                    <input type="text" class="form-control" id="role" name="role">
                                </div>
                            </div>

                            <!-- Note -->
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="notes">Note</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                                </div>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-success">Salva Proprietario</button>
                    </form>
                </div>
            </div>
        </div>
    </div>



    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <!-- Include Select2 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

    <script>
        $(document).ready(function() {
            // Attiva Select2 per il campo "Nazione"
            $("#country").select2({
                width: '100%',
                placeholder: "Seleziona un paese...",
                allowClear: true
            });

            // Selezione del proprietario nel dropdown
            $("#ownerSelect").change(function() {
                if ($(this).val() === "new_owner") {
                    $("#newOwnerModal").modal("show"); // Apri il modale
                    $(this).val(""); // Resetta il valore del dropdown
                }
            });

            // Abilita/disabilita i campi in base al tipo di proprietario
            $("#ownerType").change(function() {
                if ($(this).val() === "company") {
                    $("#companyName").prop("disabled", false);
                    $("#firstName, #lastName").prop("disabled", true).val("");
                } else {
                    $("#companyName").prop("disabled", true).val("");
                    $("#firstName, #lastName").prop("disabled", false);
                }
            });

            // Invio dati AJAX per aggiungere il nuovo proprietario
            $("#newOwnerForm").submit(function(e) {
                e.preventDefault(); // Evita il refresh della pagina
                let formData = $(this).serialize();

                $.post("add-new-owner.php", formData, function(response) {
                    let result = JSON.parse(response);

                    if (result.success) {
                        Swal.fire({
                            icon: "success",
                            title: "Proprietario aggiunto!",
                            text: result.message,
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            $("#newOwnerModal").modal("hide"); // Chiudi il modale

                            // Aggiungi il nuovo proprietario al dropdown
                            $("#ownerSelect").prepend(`<option value="${result.owner_id}" selected>
                        ${result.owner_name} - ${result.tax_code}
                    </option>`);
                        });
                    } else {
                        Swal.fire({
                            icon: "error",
                            title: "Errore!",
                            text: result.message
                        });
                    }
                }).fail(function() {
                    Swal.fire({
                        icon: "error",
                        title: "Errore!",
                        text: "Si è verificato un problema."
                    });
                });
            });
        });
    </script>



    <script>
        document.addEventListener("DOMContentLoaded", function() {
            function getTotalOwnership() {
                let total = 0;
                document.querySelectorAll(".ownership-percentage").forEach(function(el) {
                    total += parseFloat(el.textContent) || 0;
                });
                return total;
            }

            function validatePercentage() {
                let totalOwnership = getTotalOwnership();
                let newPercentage = parseFloat(document.getElementById("ownershipPercentage").value) || 0;
                let remainingPercentage = 100 - totalOwnership;

                let errorMsg = document.getElementById("percentageError");
                let submitBtn = document.getElementById("addOwnerBtn");

                if (newPercentage > remainingPercentage) {
                    errorMsg.style.display = "block";
                    submitBtn.disabled = true;
                } else {
                    errorMsg.style.display = "none";
                    submitBtn.disabled = false;
                }
            }

            // Disabilita il form se già 100%
            let addOwnerForm = document.getElementById("addOwnerForm");
            let addOwnerBtn = document.getElementById("addOwnerBtn");
            if (getTotalOwnership() >= 100) {
                addOwnerForm.style.display = "none";
                document.getElementById("totalOwnership").style.backgroundColor = "#28a745"; // Verde
                document.getElementById("totalOwnership").style.color = "#fff";
            }
        });
    </script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            let totalOwnership = 0;

            // Somma tutte le percentuali di proprietà
            document.querySelectorAll(".ownership-percentage").forEach(function(el) {
                totalOwnership += parseFloat(el.textContent) || 0;
            });

            // Seleziona il campo nel footer
            let totalCell = document.getElementById("totalOwnership");

            // Imposta il valore e il colore di sfondo in base al totale
            totalCell.textContent = totalOwnership.toFixed(2) + "%";
            if (totalOwnership >= 100) {
                totalCell.style.backgroundColor = "#28a745"; // Verde
                totalCell.style.color = "#fff";
            } else {
                totalCell.style.backgroundColor = "#ffc107"; // Arancione
                totalCell.style.color = "#212529";
            }
        });
    </script>


    <script>
        $(document).on('click', '.remove-owner-btn', function() {
            const ownerId = $(this).data('id');
            const idhome = "<?php echo $idhome; ?>";

            Swal.fire({
                title: 'Sei sicuro?',
                text: 'Questa azione rimuoverà il proprietario selezionato.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Sì, rimuovi',
                cancelButtonText: 'Annulla',
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('remove-owner-from-home.php', {
                        owner_id: ownerId,
                        idhome: idhome
                    }, function(response) {
                        try {
                            const result = JSON.parse(response);
                            if (result.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Rimosso',
                                    text: result.message,
                                    timer: 1500,
                                    showConfirmButton: false,
                                }).then(() => {
                                    location.reload(); // Ricarica la pagina
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Errore',
                                    text: result.message,
                                });
                            }
                        } catch (error) {
                            console.error('Errore di parsing JSON:', error);
                            Swal.fire({
                                icon: 'error',
                                title: 'Errore',
                                text: 'Si è verificato un problema.',
                            });
                        }
                    }).fail(function() {
                        Swal.fire({
                            icon: 'error',
                            title: 'Errore',
                            text: 'Impossibile completare la richiesta.',
                        });
                    });
                }
            });
        });
    </script>
    <script>
        document.getElementById("addOwnerForm").addEventListener("submit", function(e) {
            e.preventDefault(); // Previene il refresh della pagina

            let formData = new FormData(this);

            fetch("add-owner-to-home.php", {
                    method: "POST",
                    body: formData,
                })
                .then(response => response.json()) // Converti la risposta in JSON
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            icon: "success",
                            title: "Proprietario aggiunto!",
                            text: data.message,
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            // Aggiorna la tabella dei proprietari
                            fetch("get-owners.php?idhome=<?php echo $idhome; ?>")
                                .then(response => response.text())
                                .then(html => {
                                    document.getElementById("ownersTable").innerHTML = html;
                                });

                            // **Aggiorna il dropdown con i proprietari disponibili**
                            fetch("get-available-owners.php?idhome=<?php echo $idhome; ?>")
                                .then(response => response.text())
                                .then(html => {
                                    document.getElementById("ownerSelectContainer").innerHTML = html;
                                });

                            // Resetta il form
                            document.getElementById("addOwnerForm").reset();
                        });
                    } else {
                        Swal.fire({
                            icon: "error",
                            title: "Errore!",
                            text: data.message
                        });
                    }
                })
                .catch(error => {
                    console.error("Errore AJAX:", error);
                    Swal.fire({
                        icon: "error",
                        title: "Errore!",
                        text: "Si è verificato un problema con la richiesta."
                    });
                });
        });
    </script>
    <script>
        function validatePercentage() {
            let totalOwnership = 0;
            document.querySelectorAll(".ownership-percentage").forEach(function(el) {
                totalOwnership += parseFloat(el.textContent) || 0;
            });

            let newPercentage = parseFloat(document.getElementById("ownershipPercentage").value) || 0;
            let remainingPercentage = 100 - totalOwnership;

            let errorMsg = document.getElementById("percentageError");
            let submitBtn = document.getElementById("addOwnerBtn");

            if (newPercentage > remainingPercentage) {
                errorMsg.style.display = "block";
                submitBtn.disabled = true;
            } else {
                errorMsg.style.display = "none";
                submitBtn.disabled = false;
            }
        }
    </script>
</body>

</html>