<?php

namespace App\Modules\Pilkades\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Modules\Pilkades\Http\Requests\SuperAdmin\StoreAdminDesaRequest;
use App\Modules\Pilkades\Mail\AdminDesaCredentialsMail;
use App\Modules\Pilkades\Models\Desa;
use App\Modules\Pilkades\Services\DesaService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Illuminate\View\View;

class AdminDesaController extends Controller
{
    public function __construct(protected DesaService $desaService) {}

    public function index(): View
    {
        $admins = User::where('role', 'admin_desa')->with('desa.kecamatan.kabupaten')->latest()->paginate(15);

        return view('pilkades::super-admin.admin-desa.index', compact('admins'));
    }

    public function store(StoreAdminDesaRequest $request, Desa $desa): RedirectResponse
    {
        $this->desaService->createAdminDesa(
            $desa,
            $request->validated('name'),
            $request->validated('email'),
            $request->validated('jabatan'),
        );

        return back()->with('success', 'Admin Desa berhasil dibuat. Kredensial telah dikirim via email.');
    }

    public function toggleActive(User $user): RedirectResponse
    {
        $user->update(['is_active' => ! $user->is_active]);

        return back()->with('success', 'Status Admin Desa berhasil diperbarui.');
    }

    public function resetPassword(User $user): RedirectResponse
    {
        $plainPassword = Str::password(12);
        $user->update(['password' => Hash::make($plainPassword)]);

        Mail::to($user->email)->queue(
            new AdminDesaCredentialsMail($user, $plainPassword, route('login'))
        );

        return back()->with('success', 'Password berhasil direset dan dikirim via email.');
    }
}
