<?php

declare(strict_types=1);

/*
 * This file is part of contao-weinanlieferung-bundle.
 *
 * (c) vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\WeinanlieferungBundle;

use Doctrine\DBAL\Connection;

class SlotChecker {

    private $db;

    public function __construct(Connection $connection) {
        $this->db = $connection;
    }

    public function checkTimeApplicableForSite(int $siteId, int $startTime, int $endTime, int $buffer=0,int $exceptionId=0): bool {
        // Get existing slots in the timeframe
        $sql = "SELECT COUNT(id) FROM tl_vr_wa_slot
WHERE
	pid = :pid
	AND
	(
		(
			time >= :start
			AND time <= :end
		)
		OR
		(
			time+duration*60 > :start
			AND time+duration*60 <= :end
		)
		OR
		(
			time < :start
			AND time+duration*60 > :end
		)
	)";
        $values = ['pid' => $siteId, 'start' => $startTime-$buffer, 'end' => $endTime+$buffer];

        if ($exceptionId > 0)
        {
            $sql .= " AND id != :exceptionId";
            $values['exceptionId'] = $exceptionId;
        }

        $ConflictingSlots = $this->db->prepare($sql)->executeQuery($values);

        return $ConflictingSlots->fetchOne() == true;
    }

}