<?php

/**
 * Class CfTasks
 */
class CfTasks
{
    /** @var PDO $connection */
    private $cfSettings;

    /** @var PDO $connection */
    private $cfdbConnection;


    /**
     * CfTasks constructor.
     */
    public function __construct()
    {
        $this->cfdbConnection = CfdbPdo::getInstance()->getConnection();
        $this->cfSettings = CfSettings::getInstance();
    }

    /**
     * @param $selectSQL
     * @param $category
     */
    public function refreshHealthDiagnosticsFailures($username)
    {
        // set err mode to throw exception when wrong query
        $this->cfdbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->cfdbConnection->prepare("SET rbac.filter = '!(any)'")->execute();
        $this->cfdbConnection->beginTransaction();
        try {
            $this->cfdbConnection->prepare('TRUNCATE __health_diagnostics_failures')->execute();
            foreach (HealthDiagnosticReportModel::$reportTypes as $type) {
                $model = new HealthDiagnosticReportModel($username, $type);
                // insert into health_diagnostics_failures hosts from health diagnostics sql directly
                $insertSQL = "INSERT INTO __health_diagnostics_failures
                              SELECT p.key as hostkey, ? as category FROM ({$model->getSql()}) p";
                $this->cfdbConnection->prepare($insertSQL)->execute([$type]);
            }
            $this->cfdbConnection->commit();
        } catch (Exception $exception) {
            $this->cfdbConnection->rollBack();
            throw $exception;
        }
    }

}
