<?php

namespace App\Http\Controllers\Admin;

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

class FaqController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $faqs = Faq::ordered()->paginate(15);
        return view('admin.faqs.index', compact('faqs'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.faqs.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'question' => 'required|string|max:500',
            'answer' => 'required|string',
            'sort_order' => 'integer|min:0',
            'is_active' => 'sometimes|boolean',
        ]);

        $data = $request->only(['question', 'answer', 'sort_order']);
        $data['is_active'] = $request->boolean('is_active', true);

        Faq::create($data);

        return redirect()->route('admin.faqs.index')
                        ->with('success', 'FAQ created successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Faq $faq)
    {
        return view('admin.faqs.edit', compact('faq'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Faq $faq)
    {
        $request->validate([
            'question' => 'required|string|max:500',
            'answer' => 'required|string',
            'sort_order' => 'integer|min:0',
            'is_active' => 'sometimes|boolean',
        ]);

        $data = $request->only(['question', 'answer', 'sort_order']);
        $data['is_active'] = $request->boolean('is_active', true);

        $faq->update($data);

        return redirect()->route('admin.faqs.index')
                        ->with('success', 'FAQ updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Faq $faq)
    {
        $faq->delete();

        return redirect()->route('admin.faqs.index')
                        ->with('success', 'FAQ deleted successfully.');
    }

    /**
     * Toggle the active status of the FAQ.
     */
    public function toggleStatus(Faq $faq)
    {
        $faq->update(['is_active' => !$faq->is_active]);

        $status = $faq->is_active ? 'activated' : 'deactivated';
        
        return redirect()->back()
                        ->with('success', "FAQ {$status} successfully.");
    }
}
