<?php

namespace AleshaCMS\Http\Controllers\Admin;

use AleshaCMS\Http\Controllers\Controller;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Illuminate\Http\Request;

class MediaController extends Controller
{
    protected function mediaUrl(Media $m): string
    {
        return '/storage/' . $m->id . '/' . $m->file_name;
    }

    protected function mediaData(Media $m): array
    {
        return [
            'id'        => $m->id,
            'name'      => $m->name,
            'url'       => $this->mediaUrl($m),
            'thumb'     => $this->mediaUrl($m),
            'mime_type' => $m->mime_type,
            'size'      => $m->size,
            'caption'   => $m->getCustomProperty('caption', ''),
        ];
    }

    public function index(Request $request)
    {
        $media = Media::query()
            ->when($request->search, fn($q) => $q->where('name', 'like', "%{$request->search}%"))
            ->when($request->type, fn($q) => $q->where('mime_type', 'like', "{$request->type}/%"))
            ->latest()
            ->paginate(24);

        if ($request->wantsJson()) {
            return response()->json([
                'data' => $media->map(fn($m) => $this->mediaData($m)),
                'meta' => [
                    'current_page' => $media->currentPage(),
                    'last_page'    => $media->lastPage(),
                    'total'        => $media->total(),
                ],
            ]);
        }

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

    public function store(Request $request)
    {
        $request->validate([
            'file'    => 'required|file|max:51200|mimes:jpg,jpeg,png,gif,webp,pdf,mp4,mov,avi,mp3,zip,doc,docx,xls,xlsx,ppt,pptx',
            'caption' => 'nullable|string|max:500',
        ]);

        $adder = auth()->user()
            ->addMediaFromRequest('file')
            ->withCustomProperties(['caption' => $request->input('caption', '')]);

        $media = $adder->toMediaCollection('uploads');

        return response()->json($this->mediaData($media));
    }

    public function update(Request $request, Media $media)
    {
        $user = auth()->user();
        if ($media->model_id !== $user->id && !$user->hasRole('admin')) {
            abort(403);
        }

        $request->validate(['caption' => 'nullable|string|max:500']);
        $media->setCustomProperty('caption', $request->input('caption', ''));
        $media->save();

        return response()->json(['success' => true, 'caption' => $media->getCustomProperty('caption', '')]);
    }

    public function destroy(Media $media)
    {
        $user = auth()->user();
        if ($media->model_id !== $user->id && !$user->hasRole('admin')) {
            abort(403);
        }

        $media->delete();
        return response()->json(['success' => true]);
    }

    public function browse(Request $request)
    {
        $media = Media::query()
            ->when($request->search, fn($q) => $q->where('name', 'like', "%{$request->search}%"))
            ->when($request->type, fn($q) => $q->where('mime_type', 'like', "{$request->type}/%"))
            ->latest()
            ->paginate(20);

        return response()->json([
            'data' => $media->map(fn($m) => $this->mediaData($m)),
            'meta' => [
                'current_page' => $media->currentPage(),
                'last_page'    => $media->lastPage(),
            ],
        ]);
    }
}
