<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlogPost;
use App\Models\BlogCategory;
use App\Models\Faq;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Auth;

class CMSAdminController extends Controller
{
    public function blogIndex()
    {
        $posts = BlogPost::with('category', 'author')->orderBy('id', 'desc')->paginate(15);
        $categories = BlogCategory::all();

        return view('admin.cms.blog', compact('posts', 'categories'));
    }

    public function storePost(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'blog_category_id' => 'required|exists:blog_categories,id',
            'excerpt' => 'nullable|string|max:500',
            'content' => 'required|string',
            'featured_image' => 'required|url',
            'meta_title' => 'nullable|string|max:255',
            'meta_description' => 'nullable|string|max:500',
        ]);

        $slug = Str::slug($validated['title']);

        $post = BlogPost::create(array_merge($validated, [
            'slug' => $slug,
            'author_id' => Auth::id(),
            'is_published' => true,
            'published_at' => now(),
        ]));

        AuditLog::record('admin_created_blog_post', $post);

        return back()->with('success', "Blog post '{$post->title}' published successfully.");
    }

    public function deletePost(string $id)
    {
        $post = BlogPost::findOrFail($id);
        $title = $post->title;
        $post->delete();

        AuditLog::record('admin_deleted_blog_post', null, ['title' => $title]);

        return back()->with('success', "Blog post '{$title}' deleted.");
    }

    public function faqIndex()
    {
        $faqs = Faq::orderBy('sort_order', 'asc')->get();
        return view('admin.cms.faqs', compact('faqs'));
    }

    public function storeFaq(Request $request)
    {
        $validated = $request->validate([
            'category' => 'required|string|max:100',
            'question' => 'required|string|max:255',
            'answer' => 'required|string',
            'sort_order' => 'nullable|integer',
        ]);

        $faq = Faq::create(array_merge($validated, [
            'sort_order' => $validated['sort_order'] ?? 0,
            'is_active' => true,
        ]));

        AuditLog::record('admin_created_faq', $faq);

        return back()->with('success', 'FAQ added successfully.');
    }

    public function deleteFaq(string $id)
    {
        $faq = Faq::findOrFail($id);
        $faq->delete();

        AuditLog::record('admin_deleted_faq', null, ['question' => $faq->question]);

        return back()->with('success', 'FAQ removed.');
    }
}
