<?php include('include/headscript.php'); ?>
<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

// Recupera l'id utente loggato e la sua email
$iduserlogin = $_SESSION['iduserlogin'];
$emailuser = $_SESSION['emailuser'];

// Query per ottenere gli immobili condivisi con l'utente loggato
$sql = "
SELECT 
    hs.idhome, 
    h.name, 
    h.address, 
    h.zip, 
    h.city, 
    h.country,
    h.mainphoto,
    hs.sharing_type,
    hs.expiration_date,
    au.first_name,
    au.last_name,
    COUNT(ho.owner_id) AS owner_count,
    SUM(ho.ownership_percentage) AS total_ownership,
    GROUP_CONCAT(
        CASE 
            WHEN po.owner_type = 'individual' 
            THEN CONCAT(po.first_name, ' ', po.last_name, ' (', ho.ownership_percentage, '%)')
            ELSE CONCAT(po.company_name, ' (', ho.ownership_percentage, '%)')
        END
        SEPARATOR '\n'
    ) AS owner_names
FROM home_sharing hs
LEFT JOIN home h ON hs.idhome = h.idhome
LEFT JOIN auth_users au ON hs.iduser = au.id
LEFT JOIN home_owners ho ON hs.idhome = ho.home_id
LEFT JOIN property_owners po ON ho.owner_id = po.owner_id
WHERE 
    (hs.idshareduser = ? OR hs.shared_email = ?) 
    AND hs.status = 'accepted'
