<?php

namespace CCDN\Helpers;

trait CustomFields
{

    /**
     * @var array
     */
    private $customFields;


    /**
     * Make from DLE xfields string to array like [ 'key' => 'value' ]
     *
     * @return array
     */
    public function xFieldsToArray()
    {
        $customFieldsTmpArr = [];
        $customFieldsArr = explode('||', $this->xfields);
        foreach ($customFieldsArr as $customField) {
            list($key, $value) = explode('|', trim($customField, '|'));
            $customFieldsTmpArr[$key] = $value;
        }
        return $customFieldsTmpArr;
    }

    /**
     * @param  string  $key
     * @return int
     */
    public function getNumberFromField($key)
    {

        if (isset($this->customFields[$key])) {
            preg_match_all('!\d+!', $this->customFields[$key], $matches);
            return (int) $matches[0][0];
        }

        return null;
    }

    /**
     * @param  string  $key
     * @param  string  $value
     *
     * @return bool
     */
    public function setField($key, $value)
    {
        if (empty($key) || $value === null || $value === '') {
            return false;
        }
        $this->customFields[$key] = $value;

        return true;
    }

    /**
     * @param  string  $key
     *
     * @return null|string
     */
    public function getField($key)
    {

        if (isset($this->customFields[$key])) {
            return $this->customFields[$key];
        }

        return null;
    }


    /**
     * @param  string  $key
     * @return bool
     */
    public function deleteField($key)
    {
        if (array_key_exists($key, $this->customFields)) {
            unset($this->customFields[$key]);
            return true;
        }
        return false;
    }


    /**
     * Prepare data for DataBase
     *
     * @return string
     */
    public function convertToDLEXFieldsFormat()
    {
        $str = [];
        $this->customFields = array_filter($this->customFields);
        foreach ($this->customFields as $key => $value) {
            $str[] = $key.'|'.$this->getDb()->safesql($value);
        }

        return implode('||', $str);
    }

}
