<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function index()
    {
        // Mengambil semua data produk dengan brand dan kategori
        $product = Product::select('products.*', 'brands.nama_brand as brand', 'categories.nama_kategori as kategori')->join('brands', 'products.brand_id', '=', 'brands.id')->join('categories', 'products.category_id', '=', 'categories.id')->orderBy('products.id', 'DESC')->get();

        // $product = Product::all();
        $brand = Brand::all(); // Ambil semua brand
        $category = Category::all(); // Ambil semua kategori

        return view('product', compact('product', 'brand', 'category'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama_produk' => 'required',
            'brand_id' => 'required|integer',
            'category_id' => 'required|integer',
            'harga' => 'required|numeric|min:0',
            'stok' => 'required|integer|min:0',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);

        // Data awal tanpa gambar
        $data = [
            'nama_produk' => $request->nama_produk,
            'brand_id' => $request->brand_id,
            'category_id' => $request->category_id,
            'harga' => $request->harga,
            'stok' => $request->stok,
            'status' => 'aktif',
        ];

        // Cek jika ada file gambar diupload
        if ($request->hasFile('image')) {
            $foto = $request->file('image');
            
            // Format nama file: nama_produk.ekstensi (contoh: Kopi_Susu.png)
            $namaBersih = preg_replace('/[^A-Za-z0-9\-]/', '_', $request->nama_produk);
            $ekstensi = $foto->getClientOriginalExtension();
            $namaFoto = $namaBersih . '.' . $ekstensi;
            
            // Path penyimpanan
            $path = public_path('upload/produk/');
            
            // Hapus file lama jika ada
            if (isset($produk->image) && file_exists($path . $produk->image)) {
                unlink($path . $produk->image);
            }
            
            $foto->move($path, $namaFoto);
            
            // Simpan hanya nama file (tanpa path)
            $data['image'] = $namaFoto; 
        }

        // Debugging sebelum simpan ke database
        // dd($data);

        // Simpan ke database
        Product::create($data);

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

    public function update(Request $request, $id)
{
    $request->validate([
        'nama_produk' => 'required',
        'brand_id' => 'required',
        'category_id' => 'required',
        'harga' => 'required|numeric',
    ]);

    $product = Product::findOrFail($id);

    // Update data produk
    $product->nama_produk = $request->nama_produk;
    $product->brand_id = $request->brand_id;
    $product->category_id = $request->category_id;
    $product->harga = $request->harga;

    // Cek apakah ada file foto baru diupload
if ($request->hasFile('image')) {
    $file = $request->file('image');
    
    // Format nama file: nama_produk.ekstensi (contoh: Kopi_Susu.png)
    $namaBersih = preg_replace('/[^A-Za-z0-9\-]/', '_', $request->nama_produk);
    $ekstensi = $file->getClientOriginalExtension();
    $fileName = $namaBersih . '.' . $ekstensi;
    
    // Path penyimpanan
    $uploadPath = public_path('upload/produk/');
    
    // Hapus foto lama jika ada
    if ($product->image) {
        $oldFilePath = $uploadPath . $product->image;
        if (file_exists($oldFilePath)) {
            unlink($oldFilePath);
        }
    }
    
    // Pindahkan file baru
    $file->move($uploadPath, $fileName);
    
    // Simpan hanya nama file (tanpa path)
    $product->image = $fileName;
    
    // Jika menggunakan update array
    // $data['image'] = $fileName;
}

    $product->save();

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


    public function destroy($id)
    {
        $product = Product::findOrFail($id);
        $product->delete();

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