<?php
// Mostra errori per il debug
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include('include/headscript.php');

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

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

// Controlla se l'ID della condivisione è fornito
$idsharing = isset($_GET['idsharing']) ? (int)$_GET['idsharing'] : 0;
if ($idsharing === 0) {
    die("ID condivisione non valido.");
}

// Recupera i dettagli della condivisione con JOIN per ruolo e tipo di condivisione
$query = "
    SELECT 
        hs.idsharing,
        hs.idhome,
        hs.shared_email,
        hs.sharing_type,
        hs.shared_sections,
        hs.expiration_date,
        sr.role_name,
        hs.role_id
    FROM home_Sharing hs
    LEFT JOIN sharing_roles sr ON hs.role_id = sr.idrole
    WHERE hs.idsharing = ?
";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $idsharing);
$stmt->execute();
$result = $stmt->get_result();
$sharing = $result->fetch_assoc();

if (!$sharing) {
    die("Condivisione non trovata.");
}

// Recupera i ruoli di condivisione
$rolesQuery = $conn->query("SELECT idrole, role_name FROM sharing_roles ORDER BY role_name ASC");
$roles = $rolesQuery->fetch_all(MYSQLI_ASSOC);

// Recupera le sezioni dalla tabella 'sections'
$sectionsQuery = $conn->query("SELECT idsections, section_name FROM sections ORDER BY section_name ASC");
$sections = $sectionsQuery->fetch_all(MYSQLI_ASSOC);

// Decode delle sezioni condivise salvate nel database
$shared_sections = json_decode($sharing['shared_sections'], true) ?: [];
?>

<!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>Modifica Condivisione</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.materialdesignicons.com/5.4.55/css/materialdesignicons.min.css">
    <link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
</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-12">
                                <h4 class="page-title"><i class="mdi mdi-share-variant" style="color: #5d6d7e;"></i> Modifica Condivisione</h4>
                                <div class="card shadow-lg">
                                    <div class="card-body">
                                        <form action="save-edit-sharing.php" method="POST">
                                            <!-- Campo nascosto per l'ID condivisione -->
                                            <input type="hidden" name="idsharing" value="<?php echo $sharing['idsharing']; ?>">
                                            <input type="hidden" name="idhome" value="<?php echo $sharing['idhome']; ?>">

                                            <!-- Email -->
                                            <div class="form-group">
                                                <label for="shared_email">
                                                    <i class="mdi mdi-email-outline" style="color: #007bff;"></i> Email condivisa
                                                </label>
                                                <input type="email" name="shared_email" id="shared_email" class="form-control shadow-sm" required
                                                    value="<?php echo htmlspecialchars($sharing['shared_email']); ?>">
                                            </div>

                                            <!-- Ruolo -->
                                            <div class="form-group">
                                                <label for="role_id">
                                                    <i class="mdi mdi-account-cog-outline" style="color: #28a745;"></i> Ruolo
                                                </label>
                                                <select name="role_id" id="role_id" class="form-control shadow-sm" required>
                                                    <option value="">Seleziona un ruolo</option>
                                                    <?php foreach ($roles as $role) { ?>
                                                        <option value="<?php echo $role['idrole']; ?>"
                                                            <?php echo $role['idrole'] == $sharing['role_id'] ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                                        </option>
                                                    <?php } ?>
                                                </select>
                                            </div>

                                            <!-- Tipo di condivisione -->
                                            <div class="form-group">
                                                <label for="sharing_type">
                                                    <i class="mdi mdi-lock-outline" style="color: #ffc107;"></i> Tipo di condivisione
                                                </label>
                                                <select name="sharing_type" id="sharing_type" class="form-control shadow-sm" required>
                                                    <option value="read-only" <?php echo ($sharing['sharing_type'] === 'read-only') ? 'selected' : ''; ?>>Solo lettura</option>
                                                    <option value="add-documents" <?php echo ($sharing['sharing_type'] === 'add-documents') ? 'selected' : ''; ?>>Aggiunta documenti</option>
                                                </select>
                                            </div>

                                            <!-- Sezioni condivise -->
                                            <div class="form-group">
                                                <label>
                                                    <i class="mdi mdi-folder-outline" style="color: #17a2b8;"></i> Sezioni condivise
                                                </label>
                                                <div>
                                                    <?php foreach ($sections as $section) { ?>
                                                        <div class="form-check">
                                                            <input type="checkbox" class="form-check-input shadow-sm"
                                                                name="shared_sections[]"
                                                                value="<?php echo $section['idsections']; ?>"
                                                                <?php echo in_array($section['idsections'], $shared_sections) ? 'checked' : ''; ?>>
                                                            <label class="form-check-label">
                                                                <?php echo htmlspecialchars($section['section_name']); ?>
                                                            </label>
                                                        </div>
                                                    <?php } ?>
                                                </div>
                                            </div>

                                            <!-- Data di scadenza -->
                                            <div class="form-group">
                                                <label for="expiration_date">
                                                    <i class="mdi mdi-calendar-range" style="color: #d9534f;"></i> Data di scadenza
                                                </label>
                                                <input type="text" name="expiration_date" id="expiration_date" class="form-control flatpickr shadow-sm"
                                                    value="<?php echo htmlspecialchars($sharing['expiration_date']); ?>">
                                            </div>

                                            <!-- Pulsanti -->
                                            <div class="form-group text-right">
                                                <button type="submit" class="btn btn-success shadow-sm">
                                                    <i class="mdi mdi-check-circle-outline"></i> Salva
                                                </button>
                                                <a href="share-home.php?idhome=<?php echo $sharing['idhome']; ?>" class="btn btn-secondary shadow-sm">
                                                    <i class="mdi mdi-arrow-left"></i> Annulla
                                                </a>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

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

    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script>
        // Inizializza il calendario per la data di scadenza
        $(".flatpickr").flatpickr({
            enableTime: false,
            dateFormat: "Y-m-d",
            minDate: "today"
        });
    </script>
</body>

</html>