<?php

namespace App\Http\Controllers;

use App\Http\Requests\CropSizeRequest;
use App\MediaRepository;
use App\Services\RemoveBg;
use Illuminate\Http\Request;
use Mtc\ContentManager\Http\Requests\MediaUploadRequest;
use Mtc\ContentManager\Http\Controllers\MediaController as MtcMediaController;
use Mtc\ContentManager\ImageSize;
use Mtc\MercuryDataModels\MediaUse;

class MediaController extends MtcMediaController
{
    /**
     * Process file upload
     *
     * @param Request $request
     * @return mixed
     */
    public function store(MediaUploadRequest $request)
    {

        if ($request->fileIsImage() && request()->input('removeBackground') == 'true') {
            (new RemoveBg())->handle($request->file('file'));
        }

        return parent::store($request);
    }

    public function cropMediaSize(CropSizeRequest $request, MediaUse $mediaUse, MediaRepository $repository)
    {
        $size = ImageSize::fromArray($request->input());
        $coordinates = $request->input('coordinates');

        // Use coordinate-based cropping if coordinates provided, otherwise use default
        if ($coordinates) {
            $result = $repository->makeSizeWithCoordinates($mediaUse->media, $size, $coordinates);
        } else {
            $result = $repository->createSize($mediaUse->media, $size, true);
        }

        if (!empty($result)) {
            $size_list = $mediaUse->allowed_sizes ?? [];
            $sizeString = $size->getWidth() . 'x' . $size->getHeight();
            if (!in_array($sizeString, $size_list)) {
                $size_list[] = $sizeString;
                $mediaUse->update([
                    'allowed_sizes' => $size_list
                ]);
            }

            return response()->json([
                'url' => $mediaUse->getUrl($sizeString),
                'size' => $sizeString,
            ]);
        }

        return response()->json(['error' => 'Failed to crop image'], 500);
    }

    public function getStats(MediaRepository $repository)
    {
        return response()->json($repository->getStats());
    }
}
