<?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);


$redirect = ( $user['superAdmin'] )
    ? URL_APP_ADMIN
    : URL_APP
;

if ( !isset($_POST['groupId']) ) {
$txt .= "group id not set\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-group.log', "a");
fwrite($file, $txt);
fclose($file);

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

    header('Location: '.$redirect);
    exit;
}

if ( !$group = $db->row("SELECT * FROM selection_group WHERE id = ?", $_POST['groupId']) ) {
$txt .= "no group by id\n";
$file = fopen(PATH_LOGS.'/btb.edit-selection-group.log', "a");
fwrite($file, $txt);
fclose($file);
    session_start();
    $_SESSION['error'] = 'Invalid group ID';

    header('Location: '.$redirect);
    exit;
}

$txt .= "group before update:\n";
$txt .= print_r($group, true);

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

        session_start();
        $_SESSION['error'] = 'You do not have permission to edit this group';

        header('Location: '.$redirect);
        exit;
    }
}

$db->update('selection_group', ['title' => $_POST['title'], 'description' => $_POST['description']], ['id' => $group['id']]);

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

session_start();
$_SESSION['error'] = 'Group updated';
header('Location: '.URL_APP.'/selections/?projectId='.$group['projectId']);
exit;
