<?PHP
#
#   FILE:  MoveItemToNewFolder.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;

$OldFolderId = GetArrayValue($_GET, "OldFolderId");
$NewFolderId = GetArrayValue($_GET, "NewFolderId");
$ItemId = GetArrayValue($_GET, "ItemId");

# can't do anything if there aren't any valid IDs to work with
if (!strlen($OldFolderId) || !strlen($NewFolderId) || !strlen($ItemId))
{
    return;
}

try
{
    $FolderFactory = new Folders_FolderFactory($User->Id());
    $ResourceFolder = $FolderFactory->GetResourceFolder();
    $OldFolder = new Folders_Folder($OldFolderId);
    $NewFolder = new Folders_Folder($NewFolderId);

    $HasOldFolder = $ResourceFolder->ContainsItem($OldFolder->Id());
    $HasNewFolder = $ResourceFolder->ContainsItem($NewFolder->Id());

    # move the item 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 ($HasOldFolder && $HasNewFolder)
    {
        # make sure the item ID is valid
        if ($OldFolder->ContainsItem($ItemId))
        {
            $OldFolder->RemoveItem($ItemId);
            $NewFolder->PrependItem($ItemId);
        }
    }
} catch (Exception $Exception) {}
