<?php

namespace App\Http\Controllers;

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

class PenggunaController extends Controller
{
    /**
     * Menampilkan halaman daftar pengguna
     * 
     * @return \Illuminate\View\View
     */
    public function index()
    {
        $pengguna = User::where('tipe_pengguna', 'admin')->get();
        return view('pengguna', compact('pengguna'));
    }
    
    /**
     * Menampilkan form tambah pengguna
     * 
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('tambah-pengguna');
    }
    
    /**
     * Menyimpan pengguna baru
     * 
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        try {
            DB::beginTransaction();
            
            $validated = $request->validate([
                'nama' => 'required|string|max:255',
                'username' => 'required|string|max:255|unique:users',
                'email' => 'required|string|email|max:255|unique:users',
                'no_telp' => 'required|string|max:20',
                'alamat' => 'required|string',
                'password' => 'required|string|min:8',
                'tipe_pengguna' => 'required|in:admin,user'
            ]);

            $validated['password'] = Hash::make($validated['password']);
            
            $user = User::create($validated);
            
            DB::commit();
            
            return redirect()->route('pengguna')
                ->with('success', 'Admin berhasil ditambahkan');
                
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error saat menambah admin: ' . $e->getMessage());
            
            return redirect()->back()
                ->withInput()
                ->withErrors(['error' => 'Terjadi kesalahan saat menyimpan data. Silakan coba lagi.']);
        }
    }
    
    /**
     * Menghapus pengguna
     * 
     * @param  int  $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        try {
            $user = User::findOrFail($id);
            $user->delete();
            
            return redirect()->route('pengguna')
                ->with('success', 'Admin berhasil dihapus');
                
        } catch (\Exception $e) {
            Log::error('Error saat menghapus admin: ' . $e->getMessage());
            
            return redirect()->back()
                ->withErrors(['error' => 'Terjadi kesalahan saat menghapus data.']);
        }
    }
} 