<?php

namespace App\Http\Controllers\Admin;

use App\Models\Faq;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class FaqController extends Controller
{
    public function index()
    {

        $faq = Faq::latest()->get();
        return view('Admin.faq.index', compact('faq'));
    }

    public function store(Request $request)
    {

        $this->validate($request, [
            'title' => 'required|string|min:5|max:100',
            'title' => 'required',
        ]);

        try {
            $faq = new Faq();
            $faq->title = $request->title;
            $faq->details = $request->details;
            $faq->add_by = Auth::user()->id;
            $faq->ip_address = $request->ip();

            $faq->save();
            return redirect()->route('faq.index')->with('success', 'Frequently asked Question Created Successfully');

        } catch (\Throwable $th) {
              // throw $th;
            return redirect()->back()->with('error', 'Frequently asked Question  creation failed');
        }
    }


    public function edit($id)
    {

        $faq = Faq::find($id);
        $faqs = Faq::get();
        return view('Admin.faq.edit', compact('faq', 'faqs'));
    }

    public function update($id, Request $request)
    {

        $this->validate(\request(),
            [
                'title' => 'required|string|min:10|max:100',
                'details' => 'required',

            ]);

        try {
            $faq = Faq::find($id);
            $faq->title = $request->title;
            $faq->details = $request->details;
            $faq->updated_by = Auth::user()->id;
            $faq->ip_address = $request->ip();

            $faq->update();
            return redirect()->route('faq.index')->with('success', ' Frequently asked Question   Update Successful');

        } catch (\Throwable $th) {
            // throw $th;
            return redirect()->back()->with('error', ' Frequently asked Question  Update failed');
        }

    }

    public function delete($id)
    {

        try {
            $faq = Faq::find($id);
            $faq->delete();
            return redirect()->route('faq.index')->with('success', ' Frequently asked Question Deleted Successful');

        } catch (\Throwable $th) {
            //throw $th;
            return redirect()->back()->with('error', ' Frequently asked Question Deleted failed');
        }

    }
}
