<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ProductAdminController extends Controller
{
    public function index(): View
    {
        return view('admin.products', [
            'products' => Product::query()->latest()->paginate(20),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        Product::query()->create($request->validate([
            'slug' => ['required', 'string', 'max:120', 'alpha_dash:ascii', 'unique:products,slug'],
            'name' => ['required', 'string', 'max:180'],
            'status' => ['required', 'string', 'in:active,inactive,archived'],
        ]));

        return back()->with('status', 'Product dibuat.');
    }

    public function update(Request $request, Product $product): RedirectResponse
    {
        $product->update($request->validate([
            'name' => ['required', 'string', 'max:180'],
            'status' => ['required', 'string', 'in:active,inactive,archived'],
        ]));

        return back()->with('status', 'Product diperbarui.');
    }

    public function destroy(Product $product): RedirectResponse
    {
        $product->delete();

        return back()->with('status', 'Product dihapus.');
    }
}
