<?php

namespace App\Http\Controllers;

use App\Models\MenuModel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MenuController extends Controller
{
    public function index(){
        $totalMenuMakanan = MenuModel::where('id_kategory', 'makanan')->count();
        $totalMenuMinuman = MenuModel::where('id_kategory', 'minuman')->count();
        $allMenu = MenuModel::all()->count();
        return view('menu/main',compact('totalMenuMakanan','totalMenuMinuman','allMenu'));
    }

    public function FormTambahMenu(){
        $totalMenuMakanan = MenuModel::where('id_kategory', 'makanan')->count();
        $totalMenuMinuman = MenuModel::where('id_kategory', 'minuman')->count();
        $allMenu = MenuModel::all()->count();
        return view('menu/form-tambah-menu',compact('totalMenuMakanan','totalMenuMinuman','allMenu'));
    }

    function DaftarMenu(){
        $dataMenu = MenuModel::all();
        $totalMenuMakanan = MenuModel::where('id_kategory', 'makanan')->count();
        $totalMenuMinuman = MenuModel::where('id_kategory', 'minuman')->count();
        $allMenu = MenuModel::all()->count();
        return view('menu/daftar-menu',compact('dataMenu','totalMenuMakanan','totalMenuMinuman','allMenu'));
    }

    public function SimpanMenu(Request $request) {
        $aturan = [
            'for_nama_makanan'  => 'required|unique:menu,nama',
            'for_kategory'      => 'required',
            'for_img'           => 'nullable|mimes:png,jpg,jpeg|max:2048', // Ganti required dengan nullable
            'for_harga'         => 'required',
            'for_jenis_menu'    => 'required'
        ];
    
        $messages = [
            'required' => 'Tidak boleh kosong',   
            'unique'   => 'Sudah ada',   
        ];
    
        $validator = Validator::make($request->all(), $aturan, $messages);
    
        if ($validator->fails()) {
            return redirect()
                ->route('form-tambah-menu')
                ->withErrors($validator)
                ->withInput();
        }
    
        // Handle file upload jika ada file baru yang diunggah
        $filename = null;
        if ($request->hasFile('for_img') && $request->file('for_img')->isValid()) {
            $photo = $request->file('for_img');
            $filename = date('Y-m-d') . '_' . $photo->getClientOriginalName();
            $path = 'gambar-menu/' . $filename;
            Storage::disk('public')->put($path, file_get_contents($photo));
        }
    
        try {
            $insert = MenuModel::create([
                'id_kategory'   => strtoupper($request->for_kategory),
                'nama'          => $request->for_nama_makanan,
                'harga'         => $request->for_harga,
                'jenis_menu'    => $request->for_jenis_menu,
                'jenis_paket'   => $request->for_jenis_paket,
                'dibuat_oleh'   => Auth::user()->name,
                'img'           => $filename // Simpan filename jika ada
            ]);
    
            if ($insert) {
                return redirect()->route('daftar-menu')
                    ->with('success', 'Menu berhasil disimpan');
            }
    
        } catch (\Throwable $th) {
            return redirect()
                ->route('form-tambah-menu')
                ->with('danger', $th->getMessage());
        }
    }
    
    function UpdateMenu($id){
        $dataUpdateMenu = MenuModel::where('id',$id)->first();
        $dataMenu = MenuModel::all();
        $totalMenuMakanan = MenuModel::where('id_kategory', 'makanan')->count();
        $totalMenuMinuman = MenuModel::where('id_kategory', 'minuman')->count();
        $allMenu = MenuModel::all()->count();

        if (!$dataUpdateMenu){
            return redirect()->route('transaksi')
            ->with('danger', 'Data tidak ditemukan');
        }
        return view('menu.update-menu',compact('dataUpdateMenu','dataMenu','totalMenuMakanan','totalMenuMinuman','allMenu'));
    }

    public function SimpanUpdateMenu(Request $request, $id)
    {
        // Aturan validasi
        $aturan = [
            'for_nama_makanan'  => 'required|unique:menu,nama,'.$id,
            'for_kategory'      => 'required',
            'for_img'           => 'nullable|mimes:png,jpg,jpeg|max:2048',
            'for_harga'         => 'required',
            'for_jenis_menu'    => 'required'
        ];
    
        // Pesan error custom
        $messages = [
             'required' => 'Tidak boleh kosong',   
             'unique' => 'Sudah ada',   
        ];
    
        // Validasi input
        $validator = Validator::make($request->all(), $aturan, $messages);
        
        if ($validator->fails()) {
            return redirect()
                ->route('update-menu', ['id' => $id])
                ->withErrors($validator)
                ->withInput();
        }
    
        // Mencari dan memperbarui menu
        $menu = MenuModel::find($id);
        
        if (!$menu) {
            return redirect()->route('daftar-menu')
                ->with('danger', 'Menu tidak ditemukan');
        }
    
        // Handle file upload jika ada file baru yang diunggah
        if ($request->hasFile('for_img')) {
            $photo = $request->file('for_img');
            $filename = date('Y-m-d') . $photo->getClientOriginalName();
            $path = 'gambar-menu/' . $filename;
            Storage::disk('public')->put($path, file_get_contents($photo));
            $menu->img = $filename;  // Update nama file gambar di database
        }
        
        // Update data
        $menu->update([
            'id_kategory'   => strtoupper($request->for_kategory),
            'nama'          => $request->for_nama_makanan,
            'harga'         => $request->for_harga,
            'jenis_menu'    => $request->for_jenis_menu,
            'jenis_paket'   => $request->for_jenis_paket,
            'dibuat_oleh'   => Auth::user()->name,
            'img'           => $menu->img ?? $menu->img  // Tetap gunakan gambar lama jika tidak ada gambar baru
        ]);
    
        return redirect()->route('daftar-menu')
            ->with('success', 'Data menu berhasil diperbarui!');
    }
    
}
