


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 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;


