<?php

/**
 * @file
 * Functions for uc_earlybird module.
 */

/**
 * Implements hook_line_item().
 */
function uc_earlybird_uc_line_item() {
  $items[] = array(
    'id' => 'earlybird',
    'title' => t('Early bird discount'),
    'default' => FALSE,
    'stored' => TRUE,
    'calculated' => TRUE,
    'add_list' => TRUE,
    'display_only' => FALSE,
  );
  return $items;
}

/**
 * Implements hook_form_alter().
 *
 * Add the discount form to the node edit form, under product settings.
 *
 * Alter the cart form to show the discount.
 */
function uc_earlybird_form_alter(&$form, &$form_state, $form_id) {
  if (strpos($form_id, '_node_form') !== FALSE) {
    $product_types = uc_product_types();
    if (in_array($form['#node']->type, $product_types)) {
      $node = $form['#node'];
      $form['base']['earlybird'] = array(
        '#title' => t('Early bird discount'),
        '#type' => 'fieldset',
        '#weight' => $form['base']['dimensions']['#weight'] + 1,
      );
      $form['base']['earlybird']['earlybird_date'] = array(
        '#title' => 'Discounted on or before',
        '#type' => 'date',
      );
      if (isset($node->earlybird)) {
        $form['base']['earlybird']['earlybird_date']['#default_value'] = array(
          'year' => date('Y', $node->earlybird['date']),
          'month' => date('n', $node->earlybird['date']),
          'day' => date('j', $node->earlybird['date']),
        );
      }
      $form['base']['earlybird']['earlybird_discount'] = array(
        '#title' => 'Discount amount',
        '#type' => 'textfield',
        '#size' => 3,
        '#description' => 'Enter in a dollar amount or percentage, e.g., 5% or 10',
        '#default_value' => isset($node->earlybird) ? $node->earlybird['discount'] : NULL,
      );
    }
  }

  if ($form_id == 'uc_cart_view_form') {
    foreach ($form['items'] as $key => &$val) {
      if (is_numeric($key)) {
        if (isset($val['nid'])) {
          $sql = "select * from {uc_earlybird} where nid = :nid";
          $result = db_query($sql, array(':nid' => $val['nid']['#value']));
          if ($earlybird = $result->fetchObject()) {
            if ($earlybird->date >= REQUEST_TIME && intval($earlybird->discount) > 0) {
              $discount = _uc_earlybird_discount_text($earlybird->discount, $val['#entity']->qty);
              $discountText = array(
                t('Early bird: !discount off at checkout', array('!discount' => $discount)),
              );
              $val['desc']['#markup'] .= theme('item_list', array(
                'items' => $discountText,
                'title' => NULL,
                'type' => 'ul',
                'attributes' => array('class' => 'uc-earlybird-teaser'),
                ));
            }
          }
        }
      }
    }
  }
}

/**
 * Implements hook_node_load().
 *
 * Load discount information to the node.
 */
function uc_earlybird_node_load($nodes, $types) {
  $sql = 'select * from {uc_earlybird} where nid IN (:nids)';
  $result = db_query($sql, array(':nids' => array_keys($nodes)));
  while ($row = $result->fetchAssoc()) {
    $nodes[$row['nid']]->earlybird = $row;
  }
}

/**
 * Implements hook_node_insert().
 *
 * Update discount information.
 */
function uc_earlybird_node_insert($node) {
  uc_earlybird_node_update($node);
}

/**
 * Implements hook_node_update().
 */
function uc_earlybird_node_update($node) {
  if (isset($node->earlybird_discount)) {
    // Insert/update the product's discount.
    extract($node->earlybird_date);
    $date = mktime(23, 59, 59, $month, $day, $year);
    if (strpos($node->earlybird_discount, '%') !== FALSE) {
      $discount = floatval($node->earlybird_discount) . '%';
    }
    else {
      $discount = floatval($node->earlybird_discount);
    }

    if (db_query('select 1 from {uc_earlybird} where nid = :nid', array(':nid' => $node->nid))->fetchField()) {
      // Node already has earlybird data.
      $update = array('nid');
    }
    else {
      $update = array();
    }
    $earlybird->nid = $node->nid;
    $earlybird->date = $date;
    $earlybird->discount = $discount;
    drupal_write_record('uc_earlybird', $earlybird, $update);
  }
}

/**
 * Implements hook_add_to_cart().
 *
 * Check time and show notification.
 */
function uc_earlybird_uc_add_to_cart($nid, $qty, $data) {
  $result = db_query('select node.title, eb.* from {uc_earlybird} eb
  inner join {node} node on node.nid = eb.nid
  where eb.nid = :nid', array(':nid' => $nid));
  if ($earlybird = $result->fetchObject()) {
    if (REQUEST_TIME <= $earlybird->date) {
      if (intval($earlybird->discount) > 0) {
        $discount_text = _uc_earlybird_discount_text($earlybird->discount, $qty);
        drupal_set_message(t('You will receive a discount of %discount when you checkout %title.', array('%title' => $earlybird->title, '%discount' => $discount_text)));
      }
    }
  }
}

/**
 * Display discount properly.
 */
function _uc_earlybird_discount_text($discount, $qty = 1) {
  if (strpos($discount, '%') !== FALSE) {

  }
  else {
    $discount *= $qty;
    $discount = uc_currency_format($discount);
  }

  return $discount;
}

/**
 * Calculate early bird discount for a product. Check time.
 */
function _uc_earlybird_calculate_discount($product) {
  $result = db_query('select * from {uc_earlybird} where nid = :nid', array(':nid' => $product->nid));
  if ($earlybird = $result->fetchObject()) {
    if (REQUEST_TIME <= $earlybird->date) {
      if (strpos($earlybird->discount, '%') !== FALSE) {
        return - (floatval($earlybird->discount) / 100 * $product->price);
      }
      else {
        return - (floatval($earlybird->discount));
      }
    }
  }
}

/**
 * Implements hook_order().
 *
 * Adds the line item discount for earlybird discounts.
 */
function uc_earlybird_uc_order($op, &$arg1, $arg2) {
  if ($op == 'save') {
    $type = 'earlybird';
    foreach ($arg1->line_items as $key => $line_item) {
      if ($line_item['type'] == $type) {
        uc_order_delete_line_item($line_item['line_item_id']);
      }
    }

    db_delete('uc_order_line_items')
      ->condition('order_id', $arg1->order_id)
      ->condition('type', $key)
      ->execute();

    $discount = 0;
    $numDiscounts = 0;
    foreach ($arg1->products as $product) {
      $discount = _uc_earlybird_calculate_discount($product);
      if ($discount < 0) {
        uc_order_line_item_add($arg1->order_id, $type, 'Early bird discount', $discount * $product->qty, NULL, NULL);
      }
    }
  }
}