<?php

namespace App\Http\Controllers;

use App\Models\Mekanik;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;

class MekanikController extends Controller
{
    public function index()
    {
        return view('pages.mekanik', [
            'mekanik' => Mekanik::all()
        ]);
    }

    public function add(Request $request)
    {
        $file = $request->file('foto');
        $filename = null;

        if ($file) {
            $filename = uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('img'), $filename);
        }

        Mekanik::create([
            'nama'     => $request->nama,
            'no_telp'  => $request->no_telp,
            'alamat'  => $request->alamat,
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'foto'     => $filename
        ]);

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

    public function update(Request $request, $id)
    {
        $data = Mekanik::find($id);
        if (!$data) {
            return back()->with('error', 'Data tidak ditemukan');
        }

        $file = $request->file('foto');
        $filename = $data->foto;

        if ($file) {
            if ($data->foto && File::exists(public_path('img/' . $data->foto))) {
                File::delete(public_path('img/' . $data->foto));
            }

            $filename = uniqid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('img'), $filename);
        }

        $data->update([
            'nama'     => $request->nama,
            'no_telp'  => $request->no_telp,
            'alamat'  => $request->alamat,
            'username' => $request->username,
            'password' => $request->password ? Hash::make($request->password) : $data->password,
            'foto'     => $filename
        ]);

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

    public function delete($id)
    {
        $data = Mekanik::find($id);
        if (!$data) {
            return back()->with('error', 'Data tidak ditemukan');
        }

        if ($data->foto && File::exists(public_path('img/' . $data->foto))) {
            File::delete(public_path('img/' . $data->foto));
        }

        $data->delete();

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