<?php

declare(strict_types=1);

namespace App\EventListener\DataContainer;

use App\Model\IsoProductMonthModel;
use Contao\Controller;
use Contao\CoreBundle\DependencyInjection\Attribute\AsCallback;
use Contao\DataContainer;
use Contao\Date;
use Doctrine\DBAL\Connection;
use Isotope\Model\Product;

#[AsCallback(table: "tl_iso_product", target: "config.onsubmit")]
class IsoProductOnSubmitListener
{
    private Connection $db;

    public function __construct()
    {
        $this->db = Controller::getContainer()->get('database_connection');
    }


    public function __invoke(DataContainer $dc): void
    {
        $Product = Product::findByPk($dc->id);
        if (!$dc->activeRecord->attr_datum || $dc->activeRecord->type == 2)
        {
            $this->db->executeQuery("UPDATE tl_iso_product SET attr_datum = ? WHERE id = ?",[9999999999,$Product->id]);

            $strDate = 'Auf Anfrage';
        } else {
            $Date = new Date($dc->activeRecord->attr_datum);
            $strDate = Date::parse('F Y',$Date->monthBegin);
        }

        if (($Month = IsoProductMonthModel::findOneByMonth($strDate)) === null)
        {
            $Month = new IsoProductMonthModel();
            $arrMonth = [
                'tstamp' => time(),
                'month'  => $strDate
            ];
            $Month->setRow($arrMonth);
            $Month->save();
            $Month->refresh();
        }

        $this->db->executeQuery("UPDATE tl_iso_product SET attr_monthyear = ? WHERE id = ?",[$Month->id,$Product->id]);

    }
}
