<?php

/**
 * @file
 */

function stormevent_list() {
  $breadcrumb = array();
  $breadcrumb[] = l(t('SuiteDesk'), 'dashboard');
  drupal_set_breadcrumb($breadcrumb);

  if (array_key_exists('organization_nid', $_GET)) {
    if ($_SESSION['stormevent_list_filter']['organization_nid'] != $_GET['organization_nid']) {
      $_SESSION['stormevent_list_filter']['organization_nid'] = $_GET['organization_nid'];
    }
    unset($_SESSION['stormevent_list_filter']['project_nid']);
    unset($_SESSION['stormevent_list_filter']['task_nid']);
  }

  if (array_key_exists('project_nid', $_GET)) {
    if ($_SESSION['stormevent_list_filter']['project_nid'] != $_GET['project_nid']) {
      $_SESSION['stormevent_list_filter']['project_nid'] = $_GET['project_nid'];
    }
    $p = node_load($_GET['project_nid']);
    $_SESSION['stormevent_list_filter']['organization_nid'] = $p->organization_nid;

    unset($_SESSION['stormevent_list_filter']['task_nid']);
  }

  if (array_key_exists('task_nid', $_GET)) {
    if ($_SESSION['stormevent_list_filter']['task_nid'] != $_GET['task_nid']) {
      $_SESSION['stormevent_list_filter']['task_nid'] = $_GET['task_nid'];
    }

    $t = node_load($_GET['task_nid']);
    $_SESSION['stormevent_list_filter']['organization_nid'] = $t->organization_nid;
    $_SESSION['stormevent_list_filter']['project_nid'] = $t->project_nid;
  }

  $i = new stdClass();
  $i->type = 'stormevent';

  $params = $_GET;
  if (isset($_SESSION['stormevent_list_filter']['organization_nid'])) {
    $params['organization_nid'] = $_SESSION['stormevent_list_filter']['organization_nid'];
  }

  $header = array(
    array(
      'data' => ' ',
    ),
    array(
      'data' => t('Event') . ' / ' . t('Organization') . ' » ' . t('Project') . ' » ' . t('Task'),
      'field' => 'n.title',
    ),
    array(
      'data' => ' ',
    ),
    array(
      'data' => t('Date'),
      'field' => 'dini',
      'class' => 'storm_list_date',
    ),
    array(
      'data' => t('Modified'),
      'field' => 'n.changed',
      'class' => 'storm_list_date',
      'sort' => 'desc',
    ),
    array(
      'data' => t('Rev.'),
      'field' => 'sev.version',
      'class' => 'storm_list_version',
    ),
    array(
      'data' => storm_icon_add_node($i, $params),
      'class' => 'storm_list_operations',
    ),
  );

  $s  = "SELECT n.*, sev.*, nre.format, tev.*,
                fda.field_stormevent_date_value AS dini,
                fda.field_stormevent_date_value2 AS dend,
                fda.field_stormevent_date_rrule AS drule,
                fev.field_stormevent_attach_list AS clip FROM {node} AS n
    INNER JOIN {stormevent} AS sev ON n.vid=sev.vid
    INNER JOIN {node_revisions} AS nre ON n.vid = nre.vid
    INNER JOIN {content_type_stormevent} AS tev ON n.vid = tev.vid
    INNER JOIN {content_field_stormevent_date} AS fda ON n.vid = fda.vid AND fda.delta = 0
    LEFT JOIN {content_field_stormevent_attach} AS fev ON n.vid = fev.vid AND fev.field_stormevent_attach_list = 1 AND fev.delta = 0
    WHERE n.status=1 AND n.type='stormevent'";

  $where = array();
  $args = array();
  $filterfields = array();

  if (isset($_SESSION['stormevent_list_filter']['organization_nid']) && $_SESSION['stormevent_list_filter']['organization_nid'] != 0) {
    $where[] = 'sev.organization_nid=%d';
    $args[] = $_SESSION['stormevent_list_filter']['organization_nid'];
    $filterfields[] = t('Organization');
  }
  if (isset($_SESSION['stormevent_list_filter']['project_nid']) && $_SESSION['stormevent_list_filter']['project_nid'] != 0) {
    $where[] = 'sev.project_nid=%d';
    $args[] = $_SESSION['stormevent_list_filter']['project_nid'];
    $filterfields[] = t('Project');
  }
  if (isset($_SESSION['stormevent_list_filter']['task_nid']) && $_SESSION['stormevent_list_filter']['task_nid'] != 0) {
    $where[] = 'sev.task_nid=%d';
    $args[] = $_SESSION['stormevent_list_filter']['task_nid'];
    $filterfields[] = t('Task');
  }

  $type_list = storm_attributes_bydomain('event type search');
  $eventtype = isset($_SESSION['stormevent_list_filter']['eventtype']) ? $_SESSION['stormevent_list_filter']['eventtype'] : $type_list['default'];
  $_SESSION['stormevent_list_filter']['eventtype'] = $eventtype;

  if ($eventtype != '-') {
    $where[] = "sev.eventtype='%s'";
    $args[] = $eventtype;
    $filterfields[] = t('Type');
  }

  if (isset($_SESSION['stormevent_list_filter']['title']) && $_SESSION['stormevent_list_filter']['title'] != '') {
    $where[] = "LOWER(n.title) LIKE LOWER('%s')";
    $args[] = $_SESSION['stormevent_list_filter']['title'];
    $filterfields[] = t('Title');
  }

  if (isset($_SESSION['stormevent_list_filter']['datebeginfrom'])) {
    $datebeginfrom = $_SESSION['stormevent_list_filter']['datebeginfrom'];
    $datebeginfrom['hour'] = 0;
    $datebeginfrom['minute'] = 0;
    $date_timestamp = _storm_datetime_to_gmtimestamp($datebeginfrom);
    if ($datebeginfrom['year']>0 && $date_timestamp>=0) {
      $wherebeginfrom = "field_stormevent_date_value>='%s'";
      $args[] = date_convert($date_timestamp, DATE_UNIX, DATE_ISO);
      $filterfields[] = t('Date');
    }
  }
  if (isset($_SESSION['stormevent_list_filter']['datebeginto'])) {
    $datebeginto = $_SESSION['stormevent_list_filter']['datebeginto'];
    $datebeginto['hour'] = 23;
    $datebeginto['minute'] = 59;
    $date_timestamp = _storm_datetime_to_gmtimestamp($datebeginto);
    if ($datebeginto['year']>0 && $date_timestamp>=0) {
      $wherebeginto = "field_stormevent_date_value<='%s'";
      $args[] = date_convert($date_timestamp, DATE_UNIX, DATE_ISO);
      $filterfields[] = t('Date');
    }
  }
  if (isset($_SESSION['stormevent_list_filter']['dateendfrom'])) {
    $dateendfrom = $_SESSION['stormevent_list_filter']['dateendfrom'];
    $dateendfrom['hour'] = 0;
    $dateendfrom['minute'] = 0;
    $date_timestamp = _storm_datetime_to_gmtimestamp($dateendfrom);
    if ($dateendfrom['year']>0 && $date_timestamp>=0) {
      $whereendfrom = "field_stormevent_date_value2>='%s'";
      $args[] = date_convert($date_timestamp, DATE_UNIX, DATE_ISO);
      $filterfields[] = t('Date');
    }
  }
  if (isset($_SESSION['stormevent_list_filter']['dateendto'])) {
    $dateendto = $_SESSION['stormevent_list_filter']['dateendto'];
    $dateendto['hour'] = 23;
    $dateendto['minute'] = 59;
    $date_timestamp = _storm_datetime_to_gmtimestamp($dateendto);
    if ($dateendto['year']>0 && $date_timestamp>=0) {
      $whereendto = "field_stormevent_date_value2<='%s'";
      $args[] = date_convert($date_timestamp, DATE_UNIX, DATE_ISO);
      $filterfields[] = t('Date');
    }
  }
  if (isset($wherebeginfrom) || isset($wherebeginto) || isset($whereendfrom) || isset($whereendto)) {
    $wheredate = "SELECT vid FROM {content_field_stormevent_date} WHERE vid = n.vid";
    $wheredate .= isset($wherebeginfrom) ? " AND $wherebeginfrom" : '';
    $wheredate .= isset($wherebeginto) ? " AND $wherebeginto" : '';
    $wheredate .= isset($whereendfrom) ? " AND $whereendfrom" : '';
    $wheredate .= isset($whereendto) ? " AND $whereendto" : '';
    $where[] = "EXISTS ($wheredate)";
  }

  // This section only provides the value for the fieldset label, doesn't control actual filter
  $itemsperpage = isset($_SESSION['stormevent_list_filter']['itemsperpage']) ? $_SESSION['stormevent_list_filter']['itemsperpage'] : variable_get('storm_default_items_per_page', 10);

  if (count($filterfields) == 0) {
    $filterdesc = t('Not filtered');
  }
  else {
    $filterdesc = t('Filtered by !fields', array('!fields' => implode(", ", array_unique($filterfields))));
  }
  $filterdesc .= ' | '. t('!items items per page', array('!items' => $itemsperpage));

  $o = drupal_get_form('stormevent_list_filter', $filterdesc);

  $s = stormevent_access_sql($s, $where);
  $s = db_rewrite_sql($s);
  $tablesort = tablesort_sql($header);

  $r = pager_query($s . $tablesort, $itemsperpage, 0, NULL, $args);

  $events = array();
  while ($item = db_fetch_object($r)) {
    $events[] = $item;
  }

  $o .= theme('stormevent_list', $header, $events);
  $o .= theme('pager', NULL, $itemsperpage, 0);
  print theme('page', $o);
}

