<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author Daniele Termini
 * @package Application\Admin
 */

namespace Application\Admin\Form;

/**
 * Campo checklist.
 *
 * @deprecated
 */
abstract class ChecklistField extends Field
{
    /**
     * {@inheritdoc}
     */
    protected $default = false;

    /**
     * {@inheritdoc}
     */
    public function setAttributeModel()
    {
        $this->setRelations(isset($_POST[$this->post_name]) && is_array($_POST[$this->post_name]) ? array_keys($_POST[$this->post_name]) : []);
    }

    /**
     * {@inheritdoc}
     */
    public function getViewCode()
    {
        $foreigns = $this->getAllForeign();
        $relations = $this->getRelations();

        foreach ($foreigns as $foreign) {
            $foreign->is_checked = array_key_exists($foreign->id, $relations);
        }

        $code = '';
        foreach ($foreigns as $rel) {
            $code .= '<input class="checklist" type="checkbox" id="' . $this->attribute_name . '_' . $rel->id . '" name="' . $this->attribute_name . '[' . $rel->id . ']" ' . ($rel->is_checked ? 'checked="checked"' : '') . ' />';
            $code .= '<label for="' . $this->attribute_name . '_' . $rel->id . '">' . $rel->name . '</label>';
            $code .= '<br />';
        }

        return $code;
    }

    /**
     *
     */
    protected function getAllForeign()
    {
        $foreign_class = $this->get('foreign');

        return $foreign_class::all();
    }

    /**
     *
     */
    abstract public function deleteRelations();

    /**
     *
     */
    abstract public function setRelations(array $relations);

    /**
     *
     */
    abstract public function getRelations();
}
