<?php

namespace Modules\ClinicSite\Http\Controllers\Admin;

use Illuminate\Routing\Controller;
use Modules\ClinicSite\Entities\CsSite;
use Modules\ClinicSite\Entities\CsMessage;

class MessageController extends Controller
{
    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate()
    {
        if (! auth()->user()->can('clinic_site.access_module')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        $messages = CsMessage::where('business_id', $this->biz())->orderByDesc('id')->paginate(25);
        return view('clinicSite::admin.messages', compact('messages'));
    }

    public function show($id)
    {
        $this->gate();
        $message = CsMessage::where('business_id', $this->biz())->findOrFail($id);
        $message->update(['is_read' => true]);
        return view('clinicSite::admin.message_show', compact('message'));
    }

    public function toggleRead($id)
    {
        $this->gate();
        $m = CsMessage::where('business_id', $this->biz())->findOrFail($id);
        $m->update(['is_read' => ! $m->is_read]);
        return back();
    }

    public function destroy($id)
    {
        $this->gate();
        CsMessage::where('business_id', $this->biz())->findOrFail($id)->delete();
        return redirect()->route('cs.messages')->with('status', ['success' => 1, 'msg' => __('clinicSite::lang.deleted')]);
    }
}
