<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::with('unit')->latest()->get();
        return view('products.index', compact('products'));
    }

    public function create()
    {
        $units = Unit::orderBy('name')->get();

        return view(
            'products.create',
            compact('units')
        );
    }


    public function store(Request $request)
    {
        $data = $request->all();

        if ($request->hasFile('image')) {

            $data['image'] = $request
                ->file('image')
                ->store('products', 'public');
        }

        Product::create($data);

        return redirect('/products')
            ->with('success', 'Produk ditambahkan');
    }

    public function edit(Product $product)
    {
        $units = Unit::orderBy('name')->get();

        return view(
            'products.edit',
            compact('product', 'units')
        );
    }

    public function update(Request $request, Product $product)
    {
        $data = $request->all();

        if ($request->hasFile('image')) {

            if ($product->image) {

                Storage::disk('public')
                    ->delete($product->image);
            }

            $data['image'] = $request
                ->file('image')
                ->store('products', 'public');
        }

        $product->update($data);

        return redirect('/products')
            ->with('success', 'Produk diupdate');
    }

    public function destroy(Product $product)
    {
        $product->delete();
        return redirect('/products')->with('success', 'Produk dihapus');
    }
}
