CREATE TABLE pbx_organizacao
(
  id serial NOT NULL PRIMARY KEY,
  nome VARCHAR(128) NOT NULL,
  status INTEGER NOT NULL DEFAULT 1,
  master int not null DEFAULT 0, 
  updated_at timestamp without time zone,
  created_at timestamp without time zone NOT NULL DEFAULT now()
);

CREATE TABLE pbx_organizacao_usuarios
(
	id SERIAL not null primary key,
	id_usuario INTEGER not null,
	id_organizacao INTEGER not null,
	updated_at timestamp without time zone,
	created_at timestamp without time zone NOT NULL DEFAULT now()
);

ALTER TABLE pbx_organizacao_usuarios ADD CONSTRAINT id_usuario FOREIGN KEY (id_usuario)
REFERENCES pbx_usuarios(id) ON DELETE CASCADE;

ALTER TABLE pbx_organizacao_usuarios ADD CONSTRAINT id_organizacao FOREIGN KEY (id_organizacao)
REFERENCES pbx_organizacao(id) ON DELETE CASCADE;

CREATE OR REPLACE FUNCTION public.tipoligacao(numfone character varying, entrada boolean DEFAULT true, organizacao int default 0)
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
declare tam integer;
declare dddfone integer;
declare ddddef integer;
declare nonoDigito integer;
declare numerofone varchar(18);
BEGIN	
	if(length(numfone) > 18)then 
	   numerofone = substring(numfone, '..................$');
	else 
	   numerofone = numfone;
        end if;
        
	ddddef = (select prm_ddd_padrao from pbx_parametros where org_id = organizacao);

	tam = length(strtoint(numerofone)::text);
	nonoDigito = strtoint( substring(substring(numerofone, '.........$'), 1, 1) ); 

	if((tam = 3) and (numerofone in('100', '128', '190', '191', '192', '193', '194', '197', '198', '199')))then 
		return 4;
	elsif((tam >= 8) and (substring(numerofone,1,4) in('0300','0500','0900','4000','4001','4002','4003','4004', '4005', '4006','4007','4008','4009','0800')))then 
		return 5;
	elsif(tam = 8)then   
		return  (case when(entrada)then 21 else 31 end);
	elsif(tam < 8)then   
		return 1;
	elsif((nonoDigito = 9) and (tam < 11))then /* Celular local */
		return  (case when(entrada)then 23 else 33 end);
	elseif((not entrada) and (substring(numerofone,1,2) = '00'))then
		return 35;
	end if;

	
	if(nonoDigito = 9)then 
		dddfone = substring(substring(numerofone, '...........$'), 1, 2);
	else
		dddfone = substring(substring(numerofone, '..........$'), 1, 2);
		 
	end if;

	if((nonoDigito = 9) and (dddfone <> ddddef))then
		return  (case when(entrada)then 24 else 34 end);
	elsif((nonoDigito = 9) and (dddfone = ddddef))then
		return  (case when(entrada)then 23 else 33 end);
	elsif(dddfone <> ddddef)then
		return  (case when(entrada)then 22 else 32 end);
	elsif(dddfone = ddddef)then
		return  (case when(entrada)then 21 else 31 end); 
	end if; 
	
	return 1;     
 	
END; 
$function$
;

ALTER TABLE pbx_usuarios ADD COLUMN org_padrao int;
------------------------------------------
-----    ADICAO DE ID NAS TABELAS    -----
------------------------------------------
DROP INDEX "idxSipRamaisNome";
DROP INDEX "pbx_usuarios_matricula_key";
DROP INDEX "idxUsuariosApelido";
DROP INDEX "idxGrupNome";
DROP INDEX "idxSiteNome";
DROP INDEX "idxUnqBase";
-----------------
ALTER TABLE pbx_grupo DROP CONSTRAINT "idxGrupNome";
ALTER TABLE pbx_usuarios DROP CONSTRAINT pbx_usuarios_new_matricula_key;
ALTER TABLE pbx_grupo_usuario DROP CONSTRAINT "pkGpUserId";
ALTER TABLE pbx_grupo ADD CONSTRAINT gp_id PRIMARY KEY (gp_id);
-----------------
-- AUTOMATIZADO NO IMPORTAEMPRESA.PHP
-- ALTER TABLE pbx_workflow_parametros DROP COLUMN wkf_id;
-- ALTER TABLE pbx_parametros DROP COLUMN id;
-- ALTER TABLE pbx_sip_general ADD COLUMN id SERIAL PRIMARY KEY;
-- ALTER TABLE pbx_iax_general ADD COLUMN id SERIAL PRIMARY KEY;
-- ALTER TABLE pbx_facilidades ADD COLUMN id SERIAL PRIMARY KEY;
-- ALTER TABLE pbx_features_general ADD COLUMN id SERIAL PRIMARY KEY;
-- ALTER TABLE pbx_features_featuremap ADD COLUMN id SERIAL PRIMARY KEY;
-- ALTER TABLE pbx_voicemail_general ADD COLUMN id SERIAL PRIMARY KEY;
-- ALTER TABLE pbx_workflow_parametros ADD COLUMN wkf_id SERIAL PRIMARY KEY;
-- ALTER TABLE pbx_parametros ADD COLUMN id SERIAL PRIMARY KEY;
-----------------

---------------------------------------------------------------
---------Correcao do tipo da senha do Conta e Senha------------
---------------------------------------------------------------
ALTER TABLE pbx_cs_usuarios
ALTER COLUMN senha TYPE VARCHAR(100);


---------------------------------------------------------------
---------Remocao do conflito entre nomes de status-------------
---------------------------------------------------------------
ALTER TABLE pbx_campanha_contato_status
DROP CONSTRAINT idxcontstatusnome;

---------------------------------------------------------------
--Troca de posicao da coluna ID para retirar conflitos do IAX--
---------------------------------------------------------------
ALTER TABLE pbx_iax_general 
ADD COLUMN id SERIAL PRIMARY key;

CREATE TABLE pbx_tokens (
	id serial NOT NULL PRIMARY KEY,
	"token" varchar(255) NOT NULL,
	id_usuario int4 NOT NULL,
	refresh_token varchar(255) NOT NULL,
	expired_at timestamp NULL,
	updated_at timestamp NULL,
	created_at timestamp NULL DEFAULT now()
);

CREATE TABLE pbx_meet (
	id SERIAL NOT NULL PRIMARY KEY,
	meet_id VARCHAR(255) NOT NULL,
	nome VARCHAR(255) NOT NULL,
	token VARCHAR(255) NOT NULL,
	status INT NOT NULL default(1),
	data_reg TIMESTAMP WITHOUT TIME ZONE DEFAULT(NOW())
);

CREATE TABLE pbx_meet_people (
	id SERIAL NOT NULL PRIMARY KEY,
	meet_id VARCHAR(255) NOT NULL,
	nome VARCHAR(255) NOT NULL,
	people_id VARCHAR(50) NOT NULL,
	left_meet TIMESTAMP WITHOUT TIME ZONE,
	join_meet TIMESTAMP WITHOUT TIME ZONE DEFAULT(NOW())
);

ALTER TABLE pbx_parametros DROP COLUMN prm_chat_api_supervisor;
ALTER TABLE pbx_parametros DROP COLUMN prm_media_simultaneo;
ALTER TABLE pbx_parametros ADD COLUMN prm_url_meet VARCHAR(250);