USE `inventory`;

DROP TRIGGER IF EXISTS `inventory`.`barang_produksi_after_update`;
DELIMITER //
CREATE DEFINER=`root`@`localhost` TRIGGER `barang_produksi_after_update` AFTER UPDATE ON `barang_produksi` FOR EACH ROW BEGIN
	DECLARE VTANGGAL DATETIME;
	DECLARE VRUANGAN CHAR(10);
	DECLARE VBARANG,VBARANGRUANGAN INT(20);
	
	
	IF NEW.STATUS != OLD.STATUS AND NEW.STATUS = 2 THEN
	
		SELECT IF(br.ID IS NULL,0,br.ID), pb.TANGGAL INTO VBARANG, VTANGGAL
			FROM barang_produksi pb
			LEFT JOIN barang_ruangan br ON br.RUANGAN = pb.RUANGAN AND br.BARANG = pb.BARANG
		WHERE pb.ID = OLD.ID;
		
		IF FOUND_ROWS() > 0 THEN
			IF VBARANG > 0 THEN
				SET VBARANGRUANGAN = VBARANG;
			ELSE
				SET VBARANGRUANGAN = (SELECT inventory.autoInsertBarangRuangan(OLD.RUANGAN, OLD.BARANG));
			END IF;
		ELSE
			SET VBARANGRUANGAN = (SELECT inventory.autoInsertBarangRuangan(OLD.RUANGAN, OLD.BARANG));
		END IF;
		
		INSERT INTO inventory.transaksi_stok_ruangan 
		(BARANG_RUANGAN, JENIS, REF, TANGGAL, JUMLAH) VALUES (VBARANGRUANGAN, 51, OLD.ID, VTANGGAL, NEW.QTY);
		
		UPDATE inventory.barang_produksi_detil SET STATUS = 2 WHERE PRODUKSI = OLD.ID;
		
	END IF;
	
	
	
	IF NEW.STATUS != OLD.STATUS AND OLD.STATUS = 2 AND NEW.STATUS = 1 THEN
	
		SELECT IF(br.ID IS NULL,0,br.ID), pb.TANGGAL INTO VBARANG, VTANGGAL
			FROM barang_produksi pb
			LEFT JOIN barang_ruangan br ON br.RUANGAN = pb.RUANGAN AND br.BARANG = pb.BARANG
		WHERE pb.ID = OLD.ID;
		
		IF FOUND_ROWS() > 0 THEN
			IF VBARANG > 0 THEN
				SET VBARANGRUANGAN = VBARANG;
			ELSE
				SET VBARANGRUANGAN = (SELECT inventory.autoInsertBarangRuangan(OLD.RUANGAN, OLD.BARANG));
			END IF;
		ELSE
			SET VBARANGRUANGAN = (SELECT inventory.autoInsertBarangRuangan(OLD.RUANGAN, OLD.BARANG));
		END IF;
		
		INSERT INTO inventory.transaksi_stok_ruangan 
		(BARANG_RUANGAN, JENIS, REF, TANGGAL, JUMLAH) VALUES (VBARANGRUANGAN, 67, OLD.ID, VTANGGAL, OLD.QTY);
		
		UPDATE inventory.barang_produksi_detil SET STATUS = 1 WHERE PRODUKSI = OLD.ID AND STATUS = 2;
		
	END IF;
END//
DELIMITER ;