<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AduanTps;
use Illuminate\Http\Request;

class AduanController extends Controller
{
    /**
     * Tampilkan semua aduan
     */
    public function index(Request $request)
    {
        $search = $request->search;

        $aduan = AduanTps::with('lokasiTps')
            ->when($search, function ($query) use ($search) {
                $query->whereHas('lokasiTps', function ($q) use ($search) {
                    $q->where('nama_tps', 'like', '%' . $search . '%');
                });
            })
            ->orderBy('tanggal_aduan', 'desc')
            ->paginate(10);

        return view('admin.aduan.index', compact('aduan'));
    }

    public function show($id)
    {
        $aduan = AduanTps::findOrFail($id);
        return view('admin.aduan.edit', compact('aduan'));
    }

    public function tanggapi(Request $request, $id)
    {
        $request->validate([
            'tanggapan_admin' => 'required|string|min:5|max:1000'
        ], [
            'tanggapan_admin.required' => 'Tanggapan admin wajib diisi.',
            'tanggapan_admin.min' => 'Tanggapan minimal 5 karakter.',
            'tanggapan_admin.max' => 'Tanggapan maksimal 1000 karakter.',
        ]);

        $aduan = AduanTps::findOrFail($id);
        $aduan->tanggapan_admin = $request->tanggapan_admin;
        $aduan->tanggal_tanggapan = now();
        $aduan->save();

        return redirect()->route('admin.aduan.index')
            ->with('success', 'Tanggapan berhasil disimpan');
    }

    /**
     * Hapus tanggapan admin
     */
    public function destroy($id)
    {
        $aduan = AduanTps::findOrFail($id);

        // Hapus file bukti foto jika ada
        if ($aduan->bukti_foto && file_exists(public_path('assets/user/img/aduan/' . $aduan->bukti_foto))) {
            unlink(public_path('assets/user/img/aduan/' . $aduan->bukti_foto));
        }

        // Hapus data aduan dari database
        $aduan->delete();

        return redirect()->route('admin.aduan.index')
            ->with('success', 'Aduan berhasil dihapus');
    }
}
