<?php

namespace App\Http\Controllers\admin;

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

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::all(); 
       return view('admin.category.index', compact('categories'));
    }

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


public function store(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'description' => 'required|string',
        'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048', 
    ]);
    if ($request->hasFile('image_url')) {
        $imageName = time().'.'.$request->file('image_url')->extension();
        $request->file('image_url')->move(public_path('category'), $imageName);
        $validatedData['image'] = 'category/'.$imageName;
    }
    Category::create($validatedData);
    return redirect()->route('admin.category')->with('success', 'Category created successfully!');
}
   public function edit($id) {
    $category = Category::findOrFail($id);
    return view('admin.category.edit',compact('category')); 
   }


  public function update(Request $request, $id)
{
    // Pehle category record find karo
    $category = Category::findOrFail($id);

    // Validation
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'description' => 'required|string',
        'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    // Agar image upload hui hai to purani image delete + nayi save
    if ($request->hasFile('image')) {
        // Purani image delete (agar exist karti hai)
        if ($category->image && file_exists(public_path($category->image))) {
            unlink(public_path($category->image));
        }

        $imageName = time().'.'.$request->file('image')->extension();
        $request->file('image')->move(public_path('category'), $imageName);
        $validatedData['image'] = 'category/'.$imageName;
    }

    // Update existing category
    $category->update($validatedData);

    return redirect()->route('admin.category')->with('success', 'Category updated successfully!');
}


public function destroy($id)
{
    $category = Category::findOrFail($id);
    if ($category->image && file_exists(public_path($category->image))) {
        unlink(public_path($category->image));
    }
    $category->delete();
    return redirect()->route('admin.category')
                     ->with('success', 'Product deleted successfully!');
}
}
