use inventory;

DELIMITER //
CREATE DEFINER=`root`@`localhost` TRIGGER `hibah_detil_after_update` AFTER UPDATE ON `hibah_detil` FOR EACH ROW 
BEGIN
	DECLARE VTANGGAL DATETIME;
	DECLARE VRUANGAN CHAR(10);
	DECLARE VBARANG, VBARANGRUANGAN, VBARANGX, VJENIS, VTMTK INT;
	
	IF NEW.STATUS != OLD.STATUS AND NEW.STATUS = 2 THEN
	
		SELECT 
			d.BARANG, h.TANGGAL,IF(h.TMTK = 1, IF(h.JENIS = 1,57,58), IF(h.JENIS = 1,55,56)), h.TMTK, h.RUANGAN INTO VBARANG, VTANGGAL, VJENIS, VTMTK, VRUANGAN
		FROM inventory.hibah h, inventory.hibah_detil d
		WHERE d.HIBAH = h.ID AND d.ID = NEW.ID;
		
		SELECT br.ID INTO VBARANGRUANGAN FROM inventory.barang_ruangan br WHERE br.BARANG = VBARANG AND br.RUANGAN = VRUANGAN;
		
		IF VJENIS = 57 OR VJENIS = 55 THEN
		
			IF VBARANGRUANGAN > 0 THEN
	 			SET VBARANGX = VBARANGRUANGAN;
	 		ELSE
	 			SET VBARANGX = (SELECT inventory.autoInsertBarangRuangan(VRUANGAN, VBARANG));
	 		END IF;
			INSERT INTO inventory.transaksi_stok_ruangan 
			(BARANG_RUANGAN, JENIS, REF, TANGGAL, JUMLAH)
			VALUES
			(VBARANGX, VJENIS, OLD.ID, VTANGGAL, OLD.QTY);
			
		ELSE
		
			IF VBARANGRUANGAN > 0 THEN
 				INSERT INTO inventory.transaksi_stok_ruangan 
				(BARANG_RUANGAN, JENIS, REF, TANGGAL, JUMLAH)
				VALUES
				(VBARANGRUANGAN, VJENIS, OLD.ID, VTANGGAL, OLD.QTY);
	 		END IF;
		
		END IF;
		
	END IF;
	
	
	IF NEW.STATUS != OLD.STATUS AND OLD.STATUS = 2 AND NEW.STATUS = 1 THEN
		SELECT 
			br.ID, h.TANGGAL,IF(h.TMTK = 1, IF(h.JENIS = 1,72,73), IF(h.JENIS = 1,70,71)), h.TMTK INTO VBARANG, VTANGGAL, VJENIS, VTMTK
		FROM inventory.hibah h, inventory.hibah_detil d, inventory.barang_ruangan br
		WHERE br.BARANG = d.BARANG AND br.RUANGAN = h.RUANGAN AND d.HIBAH = h.ID AND d.ID = OLD.ID;
		
		IF FOUND_ROWS() > 0 THEN
			INSERT INTO inventory.transaksi_stok_ruangan 
			(BARANG_RUANGAN, JENIS, REF, TANGGAL, JUMLAH)
			VALUES
			(VBARANG, VJENIS, OLD.ID, VTANGGAL, OLD.QTY);
		END IF;
	END IF;
	
END;
//

DELIMITER ;