<?php

$GLOBALS['TL_DCA']['tl_td_erg_liga'] = array
(

    // Config
    'config' => array
    (
        'dataContainer' => 'Table',
        'ptable' => 'tl_td_erg_saison',
        'ctable' => array('tl_td_erg_liga_mannschaft'),
        'enableVersioning' => true,
        'sql' => array
        (
            'keys' => array
            (
                'id' => 'primary',
                'pid' => 'index',
                'pid,bereich,liga,turnierart,nr' => 'unique',
            )
        ),
        'onsubmit_callback' => array(array('tl_td_erg_liga', 'submitCallback')),
        'ondelete_callback' => array(array('tl_td_erg_liga', 'deleteCallback'))
    ),

    // List
    'list' => array
    (
        'sorting' => array
        (
            'mode' => 4,
            'flag' => 12,
            'fields' => array('bereich', 'bereichOrder', 'ligaOrder', 'turnierartOrder', 'nr', 'bezeichnung'),
            'headerFields' => array('jahr'),
            'panelLayout' => 'sort,filter;search,limit',
            'child_record_callback' => array('tl_td_erg_liga', 'listeLigen'),
            'child_record_class' => 'no_padding',
            'disableGrouping' => false,
            'filter' => \Tanzsport\Ergebnisarchiv::getLigabereicheByUser(),
        ),
        'label' => array
        (
            'fields' => array('bereich'),
            'format' => '%1$s'
        ),
        'global_operations' => array
        (/*
			'all' => array
			(
				'label' => &$GLOBALS['TL_LANG']['MSC']['all'],
				'href' => 'act=select',
				'class' => 'header_edit_all',
				'attributes' => 'onclick="Backend.getScrollOffset();" accesskey="e"'
			)
			*/
        ),
        'operations' => array
        (
            'edit' => array
            (
                'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['edit'],
                'href' => 'act=edit',
                'icon' => 'edit.gif'
            ),
            'mannschaften' => array
            (
                'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['mannschaften'],
                'href' => 'table=tl_td_erg_liga_mannschaft',
                'icon' => 'bundles/contaoformationen/icons/mannschaften.gif'
            ),
            'turniere' => array
            (
                'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['turniere'],
                'href' => 'table=tl_td_erg_liga_turnier',
                'icon' => 'bundles/contaoformationen/icons/turniere.gif'
            ),
            /*
            'copy' => array
            (
                'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['copy'],
                'href' => 'act=copy',
                'icon' => 'copy.gif'
            ),
            */
            'delete' => array
            (
                'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['delete'],
                'href' => 'act=delete',
                'icon' => 'delete.gif',
                'attributes' => 'onclick="if(!confirm(\'' . ($GLOBALS['TL_LANG']['MSC']['deleteConfirm'] ?? null) . '\'))return false;Backend.getScrollOffset()"',
                'button_callback' => array('tl_td_erg_liga', 'deleteIcon')
            ),
            'toggle' => array
            (
                'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['toggle'],
                'icon' => 'visible.gif',
                'attributes' => 'onclick="Backend.getScrollOffset();return AjaxRequest.toggleVisibility(this,%s)"',
                'button_callback' => array('tl_td_erg_liga', 'toggleIcon')
            ),
            'show' => array
            (
                'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['show'],
                'href' => 'act=show',
                'icon' => 'show.gif'
            )
        )
    ),

    // Palettes
    'palettes' => array
    (
        '__selector__' => array(''),
        'default' => '{liga_legend},bereich,liga,turnierart,nr,bezeichnung,text;{veroeffentlichung_legend},published'
    ),

    // Subpalettes
    'subpalettes' => array
    (
        '' => ''
    ),

    // Fields
    'fields' => array
    (
        'id' => array
        (
            'sql' => "int(10) unsigned NOT NULL auto_increment",
        ),
        'pid' => array
        (
            'foreignKey' => 'tl_td_erg_saison.jahr',
            'sql' => "int(10) unsigned NOT NULL default '0'",
            'relation' => array('type' => 'belongsTo', 'load' => 'eager')
        ),
        'tstamp' => array
        (
            'sql' => "int(10) unsigned NOT NULL default '0'"
        ),
        'bereich' => array
        (
            'sql' => "varchar(12) NOT NULL default ''",
            'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['bereich'],
            'exclude' => false,
            'inputType' => 'select',
            'options_callback' => array('\Tanzsport\Ergebnisarchiv', 'getVerfuegbareLigabereicheMitLabelInternal'),
            'search' => false,
            'sorting' => false,
            'eval' => array('mandatory' => true, 'includeBlankOption' => true, 'submitOnChange' => true, 'tl_class' => 'w50'),
            'unique' => true,
            'reference' => &$GLOBALS['TL_LANG'][\Tanzsport\Ergebnisarchiv::LNG_KEY]['internal']
        ),
        'bereichOrder' => array
        (
            'sql' => "tinyint(1) unsigned NOT NULL default '0'",
        ),
        'liga' => array
        (
            'sql' => "varchar(6) NOT NULL default ''",
            'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['liga'],
            'exclude' => false,
            'inputType' => 'select',
            'options_callback' => array('\Tanzsport\Ergebnisarchiv', 'getLigenMitLabel'),
            'search' => false,
            'sorting' => false,
            'eval' => array('mandatory' => true, 'includeBlankOption' => false, 'tl_class' => 'w50'),
            'unique' => true,
            'reference' => &$GLOBALS['TL_LANG'][\Tanzsport\Ergebnisarchiv::LNG_KEY]
        ),
        'ligaOrder' => array
        (
            'sql' => "tinyint(1) unsigned NOT NULL default '0'",
        ),
        'turnierart' => array
        (
            'sql' => "varchar(6) NOT NULL default ''",
            'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['turnierart'],
            'exclude' => false,
            'inputType' => 'select',
            'options_callback' => array('\Tanzsport\Ergebnisarchiv', 'getTurnierartenMitLabel'),
            'search' => false,
            'sorting' => false,
            'eval' => array('mandatory' => true, 'includeBlankOption' => false, 'tl_class' => 'w50'),
            'unique' => true,
            'reference' => &$GLOBALS['TL_LANG'][\Tanzsport\Ergebnisarchiv::LNG_KEY]
        ),
        'turnierartOrder' => array
        (
            'sql' => "tinyint(1) unsigned NOT NULL default '0'",
        ),
        'nr' => array
        (
            'sql' => "char(1) NOT NULL default ''",
            'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['nr'],
            'exclude' => false,
            'inputType' => 'text',
            'search' => false,
            'sorting' => false,
            'eval' => array('mandatory' => false, 'rgxp' => 'digit', 'tl_class' => 'w50'),
        ),
        'bezeichnung' => array
        (
            'sql' => "varchar(18) NOT NULL default ''",
            'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['bezeichnung'],
            'exclude' => false,
            'inputType' => 'text',
            'search' => false,
            'sorting' => false,
            'eval' => array('mandatory' => false, 'maxlength' => 18, 'tl_class' => 'w50'),
        ),
        'text' => array
        (
            'sql' => "varchar(48) NOT NULL default ''",
            'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['text'],
            'exclude' => false,
            'inputType' => 'text',
            'search' => false,
            'sorting' => false,
            'eval' => array('mandatory' => false, 'maxlength' => 48, 'tl_class' => 'w50'),
        ),
        'published' => array
        (
            'label' => &$GLOBALS['TL_LANG']['tl_td_erg_liga']['published'],
            'exclude' => false,
            'filter' => true,
            'flag' => 1,
            'inputType' => 'checkbox',
            'eval' => array('doNotCopy' => true),
            'sql' => "char(1) NOT NULL default ''"
        ),
    )
);

