<?php

namespace App\Models;

use SelfPhp\Auth;
use SelfPhp\DB\Serve;

/**
 * Class Translation
 * Represents a model for categories-related data, extending the Serve class.
 */
class Translation extends Serve
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'translations';

    /**
     * Translation constructor.
     * Constructor method (currently empty).
     */
    public function __construct()
    {
        // Constructor logic (if any).
    }

    public function createOrUpdateTranslation(array $input)
    {
        if (empty($input['word_id'])) {
            throw new SPException("word_id is required.");
        }

        if (empty($input['language_code'])) {
            throw new SPException("language_code is required.");
        }
        
        $wordId       = (int) $input['word_id'];
        $languageCode = strtolower(trim($input['language_code']));

        $wordExists = Word::query()
            ->where('id', $wordId)
            ->exists();

        if (!$wordExists) {
            throw new SPException("Invalid word_id: {$wordId}");
        }
        
        $data = [
            'word_id'             => $wordId,
            'language_code'       => $languageCode,
            'translated_word'     => !empty($input['translated_word'])
                                        ? ucfirst(trim($input['translated_word']))
                                        : null,
            'translated_meaning'  => !empty($input['translated_meaning'])
                                        ? ucfirst(trim($input['translated_meaning']))
                                        : null,
            'translated_example'  => !empty($input['translated_example'])
                                        ? ucfirst(trim($input['translated_example']))
                                        : null,
            'trans_word_image'    => $input['trans_word_image'] ?? null,
            'trans_pronunciation' => $input['trans_pronunciation'] ?? null,
            'status'              => $input['status'] ?? 'draft',
            'updated_by'          => Auth::User('user_id'),
        ];

        /**
         * Detect existing translation (unique per word + language)
         */
        $translation = Translation::query()
            ->where('word_id', $wordId)
            ->where('language_code', $languageCode)
            ->first();

        if ($translation) {
            Translation::query()->where('word_id', $wordId)->update($data); 
            return Translation::query()->where('word_id', $wordId)
                ->where('language_code', $languageCode)
                ->first();
        }
        
        $data['created_by'] = Auth::User('user_id');

        $id = Translation::query()->insertGetId($data);

        if (!$id) {
            throw new SPException("Failed to create translation.");
        }

        return Translation::query()->find($id);
    }
}
