<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }

    /**
     * Menampilkan halaman daftar admin
     * 
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $admins = Admin::all();
        return view('admin', compact('admins'));
    }
    
    /**
     * Menampilkan form tambah admin
     * 
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('tambah-admin');
    }
    
    /**
     * Menyimpan admin baru
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'username' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:admins',
            'no_telp' => 'required|string|max:20',
            'alamat' => 'required|string',
            'password' => 'required|string|min:8'
        ]);

        $validated['password'] = Hash::make($validated['password']);
        
        Admin::create($validated);
        
        return redirect()->route('admin')->with('success', 'Admin berhasil ditambahkan');
    }
    
    /**
     * Menampilkan form edit admin
     * 
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $admin = Admin::findOrFail($id);
        return view('edit-admin', compact('admin'));
    }
    
    /**
     * Update data admin
     * 
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $admin = Admin::findOrFail($id);
        
        $validated = $request->validate([
            'username' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:admins,email,' . $id,
            'no_telp' => 'required|string|max:20',
            'alamat' => 'required|string',
            'password' => 'nullable|string|min:8'
        ]);

        if (!empty($validated['password'])) {
            $validated['password'] = Hash::make($validated['password']);
        } else {
            unset($validated['password']);
        }
        
        $admin->update($validated);
        
        return redirect()->route('admin')->with('success', 'Data admin berhasil diperbarui');
    }
    
    /**
     * Menghapus admin
     * 
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        $admin = Admin::findOrFail($id);
        $admin->delete();
        
        return redirect()->route('admin')->with('success', 'Admin berhasil dihapus');
    }
} 