HEX
Server: LiteSpeed
System: Linux s1049.use1.mysecurecloudhost.com 4.18.0-477.27.2.lve.el8.x86_64 #1 SMP Wed Oct 11 12:32:56 UTC 2023 x86_64
User: xedaptot (3356)
PHP: 8.3.31
Disabled: NONE
Upload Files
File: /home/xedaptot/ai.naniguide.com/app/Model/SystemEmailTemplate.php
<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Library\Contracts\TemplateSubjectInterface;
use App\Library\Traits\HasUid;
use App\Model\TemplateCategory;
use App\Services\TemplateService;

class SystemEmailTemplate extends Model implements TemplateSubjectInterface
{
    use HasUid;

    public static function newDefault()
    {
        $template = new self();

        return $template;
    }

    /**
     * @return BelongsTo<Template, $this>
     */
    public function template(): BelongsTo
    {
        return $this->belongsTo(Template::class);
    }

    public function scopeSearch($query, $keyword)
    {
        // Keyword
        if (!empty($keyword)) {
            $query = $query->where('name', 'like', '%'.trim($keyword).'%');
        }
    }

    public function scopeCategoryUid($query, $category_uid)
    {
        // Filter SystemEmailTemplate by related template's category UID
        return $query->whereHas('template.categories', function ($q) use ($category_uid) {
            $q->where('uid', $category_uid);
        });
    }

    public function deleteAndCleanup()
    {
        TemplateService::for($this)->deleteSubjectAndTemplate();
    }

    public function changeName($name)
    {
        $validator = \Validator::make(['name' => $name], [
            'name' => 'required',
        ]);

        // redirect if fails
        if ($validator->fails()) {
            return $validator;
        }

        $this->name = $name;
        $this->save();

        return $validator;
    }

    public function addSystemEmailTemplate(string $name, Template $template)
    {
        $this->name = $name;

        $newTemplate = TemplateService::for($this)->setTemplate($template, $name);

        // Admin-curated derivatives are always classified as "Extended"
        // (not "Base"). Wipe inherited categories from the copy and set Extended.
        // Style categories (Basic/Featured) are preserved if present on the parent.
        $extendedCategory = TemplateCategory::whereName('Extended')->first();
        if ($extendedCategory) {
            // Detach Base if it was inherited from copy()
            $baseCategory = TemplateCategory::whereName('Base')->first();
            if ($baseCategory) {
                $newTemplate->categories()->detach($baseCategory->id);
            }
            // Attach Extended if not already present
            if (!$newTemplate->categories()->where('template_categories.id', $extendedCategory->id)->exists()) {
                $newTemplate->categories()->attach($extendedCategory->id);
            }
        }
    }
}