<?php

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

namespace Application\Admin\Form;

use Pongho\Utilities\DateTime;

/**
 * Campo anno - mese.
 *
 * @deprecated
 */
class YearMonthField extends Field
{
    /**
     * {@inheritdoc}
     */
    protected $default;

    /**
     * {@inheritdoc}
     */
    protected function parseOptions()
    {
        $this->default = intval(date('Y'));

        parent::parseOptions();
    }

    /**
     * {@inheritdoc}
     */
    public function setAttributeModel()
    {
        if (isset($_POST[$this->post_name])) {
            $date = new DateTime(sprintf('%s%s01', str_pad((string) $_POST[$this->post_name]['year'], 4, 0, STR_PAD_LEFT), str_pad((string) $_POST[$this->post_name]['month'], 2, 0, STR_PAD_LEFT)));
        }

        $this->model->{$this->attribute_name} = $date ?? $this->default;
    }

    /**
     * {@inheritdoc}
     */
    public function getViewCode()
    {
        $attribute_value = $this->model->{$this->attribute_name};

        $html = $this->get('subject')->getContainer()->get('template_html');

        $code = '';

        $years = [];
        foreach ($this->get('years', range(1900, 2100)) as $year) {
            $years[$year] = $year;
        }

        $attributes = array_merge($this->getBaseAttributes(), [
            'name' => $this->post_name . '[year]',
            'id'   => $this->post_name . '_year',
        ]);
        $code .= $html->generateTagBlock('select', $html->select($years, $attribute_value instanceof DateTime ? intval($attribute_value->format('Y')) : $this->default), $attributes);

        $months = [];
        foreach (range(1, 12) as $month) {
            $months[$month] = get_month($month);
        }

        $attributes = array_merge($this->getBaseAttributes(), [
            'name' => $this->post_name . '[month]',
            'id'   => $this->post_name . '_month',
        ]);

        return $code . $html->generateTagBlock('select', $html->select($months, $attribute_value instanceof DateTime ? intval($attribute_value->format('m')) : $this->default), $attributes);
    }
}
