<?php

function registration_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      // This description is shown in the listing at admin/modules.
      return t('Event Registration.');
  }
}

function registration_menu($may_cache) {
  $items = array();

  if ($may_cache) {
  }else{
    if(arg(1)=='node' && arg(2)=='add' && arg(3)=='registration'){
      $items[] = array(
        'path' => 'node/add/registration/'.arg(3), 
        'title' => t('event registration'),
        'access' => true,
        'type' => MENU_CALLBACK,
      );
    }
  }

  return $items;
}

function registration_node_info() {
  return array(
    'registration' => array(
      'name' => t('event registration'), 
      'base' => 'registration'
    ),
    'registration_attendee' => array(
      'name' => t('event attendee'),
      'base' => 'registration_attendee',
    )
  );
}

function registration_form(&$node) {
  $product = node_load(array('nid'=>arg(3)));
  if($product->type != 'product'){
    drupal_set_message('Argument must be a product id','error');
    drupal_set_message('<pre>'.print_r($product,true).'</pre>');
  }
  
  $form['#pre_render'] = array('registration_form_pre_render');

  $form['pagetitle'] = array(
    '#type' => 'item',
    '#value' => 'Step 1',
  );
  $form['pagedescription'] = array(
    '#type' => 'item',
    '#value' => "<h1>Registrant Information</h1><p>As a registrant, you are responsible for paying the entry fee for your attendees. A registrant may purchase tickets for any amount of attendees to the Nature Tourism Seminar, excluding or including himself. Before you build your attendee list, we'll need some information about the registrant.<br />Required fields marked with an (*) asterisk</p>",
  );
  $form['product'] = array(
    '#type' => 'value',
    '#value' => $product->nid,
  );
  $form['title'] = array(
    '#type' => 'value',
    '#value' => ('Registration for '.$product->title),
  );
  $form['address']['#tree'] = TRUE;
  $form['address']['firstname'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#default_value' => $node->address['firstname'],
  );
  $form['address']['lastname'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#default_value' => $node->address['lastname'],
  );
  $form['address']['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#default_value' => $node->address['email'],
  );
  $form['address']['company'] = array(
    '#type' => 'textfield',
    '#title' => t('Company or Organization'),
    '#default_value' => $node->address['company'],
  );
  $form['address']['url'] = array(
    '#type' => 'textfield',
    '#title' => t('URL'),
    '#default_value' => $node->address['url'],
  );
  $form['address']['billing'] = array(
    '#type' => 'fieldset',
    '#title' => 'Billing Info',
    '#collapsible' => FALSE,
    '#description' => "<p>We will need to collect your billing information before you purchase tickets for your Nature Tourism Seminar attendees. You may choose to complete a portion of this information here, or all of it at checkout.</p>",
  );
  $form['address']['billing']['street1'] = array(
    '#type' => 'textfield',
    '#title' => t('Address'),
    '#default_value' => $node->address['street1'],
    '#size' => 60,
    '#maxlength' => 64,
  );
  $form['address']['billing']['street2'] = array(
    '#type' => 'textfield',
    '#title' => '&nbsp;',
    '#default_value' => $node->address['street2'],
    '#size' => 60,
    '#maxlength' => 64,
  );
  $form['address']['billing']['city'] = array(
    '#type' => 'textfield',
    '#title' => t('City'),
    '#default_value' => $node->address['city'],
    '#size' => 32,
    '#maxlength' => 32,
  );
  $form['address']['billing']['state'] = array(
    '#type' => 'textfield',
    '#title' => t('State'),
    '#default_value' => $node->address['state'],
    '#size' => 32,
    '#maxlength' => 32,
  );
  $form['address']['billing']['zip'] = array(
    '#type' => 'textfield',
    '#title' => t('Zip'),
    '#default_value' => $node->address['zip'],
    '#size' => 10,
    '#maxlength' => 10,
  );
  $form['address']['billing']['country'] = array(
    '#type' => 'value',
    '#value' => ($node->address['country'] ? $node->address['country'] : variable_get('ec_country', '')),
  );
  
  $form['attendees'] = array(
    '#tree' => TRUE,
  );

  for($i=0;$i<10;$i++){
    $form['attendees'][$i] = attendee_form_line();
  }

  // Add a back button
  $form['back'] = array(
    '#type'          => 'button',
    '#value'         => t('Back'),
    '#weight'        => 35,
  );
  
  return $form;
}

