USE regonline;

DROP TRIGGER IF EXISTS regonline.reservasi_after_update;

DELIMITER //
CREATE DEFINER=`root`@`localhost` TRIGGER `regonline`.`reservasi_after_update` AFTER UPDATE ON `reservasi` FOR EACH ROW BEGIN
    IF NEW.NO_REF_BPJS != OLD.NO_REF_BPJS THEN
        UPDATE log_reservasi l SET l.FLAG = 9 WHERE l.kodebooking = NEW.ID AND l.STATUS = 0;
    END IF;
    IF NEW.NIK != OLD.NIK THEN
        UPDATE log_reservasi l SET l.FLAG = 9 WHERE l.kodebooking = NEW.ID AND l.STATUS = 0;
    END IF;
    IF NEW.CONTACT != OLD.CONTACT THEN
        UPDATE log_reservasi l SET l.FLAG = 9 WHERE l.kodebooking = NEW.ID AND l.STATUS = 0;
    END IF;
    IF NEW.NO_KARTU_BPJS != OLD.NO_KARTU_BPJS THEN
        UPDATE log_reservasi l SET l.FLAG = 9 WHERE l.kodebooking = NEW.ID AND l.STATUS = 0;
    END IF;
    IF NEW.JENIS_KUNJUNGAN != OLD.JENIS_KUNJUNGAN THEN
        UPDATE log_reservasi l SET l.FLAG = 9 WHERE l.kodebooking = NEW.ID AND l.STATUS = 0;
    END IF;
    
    IF NEW.JENIS_APLIKASI = 5 THEN 
        IF NEW.STATUS != OLD.STATUS AND NEW.STATUS = 2 THEN
            IF(NEW.ANTRIAN_POLI > 0) THEN
                INSERT INTO antrian_poli(ASAL_REF,REF,NOMOR,POLI,TANGGAL,STATUS) VALUES (2,NEW.ID, NEW.ANTRIAN_POLI, NEW.POLI, NEW.TANGGALKUNJUNGAN,1);
            END IF;
        END IF;
    ELSE
        UPDATE antrian_poli SET STATUS = NEW.STATUS WHERE ASAL_REF=1 AND REF = NEW.ID;	
    END IF;
    
    IF NEW.IS_BATAL_MJKN = 0 THEN
        IF NEW.STATUS != OLD.STATUS AND NEW.STATUS = 0 THEN
            UPDATE log_reservasi l SET l.STATUS = 0 WHERE l.kodebooking = NEW.ID;
        END IF;
    ELSE
    	IF NEW.STATUS != OLD.STATUS AND NEW.STATUS = 0 THEN
            UPDATE log_reservasi l SET l.STATUS = 0, l.RESPONSE = 'Batal By MJKN' WHERE l.kodebooking = NEW.ID;
        END IF;
    END IF;
END//
DELIMITER ;