<?php

namespace App\Http\Controllers;

use App\Models\Feedback;
use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;

class FeedbackController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $received = Feedback::with('sender:id,surname,firstname')
            ->where('to_user_id', $user->id)
            ->orderByDesc('created_at')
            ->paginate(15, ['*'], 'received_page');

        $sent = Feedback::with('recipient:id,surname,firstname')
            ->where('from_user_id', $user->id)
            ->orderByDesc('created_at')
            ->paginate(15, ['*'], 'sent_page');

        return Inertia::render('Feedback/Index', [
            'received' => $received,
            'sent' => $sent,
        ]);
    }

    public function create()
    {
        $users = User::active()
            ->where('id', '!=', auth()->id())
            ->select('id', 'surname', 'firstname', 'designation', 'department_id')
            ->with('department:id,name')
            ->orderBy('surname')
            ->get();

        return Inertia::render('Feedback/Give', [
            'users' => $users,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'to_user_id' => 'required|exists:users,id',
            'type' => 'required|in:praise,constructive,suggestion',
            'content' => 'required|string|max:2000',
            'is_anonymous' => 'boolean',
        ]);

        $validated['from_user_id'] = $request->user()->id;

        Feedback::create($validated);

        return redirect()->route('feedback.index')->with('success', 'Feedback submitted successfully.');
    }
}