GROUP BY 
    hs.idhome, 
    h.name, 
    h.address, 
    h.zip, 
    h.city, 
    h.country, 
    hs.sharing_type,
    hs.expiration_date,
    au.first_name,
    au.last_name;
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('is', $iduserlogin, $emailuser);
$stmt->execute();
$result = $stmt->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">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Immobili Condivisi</title>

    <!-- Bootstrap 4 CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/dripicons/2.0.0/webfont.min.css" rel="stylesheet">

    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- Custom CSS -->
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">
    <link href="assets/css/icons.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://cdn.materialdesignicons.com/5.4.55/css/materialdesignicons.min.css">

    <style>
        /* Stili copiati dalla prima pagina */
        .button-menu-mobile {
            display: inline-block !important;
        }

        @media (min-width: 992px) {
            .button-menu-mobile {
                background-color: transparent;
                border: none;
                padding: 0;
                width: auto;
                height: auto;
            }

            .button-menu-mobile i.ion-close {
                display: none;
            }

            .button-menu-mobile i.mdi-menu {
                display: inline-block;
            }
        }

        @media (max-width: 991.98px) {
            .button-menu-mobile {
                background-color: #ff5e5e;
                border-radius: 50%;
                width: 50px;
                height: 50px;
            }

            .button-menu-mobile i.ion-close {
                display: inline-block;
            }

            .button-menu-mobile i.mdi-menu {
                display: none;
            }
        }

        .btn-main {
            background-color: rgb(96, 93, 175);
            color: #fff;
            border: none;
        }

        .btn-main:hover {
            background-color: #364fc7;
        }

        .btn-secondary {
            background-color: rgb(21, 190, 86);
            color: #212529;
            border: none;
        }

        .btn-secondary:hover {
            background-color: #868e96;
        }

        .btn-info-light {
            background-color: #ffd43b;
            color: #212529;
            border: none;
        }

        .btn-info-light:hover {
            background-color: #fcc419;
        }

        .equal-height {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .equal-height .flex-fill {
            flex: 1;
        }

        #gridView .card {
            border-radius: 10px;
            overflow: hidden;
            transition: transform 0.2s ease-in-out;
        }

        #gridView .card:hover {
            transform: scale(1.03);
        }

        .card-img-top {
            height: 180px;
            object-fit: cover;
        }

        .action-menu {
            position: absolute;
            top: 10px;
            right: 10px;
            display: none;
        }

        .box-home:hover .action-menu {
            display: block;
        }

        .action-toggle {
            border: none;
            background: rgba(255, 255, 255, 0.9);
            padding: 6px 10px;
            width: 32px;
            height: 32px;
            border-radius: 5px;
            box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .action-toggle:hover {
            background: rgba(230, 230, 230, 1);
        }

        .dropdown-menu {
            font-size: 14px;
            min-width: 180px;
        }

        .dropdown-item i {
            margin-right: 8px;
        }

        .img-thumbnail {
            border-radius: 5px;
        }

        td i.fas {
            margin-right: 5px;
        }

        .action-container {
            position: absolute;
            top: 10px;
            left: 10px;
            right: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .owner-btn {
            font-size: 14px;
            padding: 4px 10px;
        }

        .box-home .action-menu {
            opacity: 0;
            transition: opacity 0.3s ease-in-out;
        }

        .box-home:hover .action-menu {
            opacity: 1;
        }

        /* Posiziona il dropdown fuori dalla tabella se necessario */
        .table-responsive .dropdown-menu {
            position: absolute;
            z-index: 1000;
            /* Assicurati che sia sopra altri elementi */
        }

        /* Evita che il dropdown venga tagliato dal table-responsive */
        .table-responsive {
            overflow: visible;
            /* Disattiva l'overflow visibile */
        }

        /* Classe personalizzata per il dropdown delle azioni */
        .dropdown-actions .dropdown-menu {
            min-width: 180px;
            font-size: 14px;
        }

        /* Assicurati che il dropdown non sia nascosto dal contenitore della tabella */
        .dropdown-menu-right {
            right: 0;
            left: auto;
        }

        .dropdown-item.bg-warning {
            background-color: #ffca2c;
            /* Giallo brillante */
            color: #212529;
            /* Testo scuro per contrasto */
        }

        .dropdown-item.bg-warning:hover {
            background-color: #e0b026;
            /* Giallo più scuro al passaggio del mouse */
            color: #212529;
        }
    </style>
</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'); ?>

                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="page-title-box">
                                    <div class="btn-group float-right">
                                        <ol class="breadcrumb hide-phone p-0 m-0">
                                            <li class="breadcrumb-item"><a href="#">CasaDoc</a></li>
                                            <li class="breadcrumb-item active">Immobili Condivisi</li>
                                        </ol>
                                    </div>
                                    <h4 class="page-title">Immobili Condivisi</h4>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-12 d-flex justify-content-start align-items-center gap-3">
                                <button id="toggleViewBtn" class="btn btn-info ms-2">
                                    <i class="fas fa-th-large"></i> Vista Griglia
                                </button>
                            </div>
                        </div>

                        <!-- Table View -->
                        <div id="tableView" style="display: none;">
                            <div class="row">
                                <div class="col-xl-12">
                                    <div class="card">
                                        <div class="card-body">
                                            <div class="table-responsive">
                                                <table id="sharedHomesTable" class="table table-bordered table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th>Foto</th>
                                                            <th>Nome</th>
                                                            <th>Città / Nazione</th>
                                                            <th>Indirizzo</th>
                                                            <th>Proprietari</th>
                                                            <th>Condiviso da</th>
                                                            <th>Data Scadenza</th>
                                                            <th>Azioni</th>
                                                        </tr>
                                                        <tr>
                                                            <th></th>
                                                            <th><input type="text" placeholder="Cerca Nome" class="form-control form-control-sm"></th>
                                                            <th><input type="text" placeholder="Cerca Città" class="form-control form-control-sm"></th>
                                                            <th><input type="text" placeholder="Cerca Indirizzo" class="form-control form-control-sm"></th>
                                                            <th><input type="text" placeholder="Cerca Proprietari" class="form-control form-control-sm"></th>
                                                            <th><input type="text" placeholder="Cerca Condiviso da" class="form-control form-control-sm"></th>
                                                            <th><input type="text" placeholder="Cerca Scadenza" class="form-control form-control-sm"></th>
                                                            <th></th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php while ($row = $result->fetch_assoc()) { ?>
                                                            <tr>
                                                                <td>
                                                                    <img src="mainphoto/<?php echo htmlspecialchars($row['mainphoto'] ?? 'default.jpg'); ?>"
                                                                        class="img-thumbnail open-photo"
                                                                        style="width: 80px; height: 80px; object-fit: cover; cursor: pointer;"
                                                                        alt="<?php echo htmlspecialchars($row['name']); ?>"
                                                                        data-toggle="modal" data-target="#photoModal"
                                                                        data-src="mainphoto/<?php echo htmlspecialchars($row['mainphoto'] ?? 'default.jpg'); ?>">
                                                                </td>
                                                                <td><?php echo htmlspecialchars($row['name']); ?></td>
                                                                <td><?php echo htmlspecialchars($row['city']); ?>, <?php echo htmlspecialchars($row['country']); ?></td>
                                                                <td><?php echo htmlspecialchars($row['address']); ?></td>
                                                                <td>
                                                                    <?php echo nl2br(htmlspecialchars($row['owner_names'])); ?>
                                                                    <br>
                                                                    <?php
                                                                    if ($row['owner_count'] == 0) {
                                                                        $btn_class = "btn-danger";
                                                                        $btn_text = '<i class="fas fa-user-times"></i> Assegna Proprietario';
                                                                    } elseif ($row['total_ownership'] < 100) {
                                                                        $btn_class = "btn-warning";
                                                                        $btn_text = '<i class="fas fa-user-edit"></i> ' . $row['owner_count'] . ' (' . htmlspecialchars($row['total_ownership']) . '%)';
                                                                    } else {
                                                                        $btn_class = "btn-success";
                                                                        $btn_text = '<i class="fas fa-user-check"></i> ' . $row['owner_count'];
                                                                    }
                                                                    ?>
                                                                    <a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn <?php echo $btn_class; ?> btn-sm mt-1">
                                                                        <?php echo $btn_text; ?>
                                                                    </a>
                                                                </td>
                                                                <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></td>
                                                                <td><?php echo $row['expiration_date'] ? htmlspecialchars($row['expiration_date']) : 'Nessuna'; ?></td>
                                                                <td class="text-nowrap">
                                                                    <div class="dropdown dropdown-actions">
                                                                        <!-- Aggiungiamo la classe dropdown-actions per il posizionamento -->
                                                                        <button class="btn btn-light btn-sm dropdown-toggle action-toggle" type="button" data-toggle="dropdown" aria-expanded="false">
                                                                            <i class="fas fa-ellipsis-v"></i>
                                                                        </button>
                                                                        <ul class="dropdown-menu dropdown-menu-right">
                                                                            <li><a class="dropdown-item" href="manage-home.php?idhome=<?php echo $row['idhome']; ?>">
                                                                                    <i class="fas fa-info-circle"></i> Dettagli
                                                                                </a></li>
                                                                            <li><a class="dropdown-item" href="documents-home-shared.php?idhome=<?php echo $row['idhome']; ?>">
                                                                                    <i class="fas fa-folder-open"></i> Documenti
                                                                                </a></li>
                                                                            <li><a class="dropdown-item text-dark bg-warning" href="download-shared-documents.php?idhome=<?php echo $row['idhome']; ?>">
                                                                                    <i class="fas fa-file-archive"></i> Scarica ZIP
                                                                                </a></li>
                                                                            <li><a class="dropdown-item" href="download-report.php?idhome=<?php echo $row['idhome']; ?>">
                                                                                    <i class="fas fa-file-alt"></i> Scarica Report
                                                                                </a></li>
                                                                        </ul>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                        <?php } ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Grid View -->
                        <div id="gridView" style="display: block;">
                            <div class="row">
                                <?php
                                $result->data_seek(0); // Ripristina i dati per la griglia
                                while ($row = $result->fetch_assoc()) { ?>
                                    <div class="col-md-3 col-sm-6 mb-4">
                                        <div class="card shadow-sm border-0 position-relative box-home">
                                            <img src="mainphoto/<?php echo htmlspecialchars($row['mainphoto'] ?? 'default.jpg'); ?>"
                                                class="card-img-top"
                                                alt="<?php echo htmlspecialchars($row['name']); ?>">
                                            <div class="action-container">
                                                <?php
                                                if ($row['owner_count'] == 0) {
                                                    $btn_class = "btn-danger";
                                                } elseif ($row['total_ownership'] < 100) {
                                                    $btn_class = "btn-warning";
                                                } else {
                                                    $btn_class = "btn-success";
                                                }
                                                ?>
                                                <a href="assign-owners.php?idhome=<?php echo $row['idhome']; ?>&editpage=nochange" class="btn <?php echo $btn_class; ?> btn-sm owner-btn">
                                                    <i class="fas fa-user"></i> <?php echo htmlspecialchars($row['owner_count']); ?>
                                                </a>
                                                <div class="dropdown action-menu">
                                                    <button class="btn btn-light btn-sm action-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                        <i class="fas fa-ellipsis-v"></i>
                                                    </button>
                                                    <div class="dropdown-menu dropdown-menu-right">
                                                        <a class="dropdown-item" href="manage-home.php?idhome=<?php echo $row['idhome']; ?>">
                                                            <i class="fas fa-info-circle"></i> Dettagli
                                                        </a>
                                                        <a class="dropdown-item" href="documents-home-shared.php?idhome=<?php echo $row['idhome']; ?>">
                                                            <i class="fas fa-folder-open"></i> Documenti
                                                        </a>
                                                        <a class="dropdown-item text-dark bg-warning" href="download-shared-documents.php?idhome=<?php echo $row['idhome']; ?>">
                                                            <i class="fas fa-file-archive"></i> Scarica ZIP
                                                        </a>
                                                        <a class="dropdown-item" href="download-report.php?idhome=<?php echo $row['idhome']; ?>">
                                                            <i class="fas fa-file-alt"></i> Scarica Report
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="card-body text-center">
                                                <h5 class="card-title"><?php echo htmlspecialchars($row['name']); ?></h5>
                                                <p class="card-text"><?php echo htmlspecialchars($row['address']); ?> - <?php echo htmlspecialchars($row['city']); ?></p>
                                            </div>
                                        </div>
                                    </div>
                                <?php } ?>
                            </div>
                        </div>

                        <div class="mb-3">
                            <button onclick="history.back()" class="btn btn-dark">
                                <i class="fas fa-arrow-left"></i> Torna indietro
                            </button>
                        </div>
                    </div><!-- container -->
                </div><!-- Page content Wrapper -->
            </div><!-- content -->
            <?php include('include/footer.php'); ?>
        </div><!-- End Right content here -->
    </div><!-- END wrapper -->

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
    <script src="assets/js/popper.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="assets/js/modernizr.min.js"></script>
    <script src="assets/js/detect.js"></script>
    <script src="assets/js/fastclick.js"></script>
    <script src="assets/js/jquery.slimscroll.js"></script>
    <script src="assets/js/jquery.blockUI.js"></script>
    <script src="assets/js/waves.js"></script>
    <script src="assets/js/jquery.nicescroll.js"></script>
    <script src="assets/js/jquery.scrollTo.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        $(document).ready(function() {
            var table = $('#sharedHomesTable').DataTable({
                responsive: true,
                autoWidth: false,
                initComplete: function() {
                    // Aggiusta il posizionamento dei dropdown dopo l'inizializzazione
                    this.api().columns().every(function() {
                        var column = this;
                        $('input', column.header()).on('keyup change', function() {
                            if (column.search() !== this.value) {
                                column.search(this.value).draw();
                            }
                        });
                    });
                }
            });

            $("#tableView").hide();
            $("#gridView").show();
            $("#toggleViewBtn").html('<i class="fas fa-list"></i> Vista Elenco');

            $("#toggleViewBtn").click(function() {
                if ($("#tableView").is(":visible")) {
                    $("#tableView").hide();
                    $("#gridView").show();
                    $("#toggleViewBtn").html('<i class="fas fa-list"></i> Vista Elenco');
                } else {
                    $("#gridView").hide();
                    $("#tableView").show();
                    setTimeout(function() {
                        table.columns.adjust().draw();
                        $('#sharedHomesTable').css('width', '100%');
                    }, 200);
                    $("#toggleViewBtn").html('<i class="fas fa-th-large"></i> Vista Griglia');
                }
            });

            // Gestione manuale dei dropdown per evitare conflitti e posizionamento corretto
            $('.action-toggle').on('click', function(e) {
                e.preventDefault();
                var $dropdown = $(this).siblings('.dropdown-menu');
                $('.dropdown-menu').not($dropdown).removeClass('show'); // Chiude gli altri dropdown aperti
                $dropdown.toggleClass('show');

                // Posiziona il dropdown fuori dalla tabella se necessario
                if ($dropdown.hasClass('show')) {
                    var dropdownTop = $(this).offset().top + $(this).outerHeight();
                    var dropdownLeft = $(this).offset().left;
                    $dropdown.css({
                        'position': 'absolute',
                        'top': dropdownTop + 'px',
                        'left': dropdownLeft + 'px',
                        'z-index': 1000
                    });
                }
            });

            // Chiude il dropdown se si clicca fuori
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.dropdown').length) {
                    $('.dropdown-menu').removeClass('show');
                }
            });

            // Chiude il dropdown quando si seleziona un'opzione
            $('.dropdown-menu a').on('click', function() {
                $(this).closest('.dropdown-menu').removeClass('show');
            });
        });

        // Controllo se ci sono documenti allegati
        function checkDocuments() {
            let documents = document.getElementById("fileInput").files; // Supponendo un input file
            if (documents.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Nessun documento presente',
                    text: 'Carica almeno un file per procedere.',
                    confirmButtonText: 'OK'
                });
            } else {
                // Procedi con il caricamento
                console.log("Documenti trovati:", documents);
            }
        }

        // Esempio di HTML per l'input file
        document.write('<input type="file" id="fileInput" multiple>');
        document.write('<button onclick="checkDocuments()">Verifica</button>');

        // Importa la libreria se non l'hai già inclusa
        document.write('<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11">
    </script>');

    </script>
    <!-- Modal per visualizzazione dell'immagine -->
    <div class="modal fade" id="photoModal" tabindex="-1" role="dialog" aria-labelledby="photoModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="photoModalLabel">Foto Immobile</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body text-center">
                    <img id="modalPhoto" src="" class="img-fluid rounded" alt="Immagine immobile">
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            $(".open-photo").on("click", function() {
                let imgSrc = $(this).attr("data-src");
                $("#modalPhoto").attr("src", imgSrc);
            });
        });
    </script>

</body>

</html>