<?php

namespace ModulesGarden\Servers\OpenXchange\App\Helpers\Repositories;

use \WHMCS\CustomField;
use ModulesGarden\Servers\OpenXchange\App\Models\CustomFieldValueModel;

class CustomFieldRepository
{
    const OX_CONTEXT_CUSTOM_FIELD = 'context_id';
    const OX_CONTEXT_NAME_FIELD = 'context_name';

    public static function getCustomField($name, $relid, $type)
    {
        return CustomField::where([
                ['fieldname', 'like', $name.'|%'],
                ['type', $type],
                ['relid', $relid]
            ])->first();
    }

    public static function saveCustomFieldValue($relid, $packageId, $value, $fieldName)
    {
        $fieldId = self::getContextCustomField($packageId, $fieldName);
        return CustomFieldValueModel::updateOrCreate(
            ['fieldid' => $fieldId, 'relid' => $relid],
            ['value' => $value]
        );
    }

    public static function getCustomFieldValue($fieldid, $relid)
    {
        return CustomFieldValueModel::where('fieldid', $fieldid)
            ->where('relid', $relid)
            ->first();
    }

    public static function getContextCustomField($packageId, $fieldName)
    {
        return CustomFieldRepository::getCustomField($fieldName, $packageId, 'product')->id;
    }

}
