SET AUTOCOMMIT=0;

USE billing;

ALTER TABLE products CHANGE COLUMN class class ENUM('sippeering', 'pstnpeering', 'reseller', 'sipaccount', 'pbxaccount') NOT NULL;

INSERT INTO products VALUES
  (NULL, NULL, 'sipaccount', 'SIP_ACCOUNT', 'Basic SIP Account', 1, NULL, NULL, NULL);
SELECT LAST_INSERT_ID() INTO @sip_id;
UPDATE billing_mappings SET product_id = @sip_id WHERE product_id IS NULL;

INSERT INTO products VALUES
  (NULL, NULL, 'pbxaccount', 'PBX_ACCOUNT', 'Cloud PBX Account', 1, NULL, NULL, NULL);

USE provisioning;

ALTER TABLE voip_subscribers 
  ADD COLUMN is_pbx_group TINYINT(1) NOT NULL DEFAULT 0 AFTER webpassword;
ALTER TABLE voip_subscribers 
  CHANGE COLUMN autoconf_group_id pbx_group_id INT(11) UNSIGNED DEFAULT NULL;
ALTER TABLE voip_subscribers 
  DROP COLUMN autoconf_displayname;

CREATE TABLE `voip_pbx_groups` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `contract_id` int(11) unsigned NOT NULL,
  `subscriber_id` int(11) unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  `extension` varchar(255) DEFAULT NULL,
  `hunt_policy` enum('serial','parallel') NOT NULL DEFAULT 'serial',
  `hunt_policy_timeout` int(4) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `contract_idx` (`contract_id`),
  KEY `subscriber_idx` (`subscriber_id`),
  CONSTRAINT `fk_v_sub_group` FOREIGN KEY (`subscriber_id`) REFERENCES `voip_subscribers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO voip_preference_groups (name) values ('Cloud PBX');
SELECT LAST_INSERT_ID() INTO @vpg_id;

UPDATE voip_preferences SET 
  voip_preference_groups_id = @vpg_id, 
  internal = 1 
WHERE attribute = 'cloud_pbx';

INSERT INTO voip_preferences 
  (voip_preference_groups_id, attribute, type, usr_pref, dom_pref, peer_pref, 
   internal, data_type, max_occur, description, modify_timestamp)
VALUES
  (@vpg_id, 'cloud_pbx_hunt_policy', 0, 1, 0, 0, 
   1, 'enum', 1, 'The hunting policy for PBX hunt groups.', '1970-01-01 00:00:00'),
  (@vpg_id, 'cloud_pbx_hunt_timeout', 1, 1, 0, 0, 
   1, 'int', 1, 'The serial timeout for hunting in PBX hunt groups.', '1970-01-01 00:00:00'),
  (@vpg_id, 'cloud_pbx_hunt_group', 0, 1, 0, 0, 
   1, 'string', 0, 'The members (as SIP URIs) of the PBX hunt group.', '1970-01-01 00:00:00'),
  (@vpg_id, 'cloud_pbx_base_cli', 0, 1, 0, 0, 
   1, 'string', 1, 'The base CLI for the PBX extension.', '1970-01-01 00:00:00');

SELECT id INTO @hunt_id FROM voip_preferences WHERE attribute = 'cloud_pbx_hunt_policy';
INSERT INTO voip_preferences_enum
  (preference_id, label, value, usr_pref, dom_pref, peer_pref, default_val)
  VALUES
  (@hunt_id, 'serial', 'serial', 1, 0, 0, 1),
  (@hunt_id, 'parallel', 'parallel', 1, 0, 0, 0);

COMMIT;
