<?php

namespace App\Http\Controllers\Instansi;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class PengaturanController extends Controller
{
    public function index()
    {
        $user     = Auth::user();
        $instansi = $user->instansi;

        return view('instansi.pengaturan.index', compact('user', 'instansi'));
    }

    public function updateInstansi(Request $request)
    {
        $instansi = Auth::user()->instansi;

        $request->validate([
            'nama_instansi' => 'required|string|max:200',
            'alamat'        => 'nullable|string|max:500',
            'latitude'      => 'required|numeric|between:-90,90',
            'longitude'     => 'required|numeric|between:-180,180',
            'radius_meter'  => 'required|integer|min:10|max:10000',
        ]);

        $instansi->update($request->only([
            'nama_instansi', 'alamat', 'latitude', 'longitude', 'radius_meter'
        ]));

        return back()->with('success', 'Data instansi berhasil diperbarui.');
    }

    public function updateAkun(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'name'     => 'required|string|max:100',
            'email'    => 'required|email|unique:users,email,' . $user->id,
            'password' => 'nullable|min:8|confirmed',
        ]);

        $data = [
            'name'  => $request->name,
            'email' => $request->email,
        ];

        if ($request->filled('password')) {
            $data['password'] = Hash::make($request->password);
        }

        $user->update($data);

        return back()->with('success', 'Data akun berhasil diperbarui.');
    }
}