<?php

namespace CreoCode\ContaoFormSubmissions\Classes;

use Contao\Database;
use Contao\Config;
use Contao\FormModel;
use CreoCode\ContaoFormSubmissions\Model\FormSubmissionsSetModel;

class Cron
{
    /**
     * Performs daily anonymisation and deletion of old submissions.
     */
    public static function dailyCron(): void
    {
        $lastRun = Config::get('daily_run');

        if ($lastRun && $lastRun >= strtotime('-1 day')) {
            return;
        }

        $arrFormSets = FormSubmissionsSetModel::findAll();

        if ($arrFormSets === null) {
            Config::persist('daily_run', time());
            return;
        }

        $db = Database::getInstance();

        foreach ($arrFormSets as $formSet) {
            $form = FormModel::findById($formSet->form_id);

            // Skip if form was deleted
            if ($form === null) {
                continue;
            }

            // Anonymise: blank stored submission data older than threshold
            $anonymiseAfter = (int) $form->cc_anonymise_after;
            if ($anonymiseAfter > 0) {
                $tstampAfter = strtotime('-' . $anonymiseAfter . ' month', time());
                $db->prepare(
                    'UPDATE tl_form_submissions_data SET data=?, arrSubmitted=?, arrLabels=?, arrFields=?
                     WHERE form_id=? AND tstamp < ?'
                )->execute('', '', '', '', $form->id, $tstampAfter);
            }

            // Delete: remove submissions and their data older than threshold
            $deleteAfter = (int) $form->cc_delete_after;
            if ($deleteAfter > 0) {
                $tstampAfter = strtotime('-' . $deleteAfter . ' month', time());
                $db->prepare(
                    'DELETE FROM tl_form_submissions_data WHERE form_id=? AND tstamp < ?'
                )->execute($form->id, $tstampAfter);
                $db->prepare(
                    'DELETE FROM tl_form_submissions WHERE pid=? AND tstamp < ?'
                )->execute($formSet->id, $tstampAfter);
            }
        }

        Config::persist('daily_run', time());
    }
}
