CREATE OR REPLACE FUNCTION food600.doplnuctdendosksez(
	cdata integer)
    RETURNS integer
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE 
	zoznamkas CURSOR FOR SELECT DISTINCT id_kas as id_kas from food600.sk__sez WHERE uct_den IS NULL and c_data=cdata;
	zoznamkas1 CURSOR FOR SELECT DISTINCT id_kas as id_kas from food600.sk__sez_a WHERE uct_den IS NULL and c_data=cdata;
	xhodina CHARACTER(2) DEFAULT '08';
	kasa CHARACTER(2);
	midkas CHARACTER(2);
	mdone INTEGER DEFAULT 1;
BEGIN

OPEN zoznamkas;
WHILE (mdone>0) LOOP
	FETCH zoznamkas INTO kasa;
	IF kasa ISNULL THEN
		mdone:=0;
	ELSE
		SELECT id_kas INTO midkas FROM food600.hodiny_uzaverek WHERE id_kas=kasa AND c_data=cdata LIMIT 1;
		IF midkas IS NULL THEN
			INSERT INTO food600.hodiny_uzaverek (id_kas, n_hodina, hodina, c_data) VALUES (kasa, 8, xhodina, cdata);
		END IF;
	END IF;
END LOOP;
CLOSE zoznamkas;
OPEN zoznamkas1;
WHILE (mdone>0) LOOP
	FETCH zoznamkas1 INTO kasa;
	IF kasa ISNULL THEN
		mdone:=0;
	ELSE
		SELECT id_kas INTO midkas FROM food600.hodiny_uzaverek WHERE id_kas=kasa AND c_data=cdata LIMIT 1;
		IF midkas IS NULL THEN
			INSERT INTO food600.hodiny_uzaverek (id_kas, n_hodina, hodina, c_data) VALUES (kasa, 8, xhodina, cdata);
		END IF;
	END IF;
END LOOP;
CLOSE zoznamkas1;
UPDATE food600.hodiny_uzaverek SET n_hodina=(hodina::INTEGER) WHERE n_hodina=0 OR n_hodina IS NULL;
UPDATE food600.hodiny_uzaverek SET c_stredisk=food_dat.c_stredisk FROM food600.food_dat WHERE hodiny_uzaverek.id_kas=food_dat.id and hodiny_uzaverek.c_data=food_dat.c_data;

UPDATE food600.sk__sez SET uct_den=to_date(SUBSTR(sk__sez.uzaverka, 7, 2)||' '||SUBSTR(sk__sez.uzaverka, 5, 2)||'  '||SUBSTR(sk__sez.uzaverka, 1, 4),'DD MM YYYY')-1 FROM food600.hodiny_uzaverek WHERE sk__sez.id_kas=hodiny_uzaverek.id_kas AND sk__sez.uct_den IS NULL AND SUBSTR(sk__sez.uzaverka,10, 2)<=hodiny_uzaverek.hodina;
UPDATE food600.sk__sez SET uct_den=to_date(SUBSTR(sk__sez.uzaverka, 7, 2)||' '||SUBSTR(sk__sez.uzaverka, 5, 2)||'  '||SUBSTR(sk__sez.uzaverka, 1, 4),'DD MM YYYY') FROM food600.hodiny_uzaverek WHERE sk__sez.id_kas=hodiny_uzaverek.id_kas AND sk__sez.uct_den IS NULL AND SUBSTR(sk__sez.uzaverka, 10, 2)>hodiny_uzaverek.hodina;

UPDATE food600.sk__sez_a SET uct_den=to_date(SUBSTR(sk__sez_a.uzaverka, 7, 2)||' '||SUBSTR(sk__sez_a.uzaverka, 5, 2)||'  '||SUBSTR(sk__sez_a.uzaverka, 1, 4),'DD MM YYYY')-1 FROM food600.hodiny_uzaverek WHERE sk__sez_a.id_kas=hodiny_uzaverek.id_kas AND sk__sez_a.uct_den IS NULL AND SUBSTR(sk__sez_a.uzaverka, 10, 2)<=hodiny_uzaverek.hodina;
UPDATE food600.sk__sez_a SET uct_den=to_date(SUBSTR(sk__sez_a.uzaverka, 7, 2)||' '||SUBSTR(sk__sez_a.uzaverka, 5, 2)||'  '||SUBSTR(sk__sez_a.uzaverka, 1, 4),'DD MM YYYY') FROM food600.hodiny_uzaverek WHERE sk__sez_a.id_kas=hodiny_uzaverek.id_kas AND sk__sez_a.uct_den IS NULL AND SUBSTR(sk__sez_a.uzaverka, 10, 2)>hodiny_uzaverek.hodina;
RETURN 1;
END
$BODY$;
