<?PHP
#
#   FILE:  DeleteFolder.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2012 Internet Scout Project
#   http://scout.wisc.edu/
#

# ----- MAIN -----------------------------------------------------------------

# check authorization and setup HTML suppression and page redirection
if (!Folders_Common::ApiPageCompletion("P_Folders_ManageFolders")) return;

# canceled deletion
if (GetArrayValue($_GET, "Cancel"))
{
    return;
}

$FolderId = GetArrayValue($_GET, "FolderId");

# can't do anything if there isn't a folder ID to work with
if (!strlen($FolderId))
{
    return;
}

try
{
    $FolderFactory = new Folders_FolderFactory($User->Id());
    $ResourceFolder = $FolderFactory->GetResourceFolder();
    $Folder = new Folders_Folder($FolderId);

    # delete the folder only if the resource folder contains this folder, which
    # implies that the user owns the folder and it's a valid folder of resources
    if ($ResourceFolder->ContainsItem($Folder->Id()))
    {
        $CurrentFolder = $FolderFactory->GetSelectedFolder();
        $TgtIsCurrent = $CurrentFolder->Id() == $Folder->Id();

        $ResourceFolder->RemoveItem($Folder->Id());
        $Folder->Delete();

        $FolderIds = $ResourceFolder->GetItemIds();

        # select the next folder if available
        if (count($FolderIds) && $TgtIsCurrent)
        {
            $NewCurrentFolder = new Folders_Folder(array_shift($FolderIds));
            $FolderFactory->SelectFolder($NewCurrentFolder);
        }
    }
} catch (Exception $Exception) {}
