<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class CustomerController extends Controller {
    // Menampilkan daftar user
    public function index(Request $request) {
        $query = User::query();

        if ($request->has('search')) {
            $query->where('name', 'LIKE', '%' . $request->search . '%')
                  ->orWhere('email', 'LIKE', '%' . $request->search . '%');
        }

        $users = $query->get();
        return view('admin.customer', compact('users'));
    }

    // Menampilkan form tambah user
    public function create() {
        return view('admin.createcustomer');
    }

    // Menyimpan data user baru
    public function store(Request $request) {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:100|unique:users,email',
            'password' => 'required|string|min:6',
            'role' => 'required|in:admin,user,pemilik'
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'role' => $request->role
        ]);

        return redirect()->route('admin.customer')->with('success', 'User berhasil ditambahkan.');
    }

    // Menampilkan form edit user
    public function edit($id) {
        $user = User::findOrFail($id);
        return view('admin.editcustomer', compact('user'));
    }

    // Memperbarui data user
    public function update(Request $request, $id) {
        $user = User::findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:100|unique:users,email,' . $id,
            'password' => 'nullable|string|min:6',
            'role' => 'required|in:admin,user,pemilik'
        ]);

        // Jika password kosong, gunakan password lama
        $password = $request->password ? Hash::make($request->password) : $user->password;

        $user->update([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $password,
            'role' => $request->role
        ]);

        return redirect()->route('admin.customer')->with('success', 'User berhasil diperbarui.');
    }

    // Menghapus data user
    public function destroy($id) {
        $user = User::findOrFail($id);

        $user->delete();

        return redirect()->route('admin.customer')->with('success', 'User berhasil dihapus.');
    }
}
