<?php

namespace App\Http\Controllers\Admin;

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

class BlogController extends Controller
{
    public function index()
    {
        $blogs = Blog::all();
        return view('admin.blog.index', compact('blogs'));
    }

    public function create()
    {
        return view('admin.blog.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title'=>'required|string|max:255',
            'content'=>'required|string',
            'image'=>'nullable|image|mimes:jpg,jpeg,png|max:2048'
        ]);

        $data = $request->all();
        if($request->hasFile('image')){
            $data['image'] = $request->file('image')->store('blogs','public');
        }

        Blog::create($data);
        return response()->json(['success'=>'Blog created successfully!']);
    }

    public function edit(Blog $blog)
    {
        return view('admin.blog.edit', compact('blog'));
    }

    public function update(Request $request, Blog $blog)
{
    $request->validate([
        'title'=>'required|string|max:255',
        'content'=>'required|string',
        'image'=>'nullable|image|mimes:jpg,jpeg,png|max:2048'
    ]);

    $blog->title = $request->title;
    $blog->content = $request->content;

    if($request->hasFile('image')){
        $blog->image = $request->file('image')->store('blogs','public');
    }

    $blog->save();

    return response()->json(['success'=>'Blog updated successfully!']);
}

   public function destroy($id)
{
    $blog = Blog::find($id);
    if ($blog) {
        $blog->delete();
        return response()->json(['success' => 'Blog deleted successfully']);
    }
    return response()->json(['error' => 'Blog not found'], 404);
}
// public function show($id)
// {
//     // Blog model import होना चाहिए ऊपर
//     // use App\Models\Blog;
    
//     $blog = Blog::findOrFail($id);

//     return view('admin.blog.show', compact('blog'));
// }
// public function show($slug)
// {
//     $blog = Blog::where('slug', $slug)->firstOrFail();
//     return view('blog.show', compact('blog'));
// }
}
