<?php

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

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Http\Requests\AdminDesa\StoreCandidateRequest;
use App\Modules\Pilkades\Models\Candidate;
use App\Modules\Pilkades\Services\CandidateService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class CandidateController extends Controller
{
    public function __construct(protected CandidateService $candidateService) {}

    public function index(): View
    {
        $candidates = Candidate::with('profile')->orderBy('nomor_urut')->get();

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

    public function create(): View
    {
        return view('pilkades::admin-desa.candidate.create');
    }

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

        $this->candidateService->create(
            Auth::user()->desa_id,
            $request->validated(),
            $request->file('foto'),
        );

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

    public function edit(Candidate $candidate): View
    {
        $this->authorize('update', $candidate);
        $candidate->load('profile', 'programs', 'gallery', 'videos');

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

    public function update(StoreCandidateRequest $request, Candidate $candidate): RedirectResponse
    {
        $this->authorize('update', $candidate);

        $this->candidateService->update($candidate, $request->validated(), $request->file('foto'));

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

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

        $candidate->delete();

        return redirect()->route('admin-desa.candidate.index')
            ->with('success', 'Calon berhasil dihapus.');
    }
}
