<?php

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

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Http\Requests\AdminDesa\ImportVoterRequest;
use App\Modules\Pilkades\Http\Requests\AdminDesa\StoreVoterRequest;
use App\Modules\Pilkades\Models\Tps;
use App\Modules\Pilkades\Models\Voter;
use App\Modules\Pilkades\Services\VoterService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class VoterController extends Controller
{
    public function __construct(protected VoterService $voterService) {}

    public function index(Request $request): View
    {
        $voters = Voter::with('tps')
            ->when($request->filled('q'), fn ($q) => $q->where('nama', 'like', '%'.$request->string('q').'%'))
            ->latest()
            ->paginate(20);

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

    public function create(): View
    {
        $tpsList = Tps::orderBy('urutan')->get();

        return view('pilkades::admin-desa.voter.create', compact('tpsList'));
    }

    public function store(StoreVoterRequest $request): RedirectResponse
    {
        $this->authorize('create', Voter::class);

        $this->voterService->create(Auth::user()->desa_id, $request->validated());

        return redirect()->route('admin-desa.voter.index')->with('success', 'Pemilih berhasil ditambahkan.');
    }

    public function edit(Voter $voter): View
    {
        $this->authorize('update', $voter);

        $tpsList = Tps::orderBy('urutan')->get();

        return view('pilkades::admin-desa.voter.edit', compact('voter', 'tpsList'));
    }

    public function update(StoreVoterRequest $request, Voter $voter): RedirectResponse
    {
        $this->authorize('update', $voter);

        $this->voterService->update($voter, $request->validated());

        return redirect()->route('admin-desa.voter.index')->with('success', 'Data pemilih berhasil diperbarui.');
    }

    public function destroy(Voter $voter): RedirectResponse
    {
        $this->authorize('delete', $voter);

        $voter->delete();

        return back()->with('success', 'Data pemilih berhasil dihapus.');
    }

    public function showImport(): View
    {
        return view('pilkades::admin-desa.voter.import');
    }

    public function import(ImportVoterRequest $request): RedirectResponse
    {
        $this->authorize('create', Voter::class);

        $result = $this->voterService->importFromCsv(Auth::user()->desa_id, $request->file('file'));

        return back()->with('importResult', $result);
    }
}