\System::loadLanguageFile('tl_td_erg');

class tl_td_erg_liga extends Backend
{
    public function __construct()
    {
        parent::__construct();
        $this->import('BackendUser', 'User');
    }

    public function listeLigen($arrRow)
    {
        $html = '<div class="tl_content_left">' . $GLOBALS['TL_LANG']['tl_td_erg'][$arrRow['liga']] . ' ';
        $html .= $GLOBALS['TL_LANG']['tl_td_erg'][$arrRow['turnierart']];
        if ($arrRow['bezeichnung']) {
            $html .= ' ' . $arrRow['bezeichnung'];
        } else {
            if ($arrRow['nr']) {
                $html .= ' ' . $arrRow['nr'];
            }
        }
        $html .= '</div>';
        return $html;
    }

    public function toggleIcon($row, $href, $label, $title, $icon, $attributes)
    {
        if (strlen(Input::get('tid'))) {
            $this->toggleVisibility(Input::get('tid'), (Input::get('state') == 1));
            $this->redirect($this->getReferer());
        }

        $href .= '&amp;tid=' . $row['id'] . '&amp;state=' . ($row['published'] ? '' : 1);

        if (!$row['published']) {
            $icon = 'invisible.gif';
        }

        return '<a href="' . $this->addToUrl($href) . '" title="' . specialchars($title) . '"' . $attributes . '>' . Image::getHtml($icon, $label) . '</a> ';
    }

