<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PermohonanInformasiAdminController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->get('status');
        $search = $request->get('search');

        $query = DB::table('permohonan_informasi')
            ->orderBy('created_at', 'desc');

        // Filter by status
        if ($status) {
            $query->where('status', $status);
        }

        // Filter by search (nama atau nomor registrasi)
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('nama_pemohon', 'like', "%{$search}%")
                  ->orWhere('nomor_registrasi', 'like', "%{$search}%");
            });
        }

        $permohonan = $query->paginate(15);

        return view('admin.ppid.permohonan.index', compact('permohonan', 'status', 'search'));
    }

    public function show($id)
    {
        $permohonan = DB::table('permohonan_informasi')->where('id', $id)->first();

        if (!$permohonan) {
            return redirect()->route('admin.ppid.permohonan.index')
                ->with('error', 'Data tidak ditemukan');
        }

        return view('admin.ppid.permohonan.show', compact('permohonan'));
    }

    public function updateStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:pending,diproses,disetujui,ditolak,keberatan',
            'catatan_admin' => 'nullable|string'
        ]);

        $updateData = [
            'status' => $request->status,
            'updated_at' => now()
        ];

        // Jika status berubah dari pending, set tanggal ditindaklanjuti
        if ($request->status !== 'pending') {
            $updateData['tanggal_ditindaklanjuti'] = now()->format('Y-m-d');
        }

        // Update catatan admin jika ada
        if ($request->catatan_admin) {
            $updateData['catatan_admin'] = $request->catatan_admin;
        }

        DB::table('permohonan_informasi')
            ->where('id', $id)
            ->update($updateData);

        return redirect()->route('admin.ppid.permohonan.show', $id)
            ->with('success', 'Status permohonan berhasil diperbarui');
    }

    public function destroy($id)
    {
        DB::table('permohonan_informasi')->where('id', $id)->delete();

        return redirect()->route('admin.ppid.permohonan.index')
            ->with('success', 'Permohonan berhasil dihapus');
    }
}
