<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\StoreAdminAttachmentRequest;
use App\Http\Controllers\Controller;
use App\Models\Attachment;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class UploadController extends Controller
{
    public function store(StoreAdminAttachmentRequest $request): Response
    {
        $validated = $request->validated();
        $file = $validated['userImage'];
        $userId = (int) Auth::id();
        $extension = strtolower($file->getClientOriginalExtension() ?: $file->extension() ?: 'jpg');
        $fileName = now()->format('Ymd_His').'_'.$userId.'_'.Str::random(12).'.'.$extension;
        $relativePath = 'images/'.$fileName;
        $targetDirectory = base_path('files/images');

        File::ensureDirectoryExists($targetDirectory);
        $file->move($targetDirectory, $fileName);

        $attachment = Attachment::query()->create([
            'att_name' => $fileName,
            'att_slug' => $fileName,
            'att_url' => $relativePath,
            'att_date' => now(),
            'userid' => $userId,
        ]);

        return response()->view('admin.upload.preview', [
            'previewUrl' => ASSETURL.'files/'.$attachment->att_url,
            'photoId' => $attachment->id,
        ]);
    }
}