function stormevent_list_filter(&$form_state, $filterdesc = 'Filter') {
  $organization_nid = isset($_SESSION['stormevent_list_filter']['organization_nid']) ? $_SESSION['stormevent_list_filter']['organization_nid'] : 0;
  $project_nid = isset($_SESSION['stormevent_list_filter']['project_nid']) ? $_SESSION['stormevent_list_filter']['project_nid'] : 0;
  $task_nid = isset($_SESSION['stormevent_list_filter']['task_nid']) ? $_SESSION['stormevent_list_filter']['task_nid'] : 0;

  $type_list = storm_attributes_bydomain('event type search');
  $eventtype = isset($_SESSION['stormevent_list_filter']['eventtype']) ? $_SESSION['stormevent_list_filter']['eventtype'] : $type_list['default'];

  $title = isset($_SESSION['stormevent_list_filter']['title']) ? $_SESSION['stormevent_list_filter']['title'] : '';

  $datebeginfrom = isset($_SESSION['stormevent_list_filter']['datebeginfrom']) ? $_SESSION['stormevent_list_filter']['datebeginfrom'] : NULL;
  $datebeginto = isset($_SESSION['stormevent_list_filter']['datebeginto']) ? $_SESSION['stormevent_list_filter']['datebeginto'] : NULL;
  $dateendfrom = isset($_SESSION['stormevent_list_filter']['dateendfrom']) ? $_SESSION['stormevent_list_filter']['dateendfrom'] : NULL;
  $dateendto = isset($_SESSION['stormevent_list_filter']['dateendto']) ? $_SESSION['stormevent_list_filter']['dateendto'] : NULL;

  $itemsperpage = isset($_SESSION['stormevent_list_filter']['itemsperpage']) ? $_SESSION['stormevent_list_filter']['itemsperpage'] : variable_get('storm_default_items_per_page', 10);
  $_SESSION['stormevent_list_filter']['itemsperpage'] = $itemsperpage;

  $form = array();

  $form['filter'] = array(
    '#type' => 'fieldset',
    '#title' => $filterdesc,
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );

  $form['filter']['group1'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $s = "SELECT n.nid, n.title FROM {node} AS n INNER JOIN {stormorganization} AS sor ON sor.vid=n.vid WHERE n.status=1 AND n.type='stormorganization' ORDER BY n.title";
  $s = stormorganization_access_sql($s);
  $s = db_rewrite_sql($s);
  $r = db_query($s);
  $organizations = array();
  while ($organization = db_fetch_object($r)) {
    $organizations[$organization->nid] = $organization->title;
  }
  $organizations = array(0 => t('All')) + $organizations;
  $form['filter']['group1']['organization_nid'] = array(
    '#type' => 'select',
    '#title' => t('Organization'),
    '#default_value' => $organization_nid,
    '#options' => $organizations,
    '#attributes' => array('onchange' => "stormtask_organization_project_tasks(this, 'edit-project-nid', 'edit-task-nid', '', true, '" . t('All') . "')"),
  );

  $s = "SELECT n.nid, n.title FROM {node} AS n INNER JOIN {stormproject} AS spr ON spr.vid=n.vid
  WHERE n.status=1 AND spr.organization_nid=%d AND n.type='stormproject' ORDER BY n.title";
  $s = stormproject_access_sql($s);
  $s = db_rewrite_sql($s);
  $r = db_query($s, $organization_nid);
  $projects = array();
  while ($project = db_fetch_object($r)) {
    $projects[$project->nid] = $project->title;
  }
  $projects = array(0 => t('All')) + $projects;
  $form['filter']['group1']['project_nid'] = array(
    '#type' => 'select',
    '#title' => t('Project'),
    '#default_value' => $project_nid,
    '#options' => $projects,
    '#process' => array('storm_dependent_select_process'),
    '#attributes' => array('onchange' => "stormtask_project_tasks('edit-organization-nid', this, 'edit-task-nid', '', true, '" . t('All') . "')"),
  );

  $s = "SELECT n.nid, n.title FROM {node} AS n INNER JOIN {stormtask} AS sta ON sta.nid=n.nid WHERE n.status=1 AND n.type='stormtask' AND sta.project_nid=%d ORDER BY title ";
  $s = stormtask_access_sql($s);
  $s = db_rewrite_sql($s);
  $r = db_query($s, $project_nid);
  $tasks = array();
  while ($task = db_fetch_object($r)) {
    $tasks[$task->nid] = $task->title;
  }
  $tasks = array(0 => t('All')) + $tasks;
  $form['filter']['group1']['task_nid'] = array(
    '#type' => 'select',
    '#title' => t('Task'),
    '#default_value' => $task_nid,
    '#options' => $tasks,
  );

  $form['filter']['group2'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $form['filter']['group2']['eventtype'] = array(
    '#type' => 'select',
    '#title' => t('Type'),
    '#default_value' => $eventtype,
    '#options' => $type_list['values'],
  );

  $form['filter']['group2']['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title'),
    '#default_value' => $title,
  );

  $form['filter']['group3'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $form['filter']['group3']['datebeginfrom'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date begin from'),
    '#default_value' => $datebeginfrom,
  );

  $form['filter']['group3']['datebeginto'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date begin to'),
    '#default_value' => $datebeginto,
  );

  $form['filter']['group4'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
  );

  $form['filter']['group4']['dateendfrom'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date end from'),
    '#default_value' => $dateendfrom,
  );

  $form['filter']['group4']['dateendto'] = array(
    '#type' => 'dateext',
    '#withnull' => 'true',
    '#title' => t('Date end to'),
    '#default_value' => $dateendto,
  );

  $form['filter']['group5'] = array(
    '#type' => 'markup',
    '#theme' => 'storm_form_group',
    '#attributes' => array('class' => 'formgroup-submit'),
  );

  $form['filter']['group5']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Filter'),
    '#submit' => array('stormevent_list_filter_filter'),
  );

  $form['filter']['group5']['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset'),
    '#submit' => array('stormevent_list_filter_reset'),
  );

  $form['filter']['group5']['itemsperpage'] = array(
    '#type' => 'textfield',
    '#title' => t('Items'),
    '#size' => 10,
    '#default_value' => $itemsperpage,
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );

  return $form;

}

function stormevent_list_filter_reset($form, &$form_state) {
  unset($_SESSION['stormevent_list_filter']);
}

function stormevent_list_filter_filter($form, &$form_state) {
  $_SESSION['stormevent_list_filter']['organization_nid'] = $form_state['values']['organization_nid'];
  $_SESSION['stormevent_list_filter']['project_nid'] = $form_state['values']['project_nid'];
  $_SESSION['stormevent_list_filter']['task_nid'] = $form_state['values']['task_nid'];
  $_SESSION['stormevent_list_filter']['eventtype'] = $form_state['values']['eventtype'];
  $_SESSION['stormevent_list_filter']['title'] = $form_state['values']['title'];
  $_SESSION['stormevent_list_filter']['datebeginfrom'] = $form_state['values']['datebeginfrom'];
  $_SESSION['stormevent_list_filter']['datebeginto'] = $form_state['values']['datebeginto'];
  $_SESSION['stormevent_list_filter']['dateendfrom'] = $form_state['values']['dateendfrom'];
  $_SESSION['stormevent_list_filter']['dateendto'] = $form_state['values']['dateendto'];
  $_SESSION['stormevent_list_filter']['itemsperpage'] = $form_state['values']['itemsperpage'];
}