/**
 * The #pre_render of a form allows us to make changes AFTER validation (unlike
 * hook_form_alter()), but BEFORE the form has actually been displayed. We use
 * it to control which form elements are shown, which are hidden, and which values
 * to set based on validate elements, not $_POST. This is a necessity for our
 * complicated multipage example form.
 */
function registration_form_pre_render($form_id, &$form, $next_page = TRUE) {
  require_once(dirname(__FILE__).'/multipage_form.inc');
  global $form_values;

  // Make sure it's our multipage form.
  if ($form_id == 'registration_node_form') {
    // Are we ready for the next page in our form?
    if ($next_page && isset($_POST['edit']['page']) && ($_POST['op'] != t('Back')) && ($_POST['op'] != t('Preview'))) {
      $form['page']['#value'] = $form['page']['#value'] + 1;
    }

    // Validation errors? Show previous page for correcting.
    if (form_get_errors()) {
      $form['page']['#value']--;
    }

    // Modify the #required/#type values depending on our current page.
    // The arrays tell us the pages the changes should take place in.
    $page = $form['page']['#value'];
    $descriptions[1] = "<h1>Registrant Information</h1><p>As a registrant, you are responsible for paying the entry fee for your attendees. A registrant may purchase tickets for any amount of attendees to the Nature Tourism Seminar, excluding or including himself. Before you build your attendee list, we'll need some information about the registrant.<br />Required fields marked with an (*) asterisk</p>";
    $descriptions[2] = "<h1>Event Attendees</h1><p>Build the list of attendees for whom you wish to purchase tickets. If you, the registrant, are not attending this event, you may remove yourself from this list. We will send an email notification to these attendees after payment is secured.<br />Required fields marked with an (*) asterisk</p>";
    $form['pagetitle']['#value'] = '<h2>Step ' . $page . '</h2>';
    $form['pagedescription']['#value'] = $descriptions[$page]; 
    // page 1
    multipage_form_set_element_visibility($form['address'], $page == 1);

    // page 2
    multipage_form_set_element_visibility($form['attendees'], $page == 2);
    $form['attendees']['#theme'] = ($page==2 ? 'attendees_form' : NULL);
    if($page == 2 && $form['submit']['#value'] != t('Submit')){
      multipage_form_set_value($form['attendees'][0]['firstname'], $form['address']['firstname']['#value']);
      multipage_form_set_value($form['attendees'][0]['lastname'], $form['address']['lastname']['#value']);
      multipage_form_set_value($form['attendees'][0]['email'], $form['address']['email']['#value']);
      multipage_form_set_value($form['attendees'][0]['company'], $form['address']['company']['#value']);
      multipage_form_set_value($form['attendees'][0]['url'], $form['address']['url']['#value']);
      registration_set_message('<b>Registrant:</b><br />' .
        $form['address']['firstname']['#value'] . ' ' .
        $form['address']['lastname']['#value'] . ', ' .
        $form['address']['company']['#value'] . ' (' .
        $form['address']['url']['#value'] . ')');
    }      
    
    // Buttons
    multipage_form_set_element_visibility($form['back'], in_array($form['page']['#value'], array(2)), $next_page);
    multipage_form_set_element_visibility($form['submit'], in_array($form['page']['#value'], array(2)), $next_page);

    // The button text actually helps determine if a form has actually been
    // submitted because the name is also the value of a clicked button. By
    // changing it for building, but not rendering, the form is not fully
    // sumbitted until we name it 'Submit', the usual value.
    if ($next_page) {
      $submit_text = array(NULL, t('Continue'), t('Submit'));
      $form['submit']['#value'] = $submit_text[$form['page']['#value']];
    }
  }
}

function registration_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array('info' => t('Registration Status'));
    $blocks[1] = array('info' => t('Registration Cart'));
    return $blocks;
  }else if ($op == 'view') {
    switch($delta) {
      case 0:
        $block = array(
          'subject' => t('Registration Summary'),
          'content' => theme_registration_get_messages()
        );
        break;
      case 1:
        $items = cart_get_items();
        $item_count = count($items);
        foreach($items as $key=>$item){
          $block['content'] .= '<pre>'.print_r($item,true).'</pre>';
        }
        break;
    }
    return $block;
  }
} 

