<?php

class ControllerCommonTempfiles extends Controller
{
    public function delete()
    {
        $this->load->dmodel('setting/task');
        $this->ftrgeralregistry->permissaoAcessoUrl($this->dmodel_setting_task->getTaskByType(Type_TaskUrl::TP_TaskDelTempfiles));

        $this->deleteEtiquetas();
        $this->deleteWatermarkCacheFolder();
    }

    public function deleteEtiquetas()
    {
        $data = array(
            'date_last_acting' => $this->db->dataAtual(),
            'type' => Type_TaskUrl::TP_TaskDelTempfiles
        );

        $this->dmodel_setting_task->editDateTaskByType($data);

        $minutos = Type_ExecTimeTask::Tp_ExecTime_1min / 60;
        $tempoLimite = (new DateTime($this->db->dataAtual()))->add(new DateInterval('PT' . $minutos . 'M'));
        $etiquetas = glob(DIR_CACHE . 'cachefiles/*.pdf');
        if ($etiquetas) {
            $tz = new DateTimeZone('America/Sao_Paulo');
            $dataatual = new DateTime($this->db->dataAtual());
            $dataatual->setTimeZone($tz);
            foreach ($etiquetas as $etiqueta) {
                if (file_exists($etiqueta)) {

                    $datafile = DateTime::createFromFormat('d/m/Y', date("d/m/Y", strtotime('+2 days', filectime($etiqueta))));
                    $datafile->setTimeZone($tz);
                    if ($dataatual > $datafile) {
                        unlink($etiqueta);
                    }
                }

                if (($tempoLimite) && (new DateTime($this->db->dataAtual()) > $tempoLimite)) {
                    break;
                }
            }
        }
    }

    public function deleteWatermarkCacheFolder()
    {
        $watermark_config = $this->config->get('config_watermark');
        if (!$watermark_config) {
            //apaga as pastas de cache da marca d'agua
            $watarmark_cache_dir = DIR_IMAGE . "/cache/watermark/";
            if (is_dir($watarmark_cache_dir)) {
                ftr_geral::deleteFolder($watarmark_cache_dir);
            }
        }
    }
}