USE inventory;

DROP TRIGGER IF EXISTS inventory.harga_barang_log_penerimaan_after_update;

DELIMITER //

CREATE DEFINER=`root`@`localhost` TRIGGER `harga_barang_log_penerimaan_after_update` AFTER UPDATE ON `harga_barang_log_penerimaan` FOR EACH ROW BEGIN
	
	IF NEW.STATUS != OLD.STATUS AND NEW.STATUS = 99 AND NEW.IS_UPDATE_CORE = 1 THEN
        IF EXISTS(SELECT 1
		  FROM inventory.harga_barang
		 WHERE BARANG = NEW.BARANG AND STATUS = 1) THEN	
			UPDATE inventory.harga_barang SET STATUS = 0 WHERE BARANG = NEW.BARANG AND STATUS = 1;
		END IF;

		IF NOT EXISTS(SELECT 1
		  FROM inventory.harga_barang
		 WHERE REF_PENERIMAAN = NEW.REF_PENERIMAAN) THEN	
			INSERT INTO inventory.harga_barang (BARANG, HARGA_BELI, HARGA_JUAL, PPN, MASA_BERLAKU, TANGGAL, OLEH, STATUS, REF_PENERIMAAN, IS_UPDATE_BY_CORE) VALUES (NEW.BARANG, NEW.HARGA_BELI, NEW.HARGA_JUAL, NEW.PPN, NEW.MASA_BERLAKU, NEW.TANGGAL, NEW.OLEH, 1, NEW.REF_PENERIMAAN, 1);
		END IF;
	END IF;
END//
DELIMITER ;