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

# ----- SETUP ----------------------------------------------------------------
# check authorization
if (!Folders_Common::ApiPageCompletion("P_Folders_ManageFolders"))
{
    return;
}

# get the folders plugin
$FoldersPlugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

# set up variables
$ItemId = GetArrayValue($_GET, "ItemId");
$Errors = array();

$FolderId = GetArrayValue($_GET, "FolderId");
$FolderFactory = new Folders_FolderFactory($User->Id());

# get the currently selected folder if no folder ID is given
if ($FolderId === NULL)
{
    $FolderId = $FolderFactory->GetSelectedFolder()->Id();
}

$ResourceFolder = $FolderFactory->GetResourceFolder();
$Folder = new Folders_Folder($FolderId);

PageTitle("Folders - Add Item");

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

# if resource exists
if (Resource::ItemExists($ItemId))
{
    # add 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 ($ResourceFolder->ContainsItem($Folder->Id()))
    {
        # last operation was successful?
        $Folder->AppendItem($ItemId);
    }
    else
    {
        # report that user doesn't own the folder
        array_push($Errors, 'E_FOLDERS_NOTFOLDEROWNER');
    }
}
else
{
    # report invalid item Id
    array_push($Errors, 'E_FOLDERS_NOSUCHITEM');
}

# ----- PAGE ROUTING  -----------------------------------------------------------------
# handle page routing based on the success/failure above.

# This page does not output any HTML
$GLOBALS["AF"]->SuppressHTMLOutput();

$FoldersPlugin->ProcessPageResponse($Errors, ReachedWithAjax());
