<?php

    namespace Modules\Lpj\Http\Controllers;

    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Storage;
    use Modules\Lpj\Models\LampiranDokumen;

    class LampiranDokumenController extends Controller
    {
        public function download($id)
        {
            $lampiran = LampiranDokumen::findOrFail($id);
            return Storage::download($lampiran->path_file, $lampiran->nama_file);
        }

        public function upload(Request $request)
        {
            $request->validate([
                'permohonan_id'     => 'required|exists:permohonan,id',
                'jenis_lampiran_id' => 'required|exists:jenis_lampiran,id',
                'nama_file'         => 'nullable|string|max:255',
                'file'              => 'required|file|max:10240',
                'keterangan'        => 'nullable|string|max:255',
            ]);

            $lampiran = LampiranDokumen::uploadLampiran($request->all());

            if ($lampiran) {
                return redirect()->back()->with('success', 'Lampiran uploaded successfully');
            } else {
                return redirect()->back()->with('error', 'Unauthorized or upload failed');
            }
        }

        public function delete(LampiranDokumen $lampiran)
        {
            if ($lampiran->deleteLampiran()) {
                return redirect()->back()->with('success', 'Lampiran deleted successfully');
            } else {
                return redirect()->back()->with('error', 'Unauthorized or delete failed');
            }
        }
    }
