<?php

namespace App\Models;

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

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

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

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

        if (empty($input['original_meaning'])) {
            throw new SPException("original_meaning is required.");
        }

        /**
         * Normalize values
         */
        $originalWord = ucwords(trim($input['original_word']));
        $originalMeaning = ucfirst(trim($input['original_meaning']));
        $originalLanguage = $input['original_language'] ?? 'ki';

        /**
         * Build payload
         */
        $data = [
            'original_language' => $originalLanguage,
            'category_id'       => $input['category_id'] ?? null,
            'word_type_id'      => $input['word_type_id'] ?? null,
            'original_word'     => $originalWord,
            'original_meaning'  => $originalMeaning,
            'original_example'  => !empty($input['original_example']) 
                                    ? ucfirst(trim($input['original_example'])) 
                                    : null,
            'status'            => $input['status'] ?? 'draft',
            'word_image'        => $input['word_image'] ?? null,
            'pronunciation'     => $input['pronunciation'] ?? null,
            'ipaWord'           => $input['ipaWord'] ?? null,
            'updated_by'        => Auth::User('user_id'),
        ];

        /**
         * Detect existing word (by ID OR unique key)
         */
        $word = null;

        if (!empty($input['wordId'])) {
            $word = Word::query()->where('id', $input['wordId'])->first();
        } else {
            $word = Word::query()
                ->where('original_word', $originalWord)
                ->where('original_language', $originalLanguage)
                ->first();
        }

        /**
         * UPDATE
         */
        if ($word) {
            Word::query()->where('id', $word->id)->update($data);
            return Word::query()->where('original_word', $originalWord)
                ->where('original_language', $originalLanguage)
                ->first();
        }

        /**
         * CREATE
         */
        $data['created_by'] = Auth::User('user_id');

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

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

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