<?php

namespace App\Http\Controllers;

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

class BrandController extends Controller
{
    public function index()
    {
        // Mengambil seluruh data dan join manual
        $brand = Brand::select('brands.*', DB::raw('COUNT(products.id) AS jumlah_produk'))
            ->leftJoin('products', 'brands.id', '=', 'products.brand_id')
            ->groupBy('brands.id', 'brands.nama_brand')
            ->orderBy('brands.id', 'ASC')
            ->get();

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

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

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

        Brand::create([
            'nama_brand' => $request->nama_brand,
        ]);

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

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

        $brand = Brand::findOrFail($id);

        // Update data brand
        $brand->nama_brand = $request->nama_brand;
        $brand->save();

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

    public function destroy($id)
    {
        $brand = Brand::findOrFail($id);
        $brand->delete();

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