/**
 * For participant and member delete, decrement the code usage value since
 * they are no longer using the code.
 * When a contact is deleted, we should also delete their tracking info/usage.
 * When removing participant (and additional) from events, also delete their tracking info/usage.
 */
function cividiscount_civicrm_pre($op, $name, $id, &$obj)
{
    if ($op == 'delete') {
        if (in_array($name, array('Individual', 'Household', 'Organization'))) {
            $result = _cividiscount_get_item_by_track(null, null, $id);
        } elseif ($name == 'Participant') {
            if (($result = _cividiscount_get_participant($id)) && ($contactid = $result['contact_id'])) {
                $result = _cividiscount_get_item_by_track('civicrm_participant', $id, $contactid);
            }
        } else {
            if ($name == 'Membership') {
                if (($result = _cividiscount_get_membership($id)) && ($contactid = $result['contact_id'])) {
                    $result = _cividiscount_get_item_by_track('civicrm_membership', $id, $contactid);
                }
            } else {
                return false;
            }
        }
        if (!empty($result)) {
            foreach ($result as $value) {
                if (!empty($value['item_id'])) {
                    CRM_CiviDiscount_BAO_Item::decrementUsage($value['item_id']);
                }
                if (!empty($value['id'])) {
                    CRM_CiviDiscount_BAO_Track::del($value['id']);
                }
            }
        }
    }
}