<?PHP
#
#   FILE:  EditControlledName.php
#
#   FUNCTIONS PROVIDED:
#       DisplayFoundControlledNames()
#           - displays results of search ControlledNames
#
#   FUNCTIONS EXPECTED:
#       DisplayControlledName()
#           - displays the ControlledNameId and ControlledName
#
#       DisplayControlledNamesForEdit()
#           - Displays Editable fields for a ControlledName
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011 Internet Scout Project
#   http://scout.wisc.edu/
#

PageTitle("Edit Controlled Names");

include_once("lib/AxisPHP/Axis--StandardLibrary.php");  # (for PrintOptionList())

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

# function to print the index value
function PrintIndex()
{
    global $Index;

    print $Index;
}

# functon to print the ControlledName
function PrintControlledName()
{
    global $F_ControlledName;

    print(GetHtmlTranslatedString($F_ControlledName));
}

# function to print the ControlledNameId
function PrintControlledNameId()
{
    global $F_ControlledNameId;

    print $F_ControlledNameId;
}

# function to print the ControlledNameId
function PrintVariantName()
{
    global $F_VariantName;

    print(GetHtmlTranslatedString($F_VariantName));

}

# return if ControlledNames exist or not
function ControlledNamesExist()
{
    global $NumRows;

    return $NumRows;
}

# print number of Rows
function PrintNumRows()
{
    global $NumRows;

    print $NumRows;
}

# print in use message
function PrintInUseMessage()
{
    global $InUseMessage;

    print $InUseMessage;
}

# function to see if Form variable F_ControlledName is empty or not
function SearchEntered()
{
    global $F_ControlledName;

    return (empty($F_ControlledName)) ? false : true;
}

#  display a ControlledName list of values as an option menu
function DisplayControlledNameList()
{
    global $F_FieldId;
    global $Schema;
    global $Index;

    if (isset($Index))
        $FieldName = "F_FieldId_".$Index;
    else
        $FieldName = "F_FieldId";

    $RFactory = new ResourceFactory();
    $ResourceCount = $RFactory->GetItemCount();

    $Fields = $Schema->GetFields(MetadataSchema::MDFTYPE_CONTROLLEDNAME);

    # Compute the width of the submit buttons in characters based on
    # the lengths of the field names plus "Search ".
    $Width = 0;
    foreach ($Fields as $Field)
    {
        $Width = max($Width, strlen($Field->GetDisplayName())+10);
    }

    foreach ($Fields as $Field)
    {
        $CNFactory = new ControlledNameFactory($Field->Id());

        $UsageCount = $CNFactory->GetUsageCount();
        $UsagePercentage = ($ResourceCount>0) ?
            round((100*$UsageCount)/$ResourceCount) : 0 ;
        ?>
          <tr valign="top">
              <td><?PHP print $Field->GetDisplayName(); ?></td>
              <td>(<?PHP print $Field->GetCountOfPossibleValues(); ?>&nbsp;values)</td>
              <td>
                  <input style="width: <?PHP print $Width; ?>ex;" class="cw-button cw-button-constrained cw-button-elegant"
                         type="submit" name="Submit" value="Search <?PHP print $Field->GetDisplayName(); ?>" />
              </td>
              <td><?PHP print $Field->Description(); ?></td>
              <td>
                  Assigned to <?PHP print $UsageCount; ?> resources
                  (<?PHP print $UsagePercentage; ?>%)
              </td>
          </tr>
        <?PHP

        $Items[$Field->Id()] = $Field->GetDisplayName();
    }
}

# returns true if field uses qualifiers
function FieldUsesQualifiers()
{
    global $F_FieldId;
    global $Schema;

    if ($F_FieldId > 0)
    {
        $Field = $Schema->GetField($F_FieldId);
        if (is_object($Field))
            return $Field->UsesQualifiers();
        else
            return false;
    }
    return false;
}

# returns true if field uses item level qualifiers
function FieldHasItemLevelQualifiers()
{
    global $F_FieldId;
    global $Schema;

    $Field = $Schema->GetField($F_FieldId);
    return $Field->HasItemLevelQualifiers();
}

# get default qualifier
function GetDefaultQualifier()
{
    global $F_FieldId;
    global $Schema;

    $Field = $Schema->GetField($F_FieldId);
    $Qualifier = new Qualifier($Field->DefaultQualifier());
    return $Qualifier->Name();
}

# function to print list of qualifiers
function PrintQualifierOrList()
{
    global $QualifierId;
    global $Index;
    global $F_FieldId;
    global $Schema;

    if (FieldHasItemLevelQualifiers())
    {
        $Field = $Schema->GetField($F_FieldId);

        # first value is "--"
        $Items = $Field->AssociatedQualifierList();
        $Items["--"] = "--";
        ksort($Items);

        PrintOptionList("F_QualifierName_".$Index, $Items, $QualifierId,
            0, 1, NULL, false);
    }
    else
    {
        print GetDefaultQualifier();
    }
}

