<?php

namespace App\Http\Controllers;

use App\Models\Student;
use App\Models\StudentDocument;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;

class StudentDocumentController extends Controller
{
    public function store(Request $request, Student $student): RedirectResponse
    {
        Gate::authorize('update', $student);

        $data = $request->validate([
            'type' => 'required|string|in:'.implode(',', array_keys(StudentDocument::TYPES)),
            'title' => 'nullable|string|max:150',
            'file' => 'required|file|mimes:pdf,jpg,jpeg,png,webp|max:4096',
        ]);

        $file = $request->file('file');
        $path = $file->store("branches/{$student->branch_id}/students/{$student->id}/docs", 'public');

        $student->documents()->create([
            'branch_id' => $student->branch_id,
            'type' => $data['type'],
            'title' => $data['title'] ?? StudentDocument::TYPES[$data['type']],
            'path' => $path,
            'mime' => $file->getClientMimeType(),
            'size' => $file->getSize(),
        ]);

        return back()->with('success', 'Document uploaded.');
    }

    public function destroy(Student $student, StudentDocument $document): RedirectResponse
    {
        Gate::authorize('update', $student);
        abort_unless($document->student_id === $student->id, 404);

        if (Storage::disk('public')->exists($document->path)) {
            Storage::disk('public')->delete($document->path);
        }
        $document->delete();

        return back()->with('success', 'Document deleted.');
    }
}
