<?php include('include/headscript.php'); ?>

<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

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

// Recupera l'idhome dalla query string
$idhome = isset($_GET['idhome']) ? intval($_GET['idhome']) : 0;

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

// Recupera tutte le condivisioni per l'immobile specifico
$querySharing = $conn->prepare("
    SELECT 
        hs.*, 
        sr.role_name
    FROM home_sharing hs
    LEFT JOIN sharing_roles sr ON hs.role_id = sr.idrole
    WHERE hs.idhome = ?
    ORDER BY hs.created_at DESC
");
$querySharing->bind_param('i', $idhome);
$querySharing->execute();
$resultSharing = $querySharing->get_result();
$sharings = [];

while ($row = $resultSharing->fetch_assoc()) {
    // Decode JSON sections
    $sharedSections = json_decode($row['shared_sections'], true) ?: [];
    if (!empty($sharedSections)) {
        // Match section IDs with names from the `sections` table
        $placeholders = implode(',', array_fill(0, count($sharedSections), '?'));
        $sectionQuery = $conn->prepare("SELECT section_name FROM sections WHERE idsections IN ($placeholders)");
        $sectionQuery->bind_param(str_repeat('i', count($sharedSections)), ...$sharedSections);
        $sectionQuery->execute();
        $sectionResult = $sectionQuery->get_result();
        $sectionNames = $sectionResult->fetch_all(MYSQLI_ASSOC);
        $row['section_names'] = array_column($sectionNames, 'section_name');
    } else {
        $row['section_names'] = ['Tutte le sezioni'];
    }
    $sharings[] = $row;
}

$queryHome->close();
$querySharing->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title>Gestione Condivisioni</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">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
</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">
                        <br>
                        <div class="row align-items-center mb-3">
                            <div class="col-sm-8">
                                <h4 class="page-title m-0">Condivisioni per l'immobile</h4>
                                <p class="mb-0"><strong>Dettagli immobile:</strong> <?php echo htmlspecialchars($homeDetails['address']); ?></p>
                            </div>
                            <div class="col-sm-4 text-right">

                                <a href="add-sharing.php?idhome=<?php echo $idhome; ?>" class="btn btn-success">
                                    <i class="mdi mdi-plus"></i> Aggiungi Condivisione
                                </a>
                                <a href="javascript:history.back()" class="btn btn-dark mr-2">
                                    <i class="mdi mdi-arrow-left"></i> Torna Indietro
                                </a>
                            </div>
                        </div>


                        <!-- Tabella delle condivisioni -->
                        <table id="sharingTable" class="table table-striped table-bordered">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Email</th>
                                    <th>Ruolo</th>
                                    <th>Tipologia</th>
                                    <th>Sezioni</th>
                                    <th>Scadenza</th>
                                    <th>Azioni</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sharings as $sharing) { ?>
                                    <tr>
                                        <td><?php echo $sharing['idsharing']; ?></td>
                                        <td><?php echo htmlspecialchars($sharing['shared_email']); ?></td>
                                        <td><?php echo htmlspecialchars($sharing['role_name'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($sharing['sharing_type']); ?></td>
                                        <td>
                                            <?php echo implode(', ', $sharing['section_names']); ?>
                                        </td>
                                        <td><?php echo $sharing['expiration_date'] ?: 'Senza scadenza'; ?></td>
                                        <td>
                                            <a href="edit-sharing.php?idsharing=<?php echo $sharing['idsharing']; ?>" class="btn btn-warning btn-sm">
                                                <i class="mdi mdi-pencil"></i>
                                            </a>
                                            <button class="btn btn-danger btn-sm" onclick="confirmDelete(<?php echo $sharing['idsharing']; ?>)">
                                                <i class="mdi mdi-delete"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php } ?>
                            </tbody>
                        </table>

                    </div>
                </div>
            </div>
            <?php include('include/footer.php'); ?>
        </div>
    </div>

    <!-- SweetAlert -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.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>
        $(document).ready(function() {
            $('#sharingTable').DataTable();
        });

        function confirmDelete(idsharing) {
            Swal.fire({
                title: 'Sei sicuro?',
                text: "Questa azione rimuoverà la condivisione in modo permanente.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Sì, elimina',
                cancelButtonText: 'Annulla'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Effettua la richiesta per eliminare
                    $.ajax({
                        url: `delete-sharing.php?idsharing=${idsharing}`,
                        type: 'GET',
                        success: function(response) {
                            Swal.fire(
                                'Eliminato!',
                                'La condivisione è stata eliminata con successo.',
                                'success'
                            ).then(() => {
                                // Ricarica la pagina
                                location.reload();
                            });
                        },
                        error: function() {
                            Swal.fire(
                                'Errore!',
                                'Si è verificato un problema durante l\'eliminazione.',
                                'error'
                            );
                        }
                    });
                }
            });
        }
    </script>
</body>

</html>