<?php
namespace App\Repositories\Admin\Mail;

use Illuminate\Support\Facades\DB;

final class AdminMailTemplateRepository
{
    public function list(array $filters, int $perPage)
    {
        $q = DB::table('admin_mail_templates');

        if (($filters['active'] ?? '') !== '') {
            $q->where('is_active', (int)$filters['active']);
        }
        if (!empty($filters['q'])) {
            $kw = '%'.$filters['q'].'%';
            $q->where(function($w) use ($kw){
                $w->where('code','like',$kw)
                    ->orWhere('title','like',$kw)
                    ->orWhere('subject_tpl','like',$kw)
                    ->orWhere('body_tpl','like',$kw);
            });
        }

        return $q->orderByDesc('id')->paginate($perPage)->withQueryString();
    }

    public function activeAll(): array
    {
        $rows = DB::table('admin_mail_templates')
            ->where('is_active',1)
            ->orderByDesc('id')
            ->get();

        return $rows ? $rows->all() : [];
    }

    public function find(int $id): ?object
    {
        $r = DB::table('admin_mail_templates')->where('id',$id)->first();
        return $r ?: null;
    }

    public function create(array $row): int
    {
        return (int) DB::table('admin_mail_templates')->insertGetId($row);
    }

    public function update(int $id, array $row): int
    {
        return DB::table('admin_mail_templates')->where('id',$id)->update($row);
    }

    public function existsCode(string $code): bool
    {
        return DB::table('admin_mail_templates')->where('code',$code)->exists();
    }
}
