<?php
if ( !$user['superAdmin'] ) {
    session_start();
    $_SESSION['error'] = 'Unauthorized';

    header('Location: '.URL_APP_ADMIN);
    exit;
}

if ( !is_array($_POST['publicProjects']) || count($_POST['publicProjects']) < 1 ) {
    session_start();
    $_SESSION['error'] = 'Choose at least one public project';

    header('Location: '.URL_APP_ADMIN.'/?page=pp');
    exit;
}

if ( !$_POST['note'] ) {
    session_start();
    $_SESSION['error'] = 'A note is required';

    header('Location: '.URL_APP_ADMIN.'/?page=pp');
    exit;
}

// if ( !in_array($_POST['shareLifetime'], $whitelist) ) {
//     session_start();
//     $_SESSION['error'] = 'Select a valid share lifetime';

//     header('Location: '.URL_APP_ADMIN.'/?page=pp');
//     exit;
// }

$now   = date('Y-m-d H:i:s');
$uri = generate_id(time(), 10);

$db->insert('share', [
    'uri' => $uri,
    'note' => $_POST['note'],
    'createdBy' => $user['id'],
    'createdAt' => $now,
    'expiresAt' => date('Y-m-d H:i:s', strtotime('+'.PUBLIC_PROJECT_SHARE_LINK_LIFETIME, strtotime($now)))
]);

$shareId = $db->cell("SELECT id FROM share WHERE uri = ? AND note = ? AND createdBy = ? and createdAt = ?", $uri, $_POST['note'], $user['id'], $now);

foreach ( $_POST['publicProjects'] as $publicProjectId ) {
    if ( !$publicProject = $db->row("SELECT * FROM public_project WHERE id = ?", $publicProjectId) ) {
        session_start();
        $_SESSION['error'] = 'Invalid public project ID';

        header('Location: '.URL_APP_ADMIN.'/?page=pp');
        exit;
    }

    $db->insert('public_project_share', [
        'publicProjectId' => $publicProjectId,
        'shareId' => $shareId,
    ]);
}

session_start();
$_SESSION['error'] = 'Public project share link created';

header('Location: '.URL_APP_ADMIN.'/?page=pp');
exit;