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

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

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

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

    # move the item only if it's the resource folder or the resource folder
    # contains this folder, which implies that the user owns the folder and it's
    # a valid folder of resources
    if ($IsResourceFolder || $ResourceFolder->ContainsItem($Folder->Id()))
    {
        if ($Folder->ContainsItem($ItemId))
        {
            # if given a target ID, move the item after it
            if ($TargetItemId && $Folder->ContainsItem($TargetItemId))
            {
                $Folder->InsertItemAfter($TargetItemId, $ItemId);
            }

            # otherwise just add it to the beginning of the list
            else
            {
                $Folder->PrependItem($ItemId);
            }
        }
    }
} catch (Exception $Exception) {}
