<?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 .= "get:\n";
$txt .= print_r($_GET, true);

if ( !isset($_GET['itemId']) ) {
$txt .= "no item id\n";
$file = fopen(PATH_LOGS.'/btb.delete-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

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

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

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

    session_start();
    $_SESSION['error'] = 'No item by that ID';

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

if ( !$user['superAdmin'] || $user['id'] !== $selection['createdBy'] ) {
$txt .= "not super admin or not item creator\n";
$file = fopen(PATH_LOGS.'/btb.delete-selection-item.log', "a");
fwrite($file, $txt);
fclose($file);

    session_start();
    $_SESSION['error'] = 'You do not have permission to delete that selection item';

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

$txt .= "item before delete:\n";
$txt .= print_r($selection, true);

$db->delete('selection_item', ['id' => $_GET['itemId']]);
$txt .= "item deleted\n";

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

session_start();
$_SESSION['error'] = 'Selection item deleted';

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