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

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

/**
* Display list of modified controlled names.
*/
function DisplayControlledNameList()
{
    global $CNArray;

    if (count($CNArray) > 0)
    {
        foreach($CNArray as $CNName => $CNVariant)
        {
            print $CNName;
            if(!empty($CNVariant))
            {
                print ", Variant ($CNVariant)";
            }
            print "<br>";
        }
    }
    else
    {
        print "<em>(none)</em>";
    }
}

/**
* Display list of deleted controlled names.
*/
function DisplayDeletedControlledNameList()
{
    global $CNArray_Delete;

    if (count($CNArray_Delete) > 0)
    {
        foreach($CNArray_Delete as $CNName => $CNVariant)
        {
            print $CNName;
            if(!empty($CNVariant))
            {
                print ", Variant ($CNVariant)";
            }
            print "<br>";
        }
    }
    else
    {
        print "<em>(none)</em>";
    }
}

/**
* Display list of modified resources
*/
function DisplayModifiedResourceList()
{
    global $LinkArray;

    if (count($LinkArray) > 0)
    {
        foreach ($LinkArray as $LinkIndex => $LinkString)
        {
            print $LinkString;
        }
    }
    else
    {
        print "<em>(none)</em>";
    }
}

/**
* Process changed controlled names.
*/
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
    // @codingStandardsIgnoreStart
    for ($i = 0; array_key_exists('F_ControlledNameId_'.$i, $_POST); $i++)
    {
        // @codingStandardsIgnoreEnd
        $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;
                    # Look up the CName ID of the requested remap target
                    $OtherIds = ControlledName::SearchForControlledName(
                        $Remap, $CN->FieldId());

                    # If there was no matching CName for this field, create it
                    if (empty($OtherIds))
                    {
                        $NewName = new ControlledName(NULL, $Remap, $CN->FieldId());
                        $OtherId = $NewName->Id();
                    }
                    else
                    {
                        $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 Database();
    $DB2 = new Database();
    $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;ID=".
                $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;
}

/**
* Perform actions deferred until after the pageload.
*/
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");
$SchemaId = GetArrayValue($_GET, "SC");

# check for actual deletion
if ($Submit == "Save Changes")
{
    ProcessControlledNames();
    UpdateCheckedValues();
    PerformDeferredActions();
}
else if ($Submit == "Cancel")
{
    $SC = $SchemaId ? "&SC=".intval($SchemaId) : "";
    $AF->SetJumpToPage("EditControlledName".$SC);
}

PageTitle("Edit Controlled Name Complete");