function registration_set_message($message=NULL,$type='status'){
  if ($message) {
    if (!isset($_SESSION['registration_messages'])) {
      $_SESSION['registration_messages'] = array();
    }

    if (!isset($_SESSION['registration_messages'][$type])) {
      $_SESSION['registration_messages'][$type] = array();
    }

    $_SESSION['registration_messages'][$type][] = $message;
  }

  // messages not set when DB connection fails
  return isset($_SESSION['registration_messages']) ? $_SESSION['registration_messages'] : NULL;
}   

function registration_get_messages() {
  if ($messages = registration_set_message()) {
    unset($_SESSION['registration_messages']);
  }

  return is_array($messages ? $messages : array());
}

function theme_registration_get_messages(){
  $data = registration_get_messages();
  if(!is_array($data)){
    return;
  }
  foreach($data as $type=>$messages){  
    $output .= "<div class=\"messages $type\">\n";
    if (count($messages) > 1) {
      $output .= " <ul>\n";
      foreach($messages as $message) {
        $output .= '  <li>'. $message ."</li>\n";
      }
      $output .= " </ul>\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "</div>\n";
  }

  return $output;
}

function theme_registration_cart_block(){
  
}
/**
 * Implementation of hook_form_alter(). Here, we set up the 'page' field,
 * which keeps track of what stage the form is in.
 */
function registration_form_alter($form_id, &$form) {
  // Make sure it's our multipage form.
  if ($form_id == 'registration_node_form') {

    // Determine which page of the multipage form we're on. We don't do
    // any incrementing here - that's something that our #pre_render'er
    // will do when this page of the form has successfully validated.
    $form['page'] = array(
      '#type' => 'hidden',
      '#value' => isset($_POST['edit']['page']) ? $_POST['edit']['page'] : 1,
    );

    // If back button is pressed, back up the form stage, Also, if preview
    // is hit we need to decrement the counter here to keep us on the same page.
    if ($_POST['op'] == t('Back')) {
      $form['page']['#value']--;
    }

    // This modifies the form for validation purposes. once validation is
    // completed, it'll be called one more time (through Drupal's Form API)
    // at which point it'll advance the form to the next page.
    registration_form_pre_render($form_id, $form, FALSE);
  }

  return $form;
}

function registration_load($node) {
  $additions = db_fetch_object(db_query('SELECT * FROM {registration} WHERE nid = %d', $node->nid));
  return $additions;
} 

function registration_view(&$node, $teaser = FALSE, $page = FALSE) {
  $node = node_prepare($node, $teaser);
  $result = db_query('SELECT * FROM {registration_attendees} WHERE rid = %d', $node->nid);
  while($row = db_fetch_array($result)){
    unset($row['nid']);
    unset($row['rid']);
    $row['display'] = $row['display'] ? 'Yes' : 'No';
    $rows[] = $row;
  }
  $headers = array('First Name', 'Last Name', 'Email', 'Company', 'URL', 'Display?');
  
  $node->body .= '<h2>Attendees</h2>'.theme('table',$headers,$rows);
}    

function registration_link($type, $node = NULL, $teaser = FALSE) {
  $links = array();

  if ($type == 'node' && $node->type == 'registration') {
    if (!$teaser) {
      $links[] = l('Event Details','node/'.$node->productid);
      $links[] = l('Transaction Details','admin/store/transaction/edit/'.$node->txnid);      
    }
  }
  if ($type == 'node' && $node->ptype == 'registration') {
    $links[] = l('Register for this event', 'node/add/registration/'.$node->nid);
  }
  return $links;
} 
function registration_delete($node) {
  db_query('DELETE FROM {registration} WHERE nid = %d', $node->nid);
} 
function registration_insert($node){
  // get non-empty attendees and add that many items to the cart
  foreach($node->attendees as $item){
    if($item['firstname']){
      $att_node = new stdClass();

      $att_node->title = $item['firstname'] . ' ' . $item['lastname'] . '[' . $node->title . ']';
      $att_node->type = 'registration_attendee';
      $att_node->status = 1;

      $att_node->rid = $node->nid;
      $att_node->firstname = $item['firstname'];
      $att_node->lastname = $item['lastname'];
      $att_node->email = $item['email'];
      $att_node->company = $item['company'];
      $att_node->url = $item['url'];
      $att_node->display = $item['display'];
      
      node_save($att_node);
      $attendees[] = $item;
    }
  }
  cart_add_item($node->product,count($attendees));
  
  // Kickoff the checkout process so we can manipulate the txn object
  // MUST unset $_REQUEST['op'] the first time through checkout_form
  // to properly simulate starting the checkout process
  $op = $_REQUEST['op'];
  unset($_REQUEST['op']);
  checkout_form();
  $_REQUEST['op'] = $op;
  $txn = ec_checkout_get_data();
  
  // add email and address info to the txn object
  $txn->mail = $node->address['email'];
  $txn->address['billing'] = (object)$node->address;

  // setting screen=3 will take us to the final checkout screen
  $txn->screen=2;
  
  // save txn data
  $txn->registration_nid = $node->nid;
  ec_checkout_hide_data($txn);
  
  // save 
  db_query("INSERT INTO {registration} 
    (nid, firstname, lastname, email, street1, street2, city, state, zip, country, company, url, txnid, productid) 
    VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
    $node->nid, $node->address['firstname'], $node->address['lastname'], $node->address['email'],
    $node->address['street1'], $node->address['street2'], $node->address['city'],
    $node->address['state'], $node->address['zip'], $node->address['country'], 
    $node->address['company'], $node->address['url'], $txn->txnid, $node->product ); 


  drupal_goto('cart/checkout','op=next');
}

/******************************************************************** 
 * register_attendee functions
 ********************************************************************/
function registration_attendee_insert($node){
  db_query("INSERT INTO {registration_attendees} (nid, rid, firstname, lastname, email, company, url, display) VALUES (%d, %d, '%s', '%s', '%s', '%s', '%s', %d)",
    $node->nid, $node->rid, $node->firstname, $node->lastname, $node->email, $node->company, $node->url, $node->display?1:0 ); 
}

function registration_attendee_load($node) {
  $additions = db_fetch_object(db_query('SELECT * FROM {registration_attendees} WHERE nid = %d', $node->nid));
  return $additions;
}
 
function registration_attendee_delete($node) {
  db_query('DELETE FROM {registration_attendees} WHERE nid = %d', $node->nid);
} 

function attendee_form_line(){
  $entry['firstname'] = array(
    '#type' => 'textfield',
    '#size' => '20',
  );
  $entry['lastname'] = array(
    '#type' => 'textfield',
    '#size' => '20',
  );
  $entry['email'] = array(
    '#type' => 'textfield',
    '#size' => '20',
  );
  $entry['company'] = array(
    '#type' => 'textfield',
    '#size' => '20',
  );
  $entry['url'] = array(
    '#type' => 'textfield',
    '#size' => '20',
  );
  $entry['display'] = array(
    '#type' => 'checkbox',
    '#return_value' => 1,
    '#default_value' => false,
  ); 
  return $entry;
}
 
/**
 * This function wraps the attendees form fields in a table for display.
 */
function theme_attendees_form(&$form) {
  $header = array(t('First Name'),t('Last Name'), t('Email'), t('Company'), t('URL'), t('Display'));

  $rows = array();
  foreach (element_children($form) as $key) {
    $row = array();
    $row[] = form_render($form[$key]['firstname']);
    $row[] = form_render($form[$key]['lastname']);
    $row[] = form_render($form[$key]['email']);
    $row[] = form_render($form[$key]['company']);
    $row[] = form_render($form[$key]['url']);
    $row[] = form_render($form[$key]['display']);
    $rows[] = $row;
  }
  $output = theme('table', $header, $rows);
  $output .= form_render($form);
  return $output;
}

/******************************************************************** 
 * E-commerce stuff
 ********************************************************************/
function registration_productapi(&$node, $op, $a3 = null, $a4 = null) {
  switch ($op) {
    case 'wizard_select':
      return array('registration' => t('Event Registration Product'));

    case 'attributes':
      return array('in_stock');
      
    case 'view': 
  }
}

function registration_ec_transactionapi(&$txn, $op, $arg3 = null, $arg4 = null) {
  switch ($op) {
    case 'load':
      break;
    case 'insert':
    case 'update':
      if ($txn->registration_nid) {
        db_query("UPDATE {registration} SET txnid = %d WHERE nid = %d", $txn->txnid, $txn->registration_nid);
      }
      break;
  }
}
