<?PHP
#
#   FILE:  Edit.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2014 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

$MyPlugin = $GLOBALS["G_PluginManager"]->GetPlugin("BatchEdit");

# make sure the user is allowed to do batch editing
CheckAuthorization($MyPlugin->ConfigSetting("RequiredPrivs"));

$H_Folder = new Folders_Folder(intval($_GET["FI"]));

# iterate over the items in this folder, determining which schemas
# they belong to
$H_Schemas = array();
foreach ($H_Folder->GetItemIds() as $ResourceId)
{
    $Resource = new Resource($ResourceId);
    $SchemaId = $Resource->SchemaId();

    if (!isset($H_Schemas[$SchemaId]))
    {
        $H_Schemas[$SchemaId] = new MetadataSchema($SchemaId);
    }
}
ksort($H_Schemas);

# iterate over our schemas, constructing an editing interface for each
#  of them
$H_Editors = array();
foreach ($H_Schemas as $SchemaId => $Schema)
{
    $H_Editors[$SchemaId] = new FieldEditingUI(
        "FEUI".$SchemaId, $SchemaId);
    $H_Editors[$SchemaId]->AddFieldButton(
        "Add Field", $MyPlugin->ConfigSetting("AllowedFields"));
}

$H_ChangedResources = array();
if (isset($_POST["Submit"]) && $_POST["Submit"] == "Apply All Changes")
{
    # iterate through all our editing forms, pulling out the change
    # data for each
    $ChangeData = array();
    foreach ($H_Schemas as $SchemaId => $Schema)
    {
        $ChangeData[$SchemaId] =
                $H_Editors[$SchemaId]->GetValuesFromFormData();
    }

    # iterate through all the items in this folder
    foreach ($H_Folder->GetItemIds() as $ResourceId)
    {
        $Resource = new Resource($ResourceId);

        # if we have any changes for resources in this schema
        if (count($ChangeData[$Resource->SchemaId()]))
        {
            # apply them to this resource
            $WasChanged = FieldEditingUI::ApplyChangesToResource(
                $Resource, $GLOBALS["G_User"],
                $ChangeData[$Resource->SchemaId()]);

            # and if anything was modified by the changes,
            # note that this resource was tweaked
            if ($WasChanged)
            {
                $H_ChangedResources[]= $Resource;
            }
        }
    }
}
