<?php

namespace ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\Forms\AjaxFields;

use ModulesGarden\HostingQuotaNotifications\Core\UI\Interfaces\AjaxElementInterface;
use ModulesGarden\HostingQuotaNotifications\Core\UI\ResponseTemplates;

/**
 * Select field controler
 *
 * @author Sławomir Miśkowicz <slawomir@modulesgarden.com>
 */
class Select extends \ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\Forms\Fields\Select implements AjaxElementInterface
{
    use \ModulesGarden\HostingQuotaNotifications\Core\UI\Traits\RequestObjectHandler;
    
    protected $id   = 'ajaxSelect';
    protected $name = 'ajaxSelect';
    
    protected $query = null;
    protected $queryByFormData = [];
    protected $columnTitle = '';
    protected $columnValue = '';
    protected $defaultValue = [];
    protected $columnId = 'id';
    protected $columnSelected = 'id';
    protected $disabledList = [];
    
    public function returnAjaxData()
    {
        $this->loadRequestObj();
        $key      = $this->getRequestValue('loadData', false);
        $formData = $this->getRequestValue('formData', []);
        $items = [];
        
        if (count($this->defaultValue) > 0)
        {
            foreach ($this->defaultValue as $keyT => $title)
            {
                $items[$keyT] = $title;
            }
        }
        
        if ($this->columnId)
        {
            $selectData = $this->convertSelectedValue($this->loadSelectedRecord($formData)->$key);
        }
        else
        {
            $selectData = $this->convertSelectedValue([]);
        }
        
        $items += $this->query ? $this->validateQuery($this->query)->pluck($this->columnTitle, $this->columnValue) : [];
        
        $returnData = [];
     
        foreach ($items as $itemKey => $item)
        {
            $returnData[$itemKey] = [
                'title' => $item,
                'selected' => ($selectData?(is_array($selectData) ? in_array($itemKey, $selectData, true) : $selectData == $itemKey):false),
                'disabled' => in_array($itemKey, $this->disabledList, true)
            ];
        }
        
        return (new ResponseTemplates\RawDataJsonResponse($returnData))->setCallBackFunction($this->callBackFunction);
    }

    public function initContent()
    {
        
    }
    
    public function loadSelectedRecord($formData)
    {
        $selectedQuery = (clone $this->query);
        return $selectedQuery->where($this->columnId, $formData[$this->columnId])->first();
    }
    
    public function setQuery($query)
    {
        $this->query = $query;
        
        return $this;
    }
    
    public function addDefaultValue($key, $value = '')
    {
        $this->defaultValue += [$key => $value];
        
        return $this;
    }
    
    public function convertSelectedValue($value)
    {
        return $value;
    }
    
    public function validateQuery($query)
    {
        return $query;
    }
}
