<?php

namespace App\Http\Controllers;

use App\Models\Unit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class UnitController extends Controller
{
    public function index()
    {
        $data['unit'] = Unit::all();

        return view('pages.master.unit', $data);
    }

    public function add(Request $request)
    {
        $file = $request->file('icon');

        if ($file) {
            $filename = 'icon_' . uniqid() . '_' . $request->nama . '.' . $file->getClientOriginalExtension();
            $file->move('img/icon', $filename);
        } else {
            $filename = null;
        }

        Unit::create([
            'nama' => $request->nama,
            'keterangan' => $request->keterangan,
            'icon' => $filename
        ]);

        return redirect()->back()->with('success', 'Data Berhasil Disimpan');
    }

    public function update(Request $request, $id)
    {
        $data = Unit::find($id);

        $file = $request->file('icon');

        if ($file) {
            File::delete(public_path('img/icon/' . $data->icon));

            $filename = 'icon_' . uniqid() . '_' . $request->nama . '.' . $file->getClientOriginalExtension();
            $file->move('img/icon', $filename);
        } else {
            $filename = $data->icon;
        }

        $data->update([
            'nama' => $request->nama,
            'keterangan' => $request->keterangan,
            'icon' => $filename
        ]);

        return redirect()->back()->with('success', 'Data Berhasil Disimpan');
    }

    public function delete($id)
    {
        $data = Unit::find($id);
        File::delete(public_path('img/icon/' . $data->icon));

        Unit::find($id)->delete();

        return redirect()->back()->with('success', 'Data Berhasil Disimpan');
    }
}
