<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Deferment;
use Illuminate\Support\Str;

class StudentDefermentController extends Controller
{
    public function index()
    {
        $registrationNumber = strtoupper(Auth::user()->username);

        // ✅ Fetch student deferment history
        $requests = Deferment::where('registration_number', $registrationNumber)
            ->orderByDesc('created_at')
            ->get();

        return view('student.deferment', compact('requests'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'reason' => 'required|string|min:10',
            'attachment' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:2048',
        ]);

        $registrationNumber = strtoupper(Auth::user()->username);
        $fileName = null;

        // ✅ Handle optional attachment upload
        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $fileName = Str::random(10) . '_' . time() . '.' . $file->getClientOriginalExtension();
            $file->storeAs('public/deferments', $fileName);
        }

        // ✅ Insert record into deferments table
        Deferment::create([
            'registration_number' => $registrationNumber,
            'reason' => $request->reason,
            'attachment' => $fileName,
            'status' => 'pending',
        ]);

        return redirect()->route('student.deferment')->with('success', 'Deferment request submitted successfully.');
    }
}