    public function toggleVisibility($intId, $blnVisible)
    {
        $objVersions = new Versions('tl_td_erg_liga', $intId);
        $objVersions->initialize();

        if (is_array($GLOBALS['TL_DCA']['tl_td_erg_liga']['fields']['published']['save_callback'])) {
            foreach ($GLOBALS['TL_DCA']['tl_td_erg_liga']['fields']['published']['save_callback'] as $callback) {
                if (is_array($callback)) {
                    $this->import($callback[0]);
                    $blnVisible = $this->$callback[0]->$callback[1]($blnVisible, $this);
                } elseif (is_callable($callback)) {
                    $blnVisible = $callback($blnVisible, $this);
                }
            }
        }

        // Update the database
        $this->Database->prepare("UPDATE tl_td_erg_liga SET tstamp=" . time() . ", published='" . ($blnVisible ? 1 : '') . "' WHERE id=?")
            ->execute($intId);

        $objVersions->create();
    }

    public static function submitCallback(DC_Table $dc)
    {
        \Database::getInstance()->prepare("UPDATE tl_td_erg_liga SET bereichOrder = ?, ligaOrder = ?, turnierartOrder = ? WHERE id = ?")
            ->execute(array(
                \Tanzsport\ErgebnisArchiv::getSortIndexBereich($dc->activeRecord->bereich),
                \Tanzsport\Ergebnisarchiv::getSortIndexLiga($dc->activeRecord->liga),
                \Tanzsport\Ergebnisarchiv::getSortIndexTurnierart($dc->activeRecord->turnierart),
                $dc->activeRecord->id
            ));
    }

    public static function deleteCallback(DC_Table $dc)
    {
        $mannnschaften = \Tanzsport\LigaMannschaftModel::findBy('pid', $dc->activeRecord->id);
        if ($mannnschaften != null) {
            foreach ($mannnschaften as $mannschaft) {
                $mannschaft->delete();
            }
        }
        $turniere = \Tanzsport\LigaTurnierModel::findBy('pid', $dc->activeRecord->id);
        if ($turniere != null) {
            foreach ($turniere as $turnier) {
                $turnier->delete();
            }
        }
    }

    public function deleteIcon($row, $href, $label, $title, $icon, $attributes)
    {
        if (!$this->User->isAdmin) {
            return;
        }
        return '<a href="' . $this->addToUrl('&amp;act=delete&amp;id=' . $row['id']) . '" title="' . specialchars($title) . '"' . $attributes . '>' . Image::getHtml($icon, $label) . '</a> ';
    }
}
