<?php

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

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Countdown;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class CountdownController extends Controller
{
    public function edit(): View
    {
        $countdown = Countdown::firstOrCreate(
            ['desa_id' => Auth::user()->desa_id],
            ['label' => 'Hari Pemungutan Suara', 'target_datetime' => now()->addMonth()],
        );

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

    public function update(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'label' => ['required', 'string', 'max:255'],
            'target_datetime' => ['required', 'date'],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $countdown = Countdown::firstOrCreate(['desa_id' => Auth::user()->desa_id]);
        $countdown->update($data);

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