<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\AduanTps;
use App\Models\LokasiTps;

class AduanController extends Controller
{

    public function index(Request $request)
    {
        $title = 'Aduan TPS';
        $tps = null;
        if ($request->filled('tps_id')) {
            $tps = LokasiTps::with('kategori')
                ->where('id_tps', $request->tps_id)
                ->first();
        }
        $listTps = LokasiTps::orderBy('nama_tps')->get();

        return view('user.aduan-tps', compact(
            'title',
            'tps',
            'listTps'
        ));
    }

    public function store(Request $request)
    {
        $request->validate([
            'lokasi_tps_id' => 'required|exists:lokasi_tps,id_tps',
            'nama_pelapor'  => 'required|string|max:100',
            'alamat_pelapor'=> 'required|string',
            'no_pelapor'    => 'required|string|max:20',
            'isi_aduan'     => 'required|string',
            'bukti_foto'    => 'required|image|mimes:jpg,jpeg,png|max:4096',
        ], [
            'lokasi_tps_id.required' => 'TPS wajib dipilih',
            'bukti_foto.required'   => 'Foto bukti wajib diunggah',
            'bukti_foto.image'      => 'File harus berupa gambar',
        ]);

        $fotoPath = $request->file('bukti_foto')
            ->store('aduan', 'public');

        AduanTps::create([
            'lokasi_tps_id' => $request->lokasi_tps_id,
            'nama_pelapor'  => $request->nama_pelapor,
            'alamat_pelapor'=> $request->alamat_pelapor,
            'no_pelapor'    => $request->no_pelapor,
            'isi_aduan'     => $request->isi_aduan,
            'bukti_foto'    => $fotoPath,
            'tanggal_aduan' => now(),
        ]);

        return redirect()
            ->route('user.aduan')
            ->with('success', 'Aduan berhasil dikirim');
    }
}
