<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Additional;
use Illuminate\Support\Facades\Validator;

class AdditionalController extends Controller
{
    // Store: Simpan Data Baru
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nama'  => 'required|string|min:3|max:100',
            'harga' => 'required|numeric|min:0',
        ], [
            'required' => 'Kolom :attribute wajib diisi.',
            'numeric'  => ':attribute harus berupa angka.',
            'string'     => 'Input :attribute harus berupa teks valid.',
            'max'        => ':attribute melebihi batas, maksimal :max karakter/KB.',
            'min'        => ':attribute minimal harus :min karakter/nilai.',
            'numeric'    => ':attribute harus berupa angka.',
        ], [
            'nama'  => 'nama additional',
            'harga' => 'harga additional',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error_modal', 'createAdd'); // Membuka modal tambah additional
        }

        Additional::create($request->only(['nama', 'harga']));

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

    // Update: Simpan Perubahan
    public function update(Request $request, string $id)
    {
        $additional = Additional::findOrFail($id);

        $validator = Validator::make($request->all(), [
            'nama'  => 'required|string|min:3|max:100',
            'harga' => 'required|numeric|min:0',
        ], [
            'required' => 'Kolom :attribute wajib diisi.',
            'numeric'  => ':attribute harus berupa angka.',
            'string'     => 'Input :attribute harus berupa teks valid.',
            'max'        => ':attribute melebihi batas, maksimal :max karakter/KB.',
            'min'        => ':attribute minimal harus :min karakter/nilai.',
            'numeric'    => ':attribute harus berupa angka.',
        ], [
            'nama'  => 'nama additional',
            'harga' => 'harga additional',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput()
                ->with('error_id_add', $id); // Membuka modal edit additional
        }

        $additional->update($request->only(['nama', 'harga']));

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

    // Destroy: Hapus Data
    public function destroy(string $id)
    {
        $additional = Additional::findOrFail($id);
        $additional->delete();

        return redirect()->back()->with('success', 'Additional berhasil dihapus!');
    }
}
