<?php
    if ( !$user['superAdmin'] ) {
        exit;
    }

    if ( $shareId = $_POST['id'] ) {
        $share = $db->row("SELECT * FROM share WHERE id = ?", $shareId);
        $ids   = $db->run("SELECT * FROM public_project_share WHERE shareId = ?", $share['id']);
        foreach ( $ids as $id ) {
            $share['publicProjects'][] = $db->row("SELECT * FROM public_project WHERE id = ?", $id['publicProjectId']);
        }

        $publicProjects = $db->run("SELECT * FROM public_project");
    } else {
        exit;
    }

    if ( $share ) :
?>
        <div class="mx-1 mb-2" id="sharePublicProject">
            <select name="publicProjects[]" class="selectpicker my-1" multiple data-live-search="true" title="Select public projects" data-selected-text-format="count > 2" data-width="100%" data-actions-box="true" required>
                <?php 
                    foreach ( $publicProjects as $publicProject ) :
                        if ( in_array($publicProject['id'], array_column($share['publicProjects'], 'id')) ) {
                            $selected = 'selected';
                        } else {
                            $selected = '';
                        }
                ?>
                        <option value="<?php echo $publicProject['id']; ?>" <?php echo $selected; ?>><?php echo $publicProject['title']; ?></option>
                <?php
                    endforeach; 
                ?>
            </select>
        </div>
        <div class="form-floating mb-2">
            <input type="text" name="note" class="form-control" id="note" value="<?php echo htmlspecialchars($share['note']); ?>" required>
            <label for="note">Note (e.g. "Jane at TN National")</label>
        </div>
        <input type="hidden" name="shareId" id="shareId" value="<?php echo $share['id']; ?>">
<?php
    endif;
?>