<?php

namespace App\Http\Controllers;

use App\Models\MediaAsset;
use App\Services\BunnyCDNService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;

class MediaController extends Controller
{
    protected BunnyCDNService $bunnyCDNService;

    public function __construct(BunnyCDNService $bunnyCDNService)
    {
        $this->bunnyCDNService = $bunnyCDNService;
    }

    public function index(Request $request)
    {
        $folder = $request->query('folder'); // optional

        $q = MediaAsset::query()->latest();

        if ($folder) {
            $q->where('folder', $folder);
        }

        return response()->json([
            'data' => $q->paginate(24),
        ]);
    }

    public function upload(Request $request)
    {
        $request->validate([
            'image'  => 'required|string',      // base64 string: data:image/...;base64,...
            'folder' => 'nullable|string|max:60',
            'name'   => 'nullable|string|max:120',
        ]);

        $base64Image = $request->input('image');

        // ✅ Basic validation: must look like a base64 data-url image
        if (!preg_match('#^data:image/(\w+);base64,#i', $base64Image, $m)) {
            return response()->json([
                'message' => 'Invalid image format. Expected base64 data URL (data:image/...;base64,...)',
            ], 422);
        }

        $ext = strtolower($m[1] ?? 'jpg');
        if ($ext === 'jpeg') $ext = 'jpg';

        // allow only common image extensions
        $allowed = ['jpg', 'png', 'webp', 'gif'];
        if (!in_array($ext, $allowed, true)) {
            return response()->json([
                'message' => 'Unsupported image type. Allowed: jpg, png, webp, gif.',
            ], 422);
        }

        // sanitize folder
        $folder = trim($request->input('folder', 'uploads'), '/');
        $folder = preg_replace('#[^a-zA-Z0-9/_-]#', '', $folder) ?: 'uploads';

        // Build remote file name: folder/2026/01/uuid-name.ext
        $safeName = Str::slug($request->input('name') ?: 'file');
        $remoteFileName = $folder . '/' . date('Y/m') . '/' . Str::uuid() . '-' . ($safeName ?: 'file') . '.' . $ext;

        // Decode base64
        $raw = preg_replace('#^data:image/\w+;base64,#i', '', $base64Image);
        $imageData = base64_decode($raw);

        if ($imageData === false) {
            return response()->json([
                'message' => 'Invalid base64 image data.',
            ], 422);
        }

        // Temp directory
        $tempDirectory = storage_path('app/public/temp');
        if (!File::exists($tempDirectory)) {
            File::makeDirectory($tempDirectory, 0777, true);
        }

        $tempFilePath = $tempDirectory . '/' . Str::uuid() . '.' . $ext;
        File::put($tempFilePath, $imageData);

        try {
            // Upload to Bunny
            $url = $this->bunnyCDNService->uploadImage($tempFilePath, $remoteFileName);

            if (!$url) {
                return response()->json([
                    'message' => 'Upload failed (no URL returned).',
                ], 500);
            }

            // meta
            $width = null;
            $height = null;
            $info = @getimagesize($tempFilePath);
            if (is_array($info)) {
                $width = $info[0] ?? null;
                $height = $info[1] ?? null;
            }

            $size = File::exists($tempFilePath) ? File::size($tempFilePath) : 0;

            // save asset
            $asset = MediaAsset::create([
                'name' => $request->input('name') ?: 'Image',
                'file_name' => $remoteFileName,
                'folder' => $folder,
                'url' => $url,
                'mime' => 'image/' . ($ext === 'jpg' ? 'jpeg' : $ext),
                'size' => $size,
                'width' => $width,
                'height' => $height,
                'alt' => null,
                'title' => null,
                'created_by' => auth()->id(),
            ]);

            return response()->json([
                'message' => 'Uploaded successfully',
                'data' => $asset,
                'url' => $asset->url,
            ], 201);
        } finally {
            // always cleanup temp file
            if (File::exists($tempFilePath)) {
                File::delete($tempFilePath);
            }
        }
    }

    public function destroy($id)
    {
        $asset = MediaAsset::findOrFail($id);
        $asset->delete();

        return response()->json(['message' => 'Deleted']);
    }
}
