<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Pizza;

class PizzaController extends Controller
{
    public function index()
    {
        $pizzas = Pizza::all();
        return view('admin.pizzas.index', compact('pizzas'));
    }

    public function create()
    {
        return view('admin.pizzas.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama_pizza' => 'required|string|max:255',
            'deskripsi'  => 'required|string',
            'harga'      => 'required|numeric',
            'gambar'     => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        $gambarPath = $request->file('gambar')->store('pizzas', 'public');

        Pizza::create([
            'nama_pizza' => $request->nama_pizza,
            'deskripsi'  => $request->deskripsi,
            'harga'      => $request->harga * 1000, // input 20 → tersimpan 20000
            'gambar'     => $gambarPath
        ]);

        return redirect()->route('admin.pizzas.index')->with('success', 'Pizza berhasil ditambahkan!');
    }

    public function edit(Pizza $pizza)
    {
        return view('admin.pizzas.edit', compact('pizza'));
    }

    public function update(Request $request, Pizza $pizza)
    {
        $request->validate([
            'nama_pizza' => 'required|string|max:255',
            'deskripsi'  => 'required|string',
            'harga'      => 'required|numeric',
            'gambar'     => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);

        if ($request->hasFile('gambar')) {
            $gambarPath = $request->file('gambar')->store('pizzas', 'public');
            $pizza->gambar = $gambarPath;
        }

        $pizza->nama_pizza = $request->nama_pizza;
        $pizza->deskripsi  = $request->deskripsi;
        $pizza->harga      = $request->harga * 1000; // input 20 → tersimpan 20000
        $pizza->save();

        return redirect()->route('admin.pizzas.index')->with('success', 'Pizza berhasil diperbarui!');
    }

    public function destroy(Pizza $pizza)
    {
        $pizza->delete();
        return redirect()->route('admin.pizzas.index')->with('success', 'Pizza berhasil dihapus!');
    }
}
