<?php

namespace kernel\app_modules\user_custom_fields\services;

use kernel\app_modules\user_custom_fields\models\forms\CreateUserCustomValueForm;
use kernel\app_modules\user_custom_fields\models\UserCustomValues;
use kernel\FormModel;

class UserCustomValuesService
{
    public function create(FormModel $form_model): false|UserCustomValues
    {
        $model = new UserCustomValues();
        $model->user_id = $form_model->getItem('user_id');
        $model->custom_field_id = $form_model->getItem('custom_field_id');
        $model->value = $form_model->getItem('value');

        if ($model->save()) {
            return $model;
        }

        return false;
    }

    public function update(FormModel $form_model, UserCustomValues $user_custom_value): false|UserCustomValues
    {
        $user_custom_value->user_id = $form_model->getItem('user_id');
        $user_custom_value->custom_field_id = $form_model->getItem('custom_field_id');
        $user_custom_value->value = $form_model->getItem('value');

        if ($user_custom_value->save()) {
            return $user_custom_value;
        }

        return false;
    }

    public static function getValuesByUserId(int $user_id): \Illuminate\Database\Eloquent\Collection
    {
        return UserCustomValues::with(['customField'])->where(['user_id' => $user_id])->get();
    }

    public static function getValueByFieldAndUser(int $custom_field_id, int $user_id): UserCustomValues|null
    {
        return UserCustomValues::where([
            'custom_field_id' => $custom_field_id,
            'user_id' => $user_id
        ])->first();
    }

    public static function deleteByUserAndField(int $user_id, int $custom_field_id): bool
    {
        $record = self::getValueByFieldAndUser($custom_field_id, $user_id);

        if ($record) {
            return $record->delete();
        }

        return false;
    }

    public static function save(int $userId, string $slug, string $value): UserCustomValues
    {
        $customField = CustomFieldService::getOrCreateBySlug($slug);
        $model = UserCustomValues::where('user_id', $userId)->where('custom_field_id', $customField->id)->first();
        if (!$model) {
            $service = new self();
            $form = new CreateUserCustomValueForm();
            $form->load([
                'custom_field_id' => $customField->id,
                'user_id' => $userId,
                'value' => $value,
            ]);
            $model = $service->create($form);
        }

        return $model;
    }
}