DROP TRIGGER  IF EXISTS  trigger_inc_ticket_usage_count;
DELIMITER $$
CREATE TRIGGER trigger_inc_ticket_usage_count
AFTER INSERT ON `door_log` FOR EACH ROW
begin
		/*DECLARE p_usage_count Integer;*/
		DECLARE p_count_all Integer;
		DECLARE p_count_all_2 Integer;
		DECLARE p_from DATETIME;
		DECLARE p_usage_count Integer;
		DECLARE p_max_usage_count Integer;
        
        delete from devlog;
        /** van vendég*/
		IF NEW.id_customer is  not null 
			/*van kártya*/
			and NEW.id_card is  not null
            /**van bérlet*/
            and NEW.id_ticket_current is not null
            /**bemozgás volt*/
			
		then
        
			if  NEW.direction  = 7 then
				insert into devlog ( msg) values('direction = in');
				select count(*) into @p_count_all from door_log where  created_at >= CURDATE() and  id_ticket_current  = New.id_ticket_current  and direction = 7;
			
				insert into devlog ( msg) values( concat( 'count all' ,@p_count_all ) );
            
				IF @p_count_all = 1
				THEN
					select usage_count, max_usage_count into @p_usage_count ,@p_max_usage_count from ticket where id_ticket = NEW.id_ticket_current;
					update ticket set usage_count = usage_count +1 where id_ticket = NEW.id_ticket_current;
					insert into log (type,message, app, id_ticket, id_door_log,created_at, updated_at)
						values(
							30, concat('Bérlet használat (elotte: ',@p_usage_count, ' > utana: ' , @p_usage_count +1 , ' max: ', @p_max_usage_count, ')' ), ' trigger_inc_ticket',New.id_ticket_current, New.id_door_log,now(),now());
				else
					/**
						Innentől kezdve biztos, hogy nem ez az első belépés az aktuális napon.
						Ki kell számolnunk hányadik 3 órás intervallumban vagyunk az első belépéstől számítva.
						Pl. ha 06:00 kor volt az első belépés, akkor 07: 30 még nem von le újabb használatot,
						de a 09:00 már igen
					*/
					
					select     min(created_at) + INTERVAL  (3 * FLOOR(  ( ( HOUR(TIMEDIFF(min(created_at) , now() )) /3 ) ) ) ) hour as last_date
					into @p_from
					from door_log 
					where created_at > CURDATE() and id_customer is not null;
		   
									
					/**
						
					*/
					-- select count(*) into @p_count_all_2 from door_log where  created_at >=  p_from and id_ticket_current  ;
					select count(*) into @p_count_all_2 from door_log where  created_at >=  @p_from  and  id_ticket_current  = New.id_ticket_current  and direction = 7;
					
					-- insert into devlog ( msg) values(CONCAT( 'ticket count since last period begin: ', @p_count_all_2)  );
				   /**
					Ha az első belépéstől számítot aktuális 3 órás intervallumban ez az elős belépés, akkor növeljük a használatot
				   */
				   IF @p_count_all_2 = 1
				   THEN
					-- insert into devlog ( msg) values( 'need to increase usage count multiple intervals '  );
						select usage_count, max_usage_count into @p_usage_count ,@p_max_usage_count from ticket where id_ticket = NEW.id_ticket_current;
						update ticket set usage_count = usage_count +1 where id_ticket = New.id_ticket_current;
					
						insert into log (type,message, app, id_ticket, id_door_log,created_at, updated_at)
						values(
							40, concat('Bérlet használat/egy nap tobbszori (elotte: ',@p_usage_count, ' > utana: ' , @p_usage_count +1 , ' max: ', @p_max_usage_count, ')' ), ' trigger_inc_ticket',New.id_ticket_current, New.id_door_log,now(),now());
					
					END IF; -- end @p_count_all_2 = 1
					
				END IF;
            
            End IF; -- end type == 7 ( move in )
            
            
            
            IF NEW.direction  = 5 -- type move out
			then
				insert into devlog ( msg) values('bérlet kilépés...');
				update ticket set count_move_out = usage_count where id_ticket = NEW.id_ticket_current;   
            END IF; -- end type move out
            
			/**
				Van e érvényes bérlet státusz frissítése a bérletkártyán
				update card.flag and card.id_ticket_current
            
            */
            -- insert into devlog ( msg) values( 'updateing card state'   );
            UPDATE card as c1
			left JOIN ( select  ticket.id_card as id_card , max(ticket.id_ticket) as id_ticket
			from ticket 
			where ticket.start <= CURDATE() 
				and ticket.end >= curdate() 
                and ticket.status = 10 
				and ticket.count_move_out < ticket.max_usage_count    
                and ticket.id_card = New.id_card
                group by id_card               
			order by id_card desc  ) as t 
			on t.id_card = c1.id_card
			SET c1.flag  = case when t.id_card is null then ( c1.flag | 1 << 0  )  else ( c1.flag & ~(1 << 0)  )    end
            , c1.id_ticket_current = case when t.id_ticket is null then null else t.id_ticket end
			WHERE c1.type <> 50 and c1.id_card = New.id_card;
            
            
		END IF;
	          
END;
$$
DELIMITER ;