<?php

declare(strict_types=1);

/*
 * This file is part of contao-weinanlieferung-bundle.
 *
 * (c) vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\WeinanlieferungBundle\EventListener\DataContainer;

use Contao\CoreBundle\ServiceAnnotation\Callback;
use Contao\DataContainer;
use Contao\Date;
use Doctrine\DBAL\Connection;

class WeinanlieferungSlotContainerListener
{
    /** @var Connection */
    protected $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }


    /**
     * @Callback(table="tl_vr_wa_slot", target="list.sorting.child_record")
     */
    public function onChildRecordCallback(array $row)
    {
        return sprintf('<div class="tl_content_left">%s %s</div>',Date::parse(Date::getNumericDateFormat(),$row['date']), Date::parse(Date::getNumericTimeFormat(),$row['time']));
    }

    /**
     * @Callback(table="tl_vr_wa_slot", target="config.onsubmit")
     */
    public function adjustTime(DataContainer $dc)
    {
        // Return if there is no active record (override all) or no start date has been set yet
        if (!$dc->activeRecord || empty($dc->activeRecord->date))
        {
            return;
        }

        $arrSet['time'] = strtotime(date('Y-m-d', $dc->activeRecord->date) . ' ' . date('H:i:s', $dc->activeRecord->time));

        $this->db->update("tl_vr_wa_slot",$arrSet,['id' => $dc->id]);
    }
}