<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    public function index()
    {
        // Mengambil seluruh data dan join manual
        $category = Category::select('categories.*', DB::raw('COUNT(products.id) AS jumlah_produk'))
            ->leftJoin('products', 'categories.id', '=', 'products.category_id')
            ->groupBy('categories.id', 'categories.nama_kategori')
            ->orderBy('categories.id', 'ASC')
            ->get();

        // Mengambil seluruh data dan sql join tanpa squely
        // $category = Category::withCount('products')->orderBy('id', 'ASC')->get();
        
        // $category = Category::all();
        return view('category', compact('category'));
    }

    public function store(Request $request)
    {
        // Debugging: Cek data yang dikirim dari form
        // dd($request->all());

        $request->validate([
            'nama_kategori' => 'required',
        ]);

        Category::create([
            'nama_kategori' => $request->nama_kategori, // Sesuaikan dengan input form
        ]);

        return redirect()->back()->with('success', 'Kategori berhasil ditambahkan!');
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'nama_kategori' => 'required',
        ]);

        $category = Category::findOrFail($id);

        // Update data category
        $category->nama_kategori = $request->nama_kategori;
        $category->save();

        return redirect()->back()->with('success', 'Kategori berhasil diperbarui!');
    }

    public function destroy($id)
    {
        $category = Category::findOrFail($id);
        $category->delete();

        return response()->json(['success' => true]);
    }
}
