<?PHP
#
#   FILE:  EditControlledNameComplete.php
#
#   FUNCTIONS PROVIDED:
#       DisplayControlledNameInfo()
#           - updates or deletes ControlledName fields from ControlledNames
#             and VariantNames, and updates DateLastModified for affected
#             Resources
#
#   FUNCTIONS EXPECTED:
#       None
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

# ----- EXPORTED FUNCTIONS ---------------------------------------------------

# display list of modified controlled names
function DisplayControlledNameList()
{
    global $CNArray;

    foreach($CNArray as $CNName => $CNVariant)
    {
        print $CNName;
        if(!empty($CNVariant))
            print ", Variant ($CNVariant)";
        print "<br>";
    }
}

# display list of deleted controlled names
function DisplayDeletedControlledNameList()
{
    global $CNArray_Delete;

    foreach($CNArray_Delete as $CNName => $CNVariant)
    {
        print $CNName;
        if(!empty($CNVariant))
            print ", Variant ($CNVariant)";
        print "<br>";
    }
}

# display the list of modified resources
function DisplayModifiedResourceList()
{
    global $LinkArray;

    foreach ($LinkArray as $LinkIndex => $LinkString)
    {
        print $LinkString;
    }
}

function ProcessControlledNames()
{
    global $F_ControlledName;
    global $Session;
    global $CNArray;
    global $CNArray_Delete;
    global $CNArray_Delete2;
    global $Submit;
    global $Deferred_Deletion;
    global $Deferred_Remap;

    $CNArray = array();
    $CNArray_Delete = array();

    # we assume that ControlledNameId comes before ControlledName
    for ($i = 0; array_key_exists('F_ControlledNameId_'.$i, $_POST); $i++)
    {
        $ControlledNameId = GetArrayValue($_POST, 'F_ControlledNameId_'.$i);
        $ControlledName = trim(GetArrayValue($_POST, 'F_ControlledName_'.$i));
        $QualifierId = GetArrayValue($_POST, 'F_QualifierName_'.$i);
        $VariantName = GetArrayValue($_POST, 'F_VariantName_'.$i);
        $Remap = trim(GetArrayValue($_POST, 'D_Remap_'.$i));
        $Delete = GetArrayValue($_POST, 'F_Delete_'.$i, FALSE);

        # if "--" selected, set qualifier id = NULL
        if ($QualifierId == "--")
        {
            $QualifierId = NULL;
        }

        # update the values for each controlled name
        if (!empty($ControlledName))
        {
            $CN = new ControlledName($ControlledNameId);

            if ($Delete)
            {
                $CNArray_Delete[$CN->Name()] = $CN->Variant();
                $CNArray_Delete2[] = $ControlledNameId;
                $Deferred_Deletion[] = $CN;
            }

            else
            {
                if (strlen($Remap) > 0)
                {
                    $CNArray[] = $ControlledNameId;
                    $OtherIds = ControlledName::SearchForControlledName(
                        $Remap, $CN->FieldId());

                    if (!empty($OtherIds))
                    {
                        $OtherId = array_shift($OtherIds);
                        $Deferred_Remap[] = array($CN, $OtherId);
                    }
                }
                else
                {
                    if ($CN->Name() != $ControlledName)
                    {
                        $CNArray[] = $ControlledNameId;
                        $CN->Name($ControlledName);
                    }

                    if (!empty($QualifierId))
                    {
                        if ($CN->QualifierId != $QualifierId)
                        {
                            $CNArray[] = $ControlledNameId;
                            $CN->QualifierId($QualifierId);
                        }
                    }

                    if ($CN->Variant() != $VariantName)
                    {
                        $CNArray[] = $ControlledNameId;
                        $CN->Variant($VariantName);
                    }
                }
            }
        }
    }
}

# ----- LOCAL FUNCTIONS ------------------------------------------------------

# update any checked records
function UpdateCheckedValues()
{
    global $Submit;
    global $CNArray;
    global $CNArray_Delete;
    global $CNArray_Delete2;
    global $LinkArray;

    $DB = new SPTDatabase();
    $DB2 = new SPTDatabase();
    $SearchEngine = new SPTSearchEngine();
    $LinkIndex = 0;
    $LinkArray = array();
    $NewCNArray = array();

    $CNArray_All = array_merge($CNArray, $CNArray_Delete2);

    foreach ($CNArray as $CNId)
    {
        # cache controlled name and variant for display purposes
        $CN = new ControlledName($CNId);
        $NewCNArray[$CN->Name()] = $CN->Variant();
    }

    foreach ($CNArray_All as $CNId)
    {
        # now update DateLastModified for all affected Resources if updating
        $Query = "Select distinct Resources.ResourceId, Title from ".
             "Resources INNER JOIN ResourceNameInts ON ".
             "ResourceNameInts.ResourceId=Resources.ResourceId ".
             "WHERE ControlledNameId = $CNId ".
             "ORDER BY Resources.ResourceId";

        $DB->Query($Query);

        $Rows = $DB->NumRowsSelected();
        for ($Index=0; $Index<$Rows; $Index++)
        {
            $Result = $DB->FetchRow();

            $LinkArray[$LinkIndex++] =
                "<a href=\"index.php?P=FullRecord&amp;ResourceId=".
                $Result["ResourceId"]."\" target=\"_blank\">".
                $Result["Title"]."</a><br>";
            $UpdateQuery = "Update Resources set ".
                "DateLastModified = '".date("Y-m-d H:i:s").
                "' where ResourceId = ".$Result["ResourceId"];
            $DB2->Query($UpdateQuery);

            # update the Search DB for this controlled name & resource
            $SearchEngine->UpdateForResource($Result["ResourceId"]);
        }
    }
    $CNArray = $NewCNArray;
}

function PerformDeferredActions()
{
    global $AF;
    global $Deferred_Deletion;
    global $Deferred_Remap;

    foreach ($Deferred_Deletion as $CN)
    {
        $CN->Delete(TRUE);
    }

    foreach ($Deferred_Remap as $List)
    {
        list($CN, $OtherId) = $List;
        $AF->SignalEvent("EVENT_CNAME_REMAPPED", array($CN->Id(), $OtherId));
        $CN->RemapTo($OtherId);
    }
}

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

# non-standard global variables
global $CNArray;
global $CNArray_Delete;
global $CNArray_Delete2;
global $F_ControlledName;
global $LinkArray;
global $Submit;
global $Deferred_Deletion;
global $Deferred_Remap;

$Deferred_Deletion = array();
$Deferred_Remap = array();
$CNArray_Delete2 = array();

if (!CheckAuthorization(PRIV_NAMEADMIN)) {  return;  }

$Submit = GetArrayValue($_POST, "Submit");

# check for actual deletion
if ($Submit == "Save Changes")
{
    ProcessControlledNames();
    UpdateCheckedValues();
    PerformDeferredActions();
}
else if ($Submit == "Cancel")
{
    $AF->SetJumpToPage("EditControlledName");
}

PageTitle("Edit Controlled Name Complete");
