<?php

/*
    Created by Mohamed.
*/


namespace App\Http\Controllers\API;

use App\Models\Faq;
use Illuminate\Http\Request;
use App\Http\Resources\FaqResource;
use App\Http\Controllers\Controller;

class FaqController extends Controller
{
    /**
     * Display a listing of FAQs.
     */
    public function index(Request $request)
    {
        $faqs = Faq::where('type', $request->type)->where('active', 1)->orderBy('sort')->get();
        return FaqResource::collection($faqs);
    }

    /**
     * Store a newly created FAQ.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'question' => 'required|array',
            'question.en' => 'required|string',
            'question.ar' => 'required|string',
            'answer' => 'required|array',
            'answer.en' => 'required|string',
            'answer.ar' => 'required|string',
            'active' => 'boolean',
            'sort' => 'integer',
        ]);

        $faq = Faq::create($validated);

        return new FaqResource($faq);
    }

    /**
     * Display the specified FAQ.
     */
    public function show($id)
    {
        $faq = Faq::findOrFail($id);
        return new FaqResource($faq);
    }

    /**
     * Update the specified FAQ.
     */
    public function update(Request $request, $id)
    {
        $faq = Faq::findOrFail($id);

        $validated = $request->validate([
            'question' => 'sometimes|required|array',
            'question.en' => 'sometimes|required|string',
            'question.ar' => 'sometimes|required|string',
            'answer' => 'sometimes|required|array',
            'answer.en' => 'sometimes|required|string',
            'answer.ar' => 'sometimes|required|string',
            'active' => 'boolean',
            'sort' => 'integer',
        ]);

        $faq->update($validated);

        return new FaqResource($faq);
    }

    /**
     * Remove the specified FAQ.
     */
    public function destroy($id)
    {
        $faq = Faq::findOrFail($id);
        $faq->delete();

        return response()->json(['message' => 'FAQ deleted successfully']);
    }
}
