<?php

namespace App\Http\Controllers;

use App\User;
use App\Instansi;
use App\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AdminInstansiController extends Controller
{
    public function create()
    {
        $instansis = Instansi::orderBy('nama_instansi')->get();
        return view('admin_instansi.create', compact('instansis'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name'        => 'required|string|max:255',
            'email'       => 'required|email|unique:users,email',
            'instansi_id' => 'required|exists:instansis,id',
            'password'    => 'nullable|min:6|confirmed',
        ]);

        $roleAdmin = Role::where('nama_role', 'Admin Instansi')->first();

        if (!$roleAdmin) {
            return back()->withErrors(['role' => 'Role Admin Instansi tidak ditemukan di sistem.'])->withInput();
        }

        User::create([
            'name'        => $request->name,
            'email'       => $request->email,
            'instansi_id' => $request->instansi_id,
            'role_id'     => $roleAdmin->id,
            'password'    => $request->filled('password')
                                ? Hash::make($request->password)
                                : null,
        ]);

        return redirect()->route('admininstansi.create')
            ->with('success', 'Admin Instansi berhasil ditambahkan!');
    }
}