CREATE or REPLACE FUNCTION  voicemail_on(varchar, varchar) RETURNS INTEGER AS '
  DECLARE
    _id int;
    _profile int;
    _contact int;
    _when_loggedoff_number varchar;
  BEGIN
    select into _id, _profile, _contact phoneline.id, phoneline.profile, phoneline.contact
      from phoneline
     where phoneline.company = ( select id from company  where shortname = $1 and status = ''active'') and
           extension = $2 and phoneline.status <> ''deleted'';
    update phoneline_forwarding set when_busy = ''voicemail'', when_loggedoff = ''voicemail'', when_noanswer = ''voicemail''
     where profile = _profile and phoneline = _id;
    insert into history (created, creator, contact, type, lookup, lookupid, value) values
           (now(), _contact, _contact, ''update'', ''phoneline'', _id,
           ''set voicemail on'');
    return ''0'';
  END;
' LANGUAGE plpgsql;

CREATE or REPLACE FUNCTION  voicemail_off(varchar, varchar) RETURNS INTEGER AS '
  DECLARE
    _id int;
    _profile int;
    _contact int;
    _when_loggedoff_number varchar;
  BEGIN
    select into _id, _profile, _contact phoneline.id, phoneline.profile, phoneline.contact
      from phoneline
     where phoneline.company = ( select id from company  where shortname = $1 and status = ''active'') and
           extension = $2 and phoneline.status <> ''deleted'';
    update phoneline_forwarding set when_busy = ''refuse'', when_loggedoff = ''refuse'', when_noanswer = ''refuse'' where profile = _profile and phoneline = _id;
    insert into history (created, creator, contact, type, lookup, lookupid, value) values
           (now(), _contact, _contact, ''update'', ''phoneline'', _id,
           ''set voicemail off'');
    return ''0'';
  END;
' LANGUAGE plpgsql;

