<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Media;
use App\Services\FileUploadService;
use Illuminate\Http\Request;

class MediaController extends Controller
{
    public function index()
    {
        $media = Media::latest()->paginate(24);

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

    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:jpeg,jpg,png,webp,gif,svg,pdf,doc,docx|max:10240',
        ]);

        $path = FileUploadService::store($request->file('file'), 'media');
        $file = $request->file('file');

        Media::create([
            'name' => $file->getClientOriginalName(),
            'path' => $path,
            'type' => $file->getMimeType(),
            'size' => $file->getSize(),
            'alt_text' => $request->alt_text,
        ]);

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

    public function update(Request $request, Media $media)
    {
        $request->validate([
            'alt_text' => 'nullable|string|max:255',
        ]);

        $media->update(['alt_text' => $request->alt_text]);

        return back()->with('success', 'Alt text updated.');
    }

    public function destroy(Media $media)
    {
        if (\Illuminate\Support\Facades\Storage::disk('public')->exists($media->path)) {
            \Illuminate\Support\Facades\Storage::disk('public')->delete($media->path);
        }

        $media->delete();

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