<?php

/**
 * OBG Customizations
 *
 * Copyright (c) 2021 vonRotenberg
 *
 * @license commercial
 */

namespace vonRotenberg\RealEstateListingBundle\EventListener;

use Contao\CoreBundle\ServiceAnnotation\Callback;
use Contao\Database;
use Contao\DataContainer;
use Contao\System;
use Doctrine\DBAL\Connection;
use Exception;
use vonRotenberg\RealEstateListingBundle\Model\ManagedPropertyModel;
use vonRotenberg\RealEstateListingBundle\Model\RealEstateCategoriesModel;

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

    /**
     * @Callback(table="tl_vr_real_estate_assets", target="fields.managedPropertyId.options")
     */
    public function onAddCustomRegexp(?DataContainer $dc): array
    {
        $arrOptions = [];

        if (($Properties = ManagedPropertyModel::findAllPublished()) !== null)
        {
            foreach ($Properties as $property)
            {
                $arrOptions[$property->city][$property->id] = $property->address . ' [' . $property->city . ']';
            }
        }

        return $arrOptions;
    }

    /**
     * @Callback(table="tl_vr_real_estate_assets", target="config.onsubmit")
     */
    public function setCoordinatesToAsset(DataContainer $dc)
    {
        if (!$dc->id || !$dc->activeRecord->managedPropertyId || ($Property = ManagedPropertyModel::findByPk($dc->activeRecord->managedPropertyId)) === null) {
            return;
        }

        $this->db->update('tl_vr_real_estate_assets', ['geox' => $Property->geox, 'geoy' => $Property->geoy],['id' => $dc->id]);
    }

    /**
     * @Callback(table="tl_vr_real_estate_assets", target="fields.alias.save")
     */
    public function generateAlias($varValue, DataContainer $dc)
    {
        $aliasExists = static function (string $alias) use ($dc): bool {
            $result = Database::getInstance()
                ->prepare("SELECT id FROM tl_vr_real_estate_assets WHERE alias=? AND id!=?")
                ->execute($alias, $dc->id);

            return $result->numRows > 0;
        };

        // Generate alias if there is none
        if (!$varValue)
        {
            $varValue = System::getContainer()->get('contao.slug')->generate($dc->activeRecord->title, [], $aliasExists);
        }
        elseif (preg_match('/^[1-9]\d*$/', $varValue))
        {
            throw new Exception(sprintf($GLOBALS['TL_LANG']['ERR']['aliasNumeric'], $varValue));
        }
        elseif ($aliasExists($varValue))
        {
            throw new Exception(sprintf($GLOBALS['TL_LANG']['ERR']['aliasExists'], $varValue));
        }

        return $varValue;
    }
}
