<?php

namespace App\Http\Controllers;

use App\Models\Notice;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File;

class NoticeController extends Controller
{
    private const UPLOAD_DIRECTORY = 'uploads/notices';

    public function index()
    {
        $notices = Notice::latest()->get();
        return view('notices.index', compact('notices'));
    }

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

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

        $data = $request->only('title');

        if ($request->hasFile('uploads')) {
            $data['uploads'] = $this->storeUpload($request->file('uploads'));
        }

        Notice::create($data);

        return redirect()->route('notices.index')->with('success', 'Notice added successfully.');
    }

    public function edit(Notice $notice)
    {
        return view('notices.edit', compact('notice'));
    }

    public function update(Request $request, Notice $notice)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'uploads' => 'nullable|file|mimes:pdf,doc,docx,jpg,png|max:2048',
        ]);

        $data = $request->only('title');

        if ($request->hasFile('uploads')) {
            $this->deleteUpload($notice->uploads);
            $data['uploads'] = $this->storeUpload($request->file('uploads'));
        }

        $notice->update($data);

        return redirect()->route('notices.index')->with('success', 'Notice updated successfully.');
    }

    public function destroy(Notice $notice)
    {
        $this->deleteUpload($notice->uploads);

        $notice->delete();

        return redirect()->route('notices.index')->with('success', 'Notice deleted successfully.');
    }

    private function storeUpload(UploadedFile $file): string
    {
        $directory = public_path(self::UPLOAD_DIRECTORY);
        File::ensureDirectoryExists($directory);

        $filename = time() . '_' . $file->getClientOriginalName();
        $file->move($directory, $filename);

        return self::UPLOAD_DIRECTORY . '/' . $filename;
    }

    private function deleteUpload(?string $path): void
    {
        if ($path && File::exists(public_path($path))) {
            File::delete(public_path($path));
        }
    }
}
