<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Complaint;

class ComplaintController extends Controller
{
    public function index()
    {
        $complaints = Complaint::orderBy('created_at', 'desc')->get();
        return view('backend.complaints.index', compact('complaints'));
    }

    public function create()
    {
        return view('backend.complaints.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'complainant_name' => 'required|string|max:100',
            'complaint_type' => 'required|string|max:100',
            'complaint' => 'required|string|max:200',
        ]);

        Complaint::create([
            'complainant_name' => $request->complainant_name,
            'complaint_type' => $request->complaint_type,
            'complaint' => $request->complaint,
            'resolve_status' => false,
        ]);

        return redirect()->route('complaints.index')->with('success', 'Complaint submitted successfully!');
    }

    public function show(Complaint $complaint)
    {
        return view('backend.complaints.show', compact('complaint'));
    }

    public function edit(Complaint $complaint)
    {
        return view('backend.complaints.edit', compact('complaint'));
    }

    public function update(Request $request, Complaint $complaint)
    {
        $request->validate([
            'complainant_name' => 'required|string|max:100',
            'complaint_type' => 'required|string|max:100',
            'complaint' => 'required|string|max:200',
            'resolve_status' => 'boolean',
            'budget' => 'nullable|numeric',
        ]);

        $complaint->update([
            'complainant_name' => $request->complainant_name,
            'complaint_type' => $request->complaint_type,
            'complaint' => $request->complaint,
            'resolve_status' => $request->resolve_status ?? false,
            'budget' => $request->budget,
            'resolve_date' => $request->resolve_status ? now() : null,
        ]);

        return redirect()->route('complaints.index')->with('success', 'Complaint updated successfully!');
    }

    public function destroy(Complaint $complaint)
    {
        $complaint->delete();
        return redirect()->route('complaints.index')->with('success', 'Complaint deleted successfully!');
    }
}
