<?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 -----------------------------------------------------------------

# we can't do anything without a valid item ID and want to avoid
# processing other parts of the page if we don't have one.

$Resource = new Resource($ItemId);
# if the above resource creation is unsuccessful, the constructor in Resource
# sets the status of the resource to -1, which we take advantage of here:
if ($Resource->Status() == -1)
{
    # invalid item Id
    array_push($Errors, 'E_FOLDERS_NOSUCHITEM');
}
else
{
    # 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()))
    {
        if ($Resource->Status() === 1)
        {
            # last operation was successful?
            $Folder->AppendItem($Resource->Id());
        }
        else
        {
            # resource couldn't be found in the database
            array_push($Errors, 'E_FOLDERS_RESOURCENOTFOUND');
        }
    }
    else
    {
        # user doesn't own the folder
        array_push($Errors, 'E_FOLDERS_NOTFOLDEROWNER');
    }
}

# ----- 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());