# display list of search results
function DisplayFoundControlledNames()
{
    global $DB;
    global $Index;
    global $F_ControlledNameId;
    global $F_ControlledName;
    global $F_VariantName;
    global $F_StartRec;
    global $QualifierId;
    global $NumRows;
    global $InUseMessage;
    global $MatchingControlledNames;
    global $G_RecordsPerPage;

    if ($NumRows > 0)
    {
        DisplayResults();
        $Index=0;
    }

    $Stop = min ($F_StartRec + $G_RecordsPerPage, count($MatchingControlledNames));
    for ($i=$F_StartRec; $i < $Stop; $i++)
    {
        $Result = $MatchingControlledNames[$i];

        $F_ControlledNameId = $Result["ControlledNameId"];
        $F_ControlledName = $Result["ControlledName"];
        $F_FieldId = $Result["FieldId"];
        $F_VariantName = $Result["VariantName"];
        $QualifierId = $Result["QualifierId"];
        $CN = new ControlledName($F_ControlledNameId);
        $InUseCount = $CN->InUse();

        $Link = "index.php?P=AdvancedSearch&amp;Q=Y&amp;G".$F_FieldId."=".$F_ControlledNameId;

        # display number of resources that use this controlled name
        if ($InUseCount == 1)
        {
            $InUseMessage = "<a href=\"".$Link."\">(".$InUseCount." resource)</a>";
        }

        else if ($InUseCount > 0)
        {
            $InUseMessage = "<a href=\"".$Link."\">(".$InUseCount." resources)</a>";
        }

        else
        {
            $InUseMessage = "(Not Used)";
        }


        DisplayControlledNamesForEdit();

        # only display qualifer field if field uses qualifiers
        if (FieldUsesQualifiers())
            DisplayQualifier();

        DisplayEndTags();
        $Index++;
    }
}

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

# controlledname search
function ControlledNameSearch()
{
    global $DB, $Query, $F_FieldId, $F_ControlledName, $MatchingControlledNames;

    if (isset($F_FieldId))
    {
        if (strlen($F_ControlledName)==0)
        {
            $F_ControlledName = " ";
        }

        # replace * and space with wild cards
        # pass +, squiqgles, and brackets through as literals
        # so that REGEXP in query doesn't puke
        $CNRegex = str_replace("*", ".*.", $F_ControlledName);
        $CNRegex = str_replace(" ", ".*.", $CNRegex);
        $CNRegex = str_replace("{", "[{]", $CNRegex);
        $CNRegex = str_replace("}", "[}]", $CNRegex);
        $CNRegex = str_replace("(", "[(]", $CNRegex);
        $CNRegex = str_replace(")", "[)]", $CNRegex);
        $CNRegex = str_replace("+", "[+]", $CNRegex);

        # this Query gets us close
        $Query = "Select ControlledName, VariantName, C.ControlledNameId, ".
            "C.FieldId, QualifierId from ControlledNames AS C".
            " LEFT JOIN VariantNames AS V ON ".
            "C.ControlledNameId=V.ControlledNameId WHERE (".
            "ControlledName REGEXP \"".$CNRegex."\" OR ".
            "VariantName REGEXP \"".$CNRegex."\") ".
            "AND C.FieldId = ".$F_FieldId." ".
            "ORDER BY ControlledName";
    }
    # nothing entered to search for
    else
    {
        $Query = "Select * from ControlledNames where ControlledName != ".
            "ControlledName";
    }

    $DB->Query($Query);

    while ($Row = $DB->FetchRow())
    {
        $MatchingControlledNames []= $Row;
    }

}

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

# non-standard global variables
global $F_ControlledName;
global $F_ControlledNameId;
global $F_FieldId;
global $F_VariantName;
global $F_StartRec;
global $InUseMessage;
global $Index;
global $NumRows;
global $QualifierId;
global $Query;
global $Schema;
global $MenuIndex;
global $MinLen;
global $MinLenLang;
global $MatchingControlledNames;
global $Submit;
global $G_RecordsPerPage;

$MatchingControlledNames = array();

$Words = array(
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
    "nine", "ten");
$MysqlSysVars = new MysqlSystemVariables($DB);
$MinLen = intval($MysqlSysVars->Get("ft_min_word_len"));
$MinLenLang = (isset($Words[$MinLen])) ? $Words[$MinLen] : $MinLen;
$MenuIndex = 1;

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

$DB = new Database();
$Schema = new MetadataSchema();

$G_RecordsPerPage = 100;
$F_StartRec = 0;

if (isset($_POST["F_ControlledName"]))
    $F_ControlledName = $_POST["F_ControlledName"];
if (isset($_POST["Submit"]))
{
    $Submit = $_POST["Submit"];
    if ($Submit == ">" )
    {
        $Submit = $_POST["F_CNField"];
        $F_StartRec = $_POST["F_StartRec"] + $G_RecordsPerPage;
    }
    elseif ($Submit == "<")
    {
        $Submit = $_POST["F_CNField"];
        $F_StartRec = max(0,$_POST["F_StartRec"] - $G_RecordsPerPage);
    }
}
else
    $Submit = NULL;

if (preg_match("/^Search (.*)/",$Submit ,$Regs))
{
    $Field = $Schema->GetFieldByLabel($Regs[1]);

    if (!$Field || $Field->Status() !== MetadataSchema::MDFSTAT_OK)
    {
        $Field = $Schema->GetFieldByName($Regs[1]);
    }

    $F_FieldId = $Field->Id();
}

# echo "F_FieldId = $F_FieldId, CN=$F_ControlledName<br>";

#controlled name search
ControlledNameSearch();
$NumRows = $DB->NumRowsSelected();

if ($Submit == "Cancel")
{
    $AF->SetJumpToPage("MDHome");
}
