<?php

namespace App\Http\Controllers;

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

class AdminDefermentController extends Controller
{
    public function index()
    {
        // Eager load the user relationship
        $deferments = Deferment::with('user')->latest()->get();

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

    public function create()
    {
        return view('admin.deferments.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'reason' => 'required',
            'status' => 'required',
        ]);

        Deferment::create([
            'user_id' => $request->user_id,
            'reason' => $request->reason,
            'status' => $request->status,
            'attachment' => $request->attachment ?? null,
        ]);

        return redirect()->route('admin.deferments.index')->with('success', 'Deferment created.');
    }

    public function show(Deferment $deferment)
    {
        return view('admin.deferments.show', compact('deferment'));
    }

    public function edit(Deferment $deferment)
    {
        return view('admin.deferments.edit', compact('deferment'));
    }

    public function update(Request $request, Deferment $deferment)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'reason' => 'required',
            'status' => 'required',
        ]);

        $deferment->update([
            'user_id' => $request->user_id,
            'reason' => $request->reason,
            'status' => $request->status,
            'attachment' => $request->attachment ?? null,
        ]);

        return redirect()->route('admin.deferments.index')->with('success', 'Deferment updated.');
    }

    public function destroy(Deferment $deferment)
    {
        $deferment->delete();
        return redirect()->route('admin.deferments.index')->with('success', 'Deferment deleted.');
    }
}
