<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class ProgramTranslation extends Model
{
    use HasFactory, SoftDeletes;

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'program_id',
        'franchisee_id',
        'language',
        'title',
        'sub_heading',
        'button_text',
        'age_range',
        'duration',
        'no_of_lessons',
        'description',
        'seo_title',
        'seo_description',
        'age_text',
        'duration_text',
        'lesson_duration_text',
        'tag',
        'skills_text',
        'creative_thinking_text',
        'more_info_text',
        'program_icon',
        'program_details',
        'status',
        'version',
        'adopted_from_global',
        'source_global_translation_id',
        'source_global_version',
        'last_local_edit_at',
    ];

    protected $casts = [
        'program_details' => 'array',
        'version' => 'integer',
        'adopted_from_global' => 'boolean',
        'source_global_version' => 'integer',
        'last_local_edit_at' => 'datetime',
    ];

    protected static function booted(): void
    {
        static::creating(function (self $model): void {
            if (empty($model->{$model->getKeyName()})) {
                $model->{$model->getKeyName()} = (string) Str::uuid();
            }

            $model->language = strtolower((string) ($model->language ?: 'en'));
        });
    }

    public function program(): BelongsTo
    {
        return $this->belongsTo(Program::class);
    }

    public function franchisee(): BelongsTo
    {
        return $this->belongsTo(Franchisee::class);
    }

    public function sourceGlobalTranslation(): BelongsTo
    {
        return $this->belongsTo(self::class, 'source_global_translation_id');
    }

    public function adoptedTranslations(): HasMany
    {
        return $this->hasMany(self::class, 'source_global_translation_id');
    }

    public function scopeGlobal(Builder $query): Builder
    {
        return $query->whereNull('franchisee_id');
    }

    public function scopeFranchise(Builder $query, ?string $franchiseeId = null): Builder
    {
        if ($franchiseeId) {
            return $query->where('franchisee_id', $franchiseeId);
        }

        return $query->whereNotNull('franchisee_id');
    }

    public function scopePublished(Builder $query): Builder
    {
        return $query->where('status', 'publish');
    }

    public function scopeByLanguage(Builder $query, string $language): Builder
    {
        return $query->where('language', strtolower(trim($language)));
    }
}
