
USE `inventory`;
DROP TRIGGER IF EXISTS `penerimaan_barang_after_update`;
SET @OLDTMP_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_ENGINE_SUBSTITUTION';
DELIMITER //
CREATE TRIGGER `penerimaan_barang_after_update` AFTER UPDATE ON `penerimaan_barang` FOR EACH ROW BEGIN
	IF OLD.STATUS != NEW.STATUS AND OLD.STATUS = 1 AND NEW.STATUS = 2 THEN
		UPDATE inventory.penerimaan_barang_detil
		   SET STATUS = 2, FINAL = (FINAL+1)
		 WHERE PENERIMAAN = NEW.ID
		   AND STATUS = 1;
		   
		IF EXISTS(SELECT 1 FROM mysql.innodb_table_stats r WHERE r.database_name = 'bridge' AND r.table_name = 'ska_penerimaan_execute') THEN
			INSERT INTO bridge.ska_penerimaan_execute (PENERIMAAN, JENIS, FLAG) VALUES (OLD.REF_SKA,2,1);
		END IF;
		
	END IF;
	
	
	IF OLD.STATUS != NEW.STATUS AND OLD.STATUS = 2 AND NEW.STATUS = 1 THEN 
		UPDATE inventory.penerimaan_barang_detil
		   SET STATUS = 1, BATAL = (BATAL+1)
		 WHERE PENERIMAAN = OLD.ID
		   AND STATUS = 2;
			   
		IF EXISTS(SELECT 1 FROM mysql.innodb_table_stats r WHERE r.database_name = 'bridge' AND r.table_name = 'ska_penerimaan_execute') THEN
			INSERT INTO bridge.ska_penerimaan_execute (PENERIMAAN, JENIS, FLAG) VALUES (OLD.REF_SKA,1,1);
		END IF;
		
	END IF;
	
	
	IF OLD.STATUS != NEW.STATUS AND OLD.STATUS = 1 AND NEW.STATUS = 0 THEN
		UPDATE inventory.penerimaan_barang_detil
		   SET STATUS = 0
		 WHERE PENERIMAAN = NEW.ID
		   AND STATUS = 1;
		
		IF EXISTS(SELECT 1 FROM mysql.innodb_table_stats r WHERE r.database_name = 'bridge' AND r.table_name = 'ska_penerimaan_execute') THEN
			INSERT INTO bridge.ska_penerimaan_execute (PENERIMAAN, JENIS, FLAG) VALUES (OLD.REF_SKA,0,1);
		END IF;
		
	END IF;
	
END//
DELIMITER ;
