


CREATE OR REPLACE FUNCTION mostValuableClerk(months IN NUMBER) RETURN NUMBER
IS
    startMonat DATE;
    finalclerkid NUMBER;
    maxanzahlcleanings NUMBER;
BEGIN
    startMonat := ADD_MONTHS(SYSDATE,-months);

    SELECT CLERKID, Anzahl INTO finalclerkid, maxanzahlcleanings FROM
    (
    SELECT DISTINCT CLERKID, COUNT(CLERKID) AS Anzahl
        From
        (
        SELECT clcl.CLERKID
         FROM CLEANINGCLERK clcl
         INNER JOIN CLEANINGPLAN clpl ON clcl.CLEANINGPLANID = clpl.CLEANINGPLANID
         WHERE clpl."date" >= startMonat
         )
    GROUP BY CLERKID ORDER BY Anzahl desc
    )
    WHERE ROWNUM <= 1;

    return finalclerkid;
END;

CREATE OR REPLACE PROCEDURE getLastBookings(months IN NUMBER)
IS
    CURSOR bookingsCursor IS SELECT BOOKINGID FROM BOOKING WHERE ARRIVALDATE >= ADD_MONTHS(SYSDATE,-months);

BEGIN
        FOR booking IN bookingsCursor
        LOOP
            DBMS_OUTPUT.PUT_LINE(booking.BOOKINGID);
        END LOOP;
END;

CREATE OR REPLACE PROCEDURE rooms(clientz IN NUMBER, months IN NUMBER)

IS
    CURSOR roomCursor is
    SELECT br.ROOMNUMBER
    FROM BOOKINGROOM br INNER JOIN (
        SELECT *
        FROM BOOKING INNER JOIN CLIENT
        ON BOOKING.CLIENTID = CLIENT.PERSONID
        WHERE CLIENT.PERSONID = clientz AND BOOKING.ARRIVALDATE >= add_months(sysdate, -months)
    ) bookings ON br.BOOKINGID = bookings.BOOKINGID;
BEGIN
    FOR number IN roomCursor
        LOOP
            DBMS_OUTPUT.PUT_LINE(number.ROOMNUMBER);
        END LOOP;
END rooms;

CREATE OR REPLACE TRIGGER booking_created
BEFORE INSERT OR UPDATE
ON BOOKINGROOM
FOR EACH ROW
DECLARE
    cleaningDate DATE;
BEGIN
    SELECT arrivalDate INTO cleaningDate FROM BOOKING
    WHERE BOOKING.BOOKINGID = :NEW.bookingId;
    cleaningDate := cleaningDate - 1;
    INSERT INTO CLEANINGPLAN VALUES (cleaningplan_seq.nextval, cleaningDate, 90, :NEW.roomNumber);
END;

CREATE OR REPLACE TRIGGER cleaning_while_booked 
BEFORE INSERT OR UPDATE
ON CleaningPlan
FOR EACH ROW
DECLARE 
	bookingcount NUMBER;
BEGIN
	SELECT COUNT(bk.bookingId) INTO bookingcount 
	FROM Booking bk INNER JOIN BookingRoom br ON bk.bookingId = br.bookingId 
	WHERE br.roomNumber = :NEW.roomNUMBER AND bk.arrivalDate <= :NEW."date" AND bk.departureDate >= :NEW."date";
	IF bookingcount > 0 THEN
		RAISE_APPLICATION_ERROR(-20111, 'CleaningPlan liegt in gebuchtem Zeitraum');
	END IF;
END;

CREATE OR REPLACE TRIGGER total_price
AFTER INSERT OR UPDATE ON BOOKING
FOR EACH ROW
DECLARE
	total_price NUMBER;
        nights NUMBER;
BEGIN
        nights := :NEW.DEPARTUREDATE - :NEW.ARRIVALDATE;
        total_price := nights * :NEW.COST;
        dbms_output.put_line('Gesamtpreis:');
        dbms_output.put_line(total_price);
END;

