<?php

namespace idoit\Module\SyneticsFlows\Model;

use idoit\Module\SyneticsFlows\Automation\Trigger\TriggerType\ScheduleTriggerType;

class ScheduleDao extends AutomationDao
{
    /**
     * @param int $id
     * @param string $time
     *
     * @return bool
     * @throws \isys_exception_database
     */
    public function isScheduled(int $id, string $time): bool
    {
        $query = "SELECT id FROM isys_flow_execution WHERE
           (finished IS NULL OR finished = '0000-00-00 00:00:00')
            AND isys_flow_execution__isys_flow_automation__id = {$this->convert_sql_id($id)}
            AND time = {$this->convert_sql_text($time) } limit 1";

        $alreadyScheduled = $this->retrieve($query)->count();
        if ($alreadyScheduled) {
            return true;
        }

        return false;
    }

    public function cleanUpUpcoming(int $id): bool
    {
        $command = "DELETE FROM isys_flow_execution WHERE
           (finished IS NULL OR finished = '0000-00-00 00:00:00')
            AND isys_flow_execution__isys_flow_automation__id = {$this->convert_sql_id($id)}
            AND time > now()";
        return $this->update($command) && $this->apply_update();
    }
}
