<?php

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

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

class TpsController extends Controller
{
    public function index(): View
    {
        $tpsList = Tps::orderBy('urutan')->get();

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

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'nomor' => ['required', 'string', 'max:50'],
            'nama_lokasi' => ['required', 'string', 'max:255'],
            'alamat' => ['nullable', 'string', 'max:255'],
            'urutan' => ['nullable', 'integer'],
        ]);

        $data['desa_id'] = Auth::user()->desa_id;

        Tps::create($data);

        return back()->with('success', 'TPS berhasil ditambahkan.');
    }

    public function update(Request $request, Tps $tps): RedirectResponse
    {
        $data = $request->validate([
            'nomor' => ['required', 'string', 'max:50'],
            'nama_lokasi' => ['required', 'string', 'max:255'],
            'alamat' => ['nullable', 'string', 'max:255'],
            'urutan' => ['nullable', 'integer'],
        ]);

        $tps->update($data);

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

    public function destroy(Tps $tps): RedirectResponse
    {
        $tps->delete();

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