<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SpamFilter;
use Illuminate\Http\Request;

class SpamFilterController extends Controller
{
    public function list()
    {
        $pageTitle = 'Spam Filters';
        $filters   = SpamFilter::searchable(['filter_type', 'content'])->latest()->paginate(getPaginate());
        return view('admin.setting.spam_filter.list', compact('pageTitle', 'filters'));
    }

    public function save(Request $request, $id = 0)
    {
        $request->validate([
            'filter_type' => 'required|in:name,email,text,ip',
            'content'     => $request->filter_type === 'email' ? 'required|email' : 'required|string',
        ]);

        if ($id) {
            $filter  = SpamFilter::findOrFail($id);
            $message = 'Spam filter updated successfully';
        } else {
            $filter             = new SpamFilter();
            $filter->admin_id   = auth('admin')->id();
            $message            = 'Spam filter created successfully';
        }

        $filter->filter_type = $request->filter_type;
        $filter->content     = $request->content;
        $filter->save();

        $notify[] = ['success', $message];
        return back()->withNotify($notify);
    }

    public function status($id)
    {
        $filter =  SpamFilter::find($id);

        if (!$filter) {
            return response()->json([
                'status'  => 'error',
                'message' => 'No spam filter found',
            ]);
        }

        $filter->status = !$filter->status;
        $filter->save();

        $message = $filter->status ? 'Spam filter enabled successfully' : 'Spam filter disabled successfully';

        return response()->json([
            'status'     => 'success',
            'message'    => $message,
            'filter' => $filter,
        ]);
    }

    public function delete($id)
    {
        $filter = SpamFilter::findOrFail($id);
        $filter->delete();

        $notify[] = ['success', 'Spam filter deleted successfully'];
        return back()->withNotify($notify);
    }
}
