<?php

namespace App\Http\Controllers\Admin;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Models\PredefinedReply;
use Illuminate\Http\Request;

class PredefinedReplyController extends Controller
{
    public function list(Request $request)
    {
        $snippets = PredefinedReply::searchable(['title', 'message'])->where(function ($query) {
            $query->where('admin_id', auth('admin')->id())->orWhere('global', Status::YES);
        })->limit(10)->orderBy('id', 'desc')->get();

        $html = view('admin.ticket.snippet_list', compact('snippets'))->render();

        return response()->json([
            'html' => $html,
        ]);
    }

    public function save(Request $request, $id = 0)
    {
        $request->validate([
            'title'   => 'required|string',
            'message' => 'required|string',
        ]);

        if ($id) {
            $predefinedReply = PredefinedReply::where('admin_id', auth('admin')->id())->findOrFail($id);
            $message         = 'Snippet updated successfully';
        } else {
            $predefinedReply           = new PredefinedReply();
            $predefinedReply->admin_id = auth('admin')->id();
            $message                   = 'Snippet added successfully';
        }

        $predefinedReply->title    = $request->title;
        $predefinedReply->message  = purifyHtml($request->message);
        $predefinedReply->global   = $request->global ? Status::YES : Status::NO;
        $predefinedReply->favorite = $request->favorite ? Status::YES : Status::NO;
        $predefinedReply->save();

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

    public function delete($id)
    {
        $predefinedReply = PredefinedReply::where('admin_id', auth('admin')->id())->findOrFail($id);
        $predefinedReply->delete();

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

}
