<?php

namespace App\Repositories\Admin\Member;

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

final class AdminMemberJoinFilterRepository
{
    private const TABLE = 'mem_join_filter';

    public function paginateFilters(array $filters, int $perPage = 20): LengthAwarePaginator
    {
        $q = DB::table(self::TABLE);

        $gubun = trim((string)($filters['gubun_code'] ?? ''));
        if ($gubun !== '') $q->where('gubun_code', $gubun);

        $jb = trim((string)($filters['join_block'] ?? ''));
        if ($jb !== '') $q->where('join_block', $jb);

        $ip = trim((string)($filters['filter_ip'] ?? ''));
        if ($ip !== '') $q->where('filter', $ip);

        $q->orderByDesc('dt_reg');

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

    public function find(int $seq): ?array
    {
        $row = DB::table(self::TABLE)->where('seq', $seq)->first();
        return $row ? (array)$row : null;
    }

    public function lockForUpdate(int $seq): ?array
    {
        $row = DB::table(self::TABLE)->where('seq', $seq)->lockForUpdate()->first();
        return $row ? (array)$row : null;
    }

    public function insert(array $data): int
    {
        return (int) DB::table(self::TABLE)->insertGetId($data);
    }

    // ✅ bool 말고 affected rows
    public function update(int $seq, array $data): int
    {
        return (int) DB::table(self::TABLE)->where('seq', $seq)->update($data);
    }

    public function delete(int $seq): int
    {
        return (int) DB::table(self::TABLE)->where('seq', $seq)->delete();
    }

    public function listActiveAdminsForSms(): array
    {
        return DB::table('admin_users')
            ->select(['id', 'email', 'name', 'phone_enc'])
            ->where('status', 'active')
            ->orderBy('name', 'asc')
            ->get()
            ->map(fn($r) => (array)$r)
            ->all();
    }
}
