<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Media;
use App\Services\UploadedImageOptimizer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MediaController extends Controller
{
    public function __construct(
        protected UploadedImageOptimizer $imageOptimizer
    ) {}

    public function index()
    {
        return view('admin.media.index', [
            'media' => Media::latest()->paginate(24),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'file' => 'required|file|image|max:20480',
        ]);
        $file = $request->file('file');
        $path = $file->store('media/'.date('Y/m'), 'public');
        $this->imageOptimizer->optimizeStoredFile($path);
        Media::create([
            'filename' => $file->getClientOriginalName(),
            'path' => $path,
            'mime_type' => $file->getMimeType(),
            'size' => Storage::disk('public')->size($path),
        ]);

        return back()->with('success', 'Fichier uploadé.');
    }

    /** Upload via AJAX, retourne le chemin pour remplir un champ image. */
    public function uploadApi(Request $request)
    {
        $request->validate([
            'file' => 'required|file|image|max:20480',
        ]);
        $file = $request->file('file');
        $path = $file->store('media/'.date('Y/m'), 'public');
        $this->imageOptimizer->optimizeStoredFile($path);
        Media::create([
            'filename' => $file->getClientOriginalName(),
            'path' => $path,
            'mime_type' => $file->getMimeType(),
            'size' => Storage::disk('public')->size($path),
        ]);

        return response()->json(['path' => $path, 'url' => Storage::url($path)]);
    }

    public function destroy(Media $medium)
    {
        Storage::disk('public')->delete($medium->path);
        $medium->delete();

        return back()->with('success', 'Fichier supprimé.');
    }
}
