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

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

/**
* Helper function to generate SQL to query fields from the database.
* @param string $FieldName Field name without the schema ID
* @param string $Condition Condition describing the test
* @return SQL fragment for the requested field
*/
function GetSqlForField($FieldName, $Condition)
{
    $Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

    if (($Condition == "contains") && preg_match("/Date/", $FieldName))
    {
        # when we do a Contains on a date, translate the contents of
        # the field to a catenation of common formats, so that a
        # substring search can match against these.
        $Field = "DATE_FORMAT(".$FieldName.$Plugin->GetSchemaId().", "
            ."'%M %d %Y %M %d, %Y %Y-%m-%d %m/%d/%Y')";
    }
    else
    {
        # otherwise just tack on the SchemaId
        $Field = $FieldName.$Plugin->GetSchemaId();
    }

    return $Field;
}

PageTitle("Calendar Events");

# get the plugin
$H_Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

# don't allow unauthorized access
if (!$H_Plugin->UserCanEditEvents($GLOBALS["G_User"]))
{
    CheckAuthorization(FALSE);
    return;
}

$Schema = new MetadataSchema($H_Plugin->GetSchemaId());
$ModificationField = $Schema->GetFieldByName("Date of Modification");
$DBFieldName = $ModificationField->DBFieldName();

# set up some basic values
$H_SortField = GetFormValue("SF", $DBFieldName);
$H_SortAscending = GetFormValue("SA", 0);
$H_StartingIndex = GetFormValue("SI", 0);
$H_EventsPerPage = 50;
$H_SchemaId = $H_Plugin->GetSchemaId();
$H_Events = array();

$EFactory = new CalendarEvents_EventFactory();

$H_EventCountsByTense = $EFactory->GetEventCountsByTense();

# load IDs of users that meet specified search criteria
if (GetFormValue("F_Field") && GetFormValue("F_Condition")
        && strlen(GetFormValue("F_SearchText")))
{
    $TgtField = GetFormValue("F_Field");

    # Figure out the condition part of the query:
    $ConditionMap = array(
            "contains" => "contains",
            "equals" => "=",
            "is before" => "<",
            "is after" => ">",
            );
    $Condition = $ConditionMap[GetFormValue("F_Condition")];
    $SearchText = GetFormValue("F_SearchText");
    if ($Condition == "contains")
    {
        $Target = "LIKE '%".addslashes($SearchText)."%'";
    }
    else
    {
        # if we're dealing with a date field, try to interpret
        # the search text as a date:
        if (preg_match("/Date/", $TgtField))
        {
            $SearchText = date('Y-m-d', strtotime($SearchText) );
        }

        # otherwise use the string as typed
        $Target = $Condition." '".addslashes($SearchText)."'";
    }

    # determine which fields to search
    if ($TgtField == "ALL")
    {
        $FieldsToProcess = array(
            "Title",
            "ShortTitle",
            "Description",
            "ContactEmail",
            "URL",
            "Venue",
            "Locality",
            "Region",
            "StartDate",
            "EndDate",
          );
    }
    else
    {
        $FieldsToProcess = array( $TgtField );
    }

    # iterate over the requested fields, gluing together a query
    # that searches across all of them:
    foreach ($FieldsToProcess as $Field)
    {
        $Field = GetSqlForField( $Field, $Condition );

        if (isset($WhereClause))
        {
            $WhereClause .= " OR ".$Field." ".$Target;
        }
        else
        {
            $WhereClause = " ".$Field." ".$Target;
        }
    }
}
else
{
    $WhereClause = NULL;
}

# fetch the events
$Factory = new ResourceFactory($H_SchemaId);
$EventIds = $Factory->GetItemIds($WhereClause, FALSE, $H_SortField, $H_SortAscending);
$H_EventCount = count($EventIds);

# calculate ID array checksum and reset paging if list has changed
$H_ListChecksum = md5(serialize($EventIds));
if ($H_ListChecksum != GetFormValue("CK")) {  $H_StartingIndex = 0;  }

# prune event IDs down to just currently-selected segment
$EventIds = array_slice($EventIds, $H_StartingIndex, $H_EventsPerPage);

# load events from IDs
foreach ($EventIds as $Id)
{
    $H_Events[$Id] = new CalendarEvents_Event($Id);
}
