<?php

/**
 * ArtLayout for Contao
 *
 * Copyright (c) 2016 Benjamin Roth
 *
 * @link    http://www.esales-media.de
 * @license commercial
 */

/**
 * Callbacks
 */
$GLOBALS['TL_DCA']['tl_content']['fields']['type']['options_callback'] = array('tl_content_eSM_artLayout','getContentElements');


/**
 * Provide miscellaneous methods that are used by the data configuration array.
 *
 * @author Benjamin Roth <http://www.esales-media.de>
 */
class tl_content_eSM_artLayout extends \Backend
{

  /**
   * Import the back end user object
   */
  public function __construct()
  {
    parent::__construct();
    $this->import('BackendUser', 'User');
  }

  /**
   * Return all allowed content elements
   *
   * @param DataContainer $dc
   *
   * @return array
   */
  public function getContentElements(\DataContainer $dc)
  {
    $groups = array();

    // Get article model
    $Article = \ArticleModel::findByPk($dc->activeRecord->pid);

    // Check for article layout
    if ($Article->es_type)
    {
      // Get layout model
      $ArticleLayout = \ArticleLayoutsModel::findByPk($Article->es_type);

      // Build array of allowed elements if restriction is set
      if ($ArticleLayout !== null && $ArticleLayout->restrictContentElements)
      {
        $arrAllowedCTE = deserialize($ArticleLayout->allowedElements,true);
      }
    }

    // Build elements groups
    foreach ($GLOBALS['TL_CTE'] as $k => $v)
    {
      foreach (array_keys($v) as $kk) {

        // Skip not allowed elements
        if (isset($arrAllowedCTE))
        {
          if (!in_array($kk, $arrAllowedCTE))
          {
            continue;
          }
        }
        $groups[$k][] = $kk;
      }
    }

    return $groups;
  }
}