<?php
$datetime = date("Y-m-d H:i:s");
$txt  = "\n$datetime - ".$_SERVER['PHP_SELF']."\n";
$txt .= "user:\n";
$txt .= print_r($user, true);
$txt .= "post:\n";
$txt .= print_r($_POST , true);

if ( !$user['superAdmin'] ) {
    if ( !$exists = $db->cell("SELECT id FROM client_project WHERE clientId = ? AND projectId = ?", $user['client']['id'], $_POST['projectId']) ) {
$txt .= "user does not have permission to create groups\n";
$file = fopen(PATH_LOGS.'/btb.new-selection-groups.log', "a");
fwrite($file, $txt);
fclose($file);

        session_start();
        $_SESSION['error'] = 'You do not have permission to create groups';

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

if ( !isset($_POST['projectId']) ) {
$txt .= "no project id provided\n";
$file = fopen(PATH_LOGS.'/btb.new-selection-groups.log', "a");
fwrite($file, $txt);
fclose($file);

    session_start();
    $_SESSION['error'] = 'No project ID';

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

if ( !$project = $db->row("SELECT * FROM project WHERE id = ?", $_POST['projectId']) ) {
$txt .= "no project by that id\n";
$file = fopen(PATH_LOGS.'/btb.new-selection-groups.log', "a");
fwrite($file, $txt);
fclose($file);

    session_start();
    $_SESSION['error'] = 'Invalid project ID';

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

$groups = [];
$num = max(array_keys($_POST['selectionText']));
for ( $i = 0; $i <= $num; $i++ ) {
    if ( isset($_POST['selectionCheck'][$i]) && $_POST['selectionText'][$i] ) {
        $groups[] = $_POST['selectionText'][$i];
    }
}

if ( isset($_POST['selectionDefaultCheck']) ) {
    for ( $i = 0; $i < count($_POST['selectionDefaultCheck']); $i++ ) {
        $groups[] = $_POST['selectionDefaultCheck'][$i];
    }
}

foreach ( $groups as $group ) {
    $db->insert('selection_group', [
        'projectId' => $_POST['projectId'],
        'title' => $group,
        'description' => $group,
        'createdBy' => $user['id'],
        'createdAt' => date('Y-m-d H:i:s')
    ]);

    $txt .= "group inserted:\n";
    $txt .= print_r($group, true);
}

$txt .= "done\n\n\n\n";
$file = fopen(PATH_LOGS.'/btb.new-selection-groups.log', "a");
fwrite($file, $txt);
fclose($file);

session_start();
$_SESSION['error'] = 'Group(s) added';

header('Location: '.URL_APP.'/selections/?projectId='.$_POST['projectId']);
exit;