File: /home/xedaptot/be.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);
}
}
}
}