<?php

namespace App\Http\Controllers;

use App\Http\Resources\Image as ImageResource;
use App\Models\Memo;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;

class ImageController extends Controller
{
    public function users(User $user)
    {
        foreach (auth()->user()->images as $image) {
            if(File::exists(storage_path('app/public/'.$image->path))) {
                File::delete(storage_path('app/public/'.$image->path));
                auth()->user()->images()->where('id', $image->id)->delete();
            }
        }

        $data = $this->storeImage();

        $newImage = auth()->user()->images()->create([
            'path' => $data['path'],
            'width' => $data['width'],
            'height' => $data['height'],
            'location' => $data['location'],
        ]);

        $this->haveThumbnailImage($data, auth()->user());

        auth()->user()->update(['updated_at' => now()]);

        return new ImageResource($newImage);
    }

    public function memos(Memo $memo)
    {
        foreach ($memo->images as $image) {
            if(File::exists(storage_path('app/public/'.$image->path))) {
                File::delete(storage_path('app/public/'.$image->path));
                $memo->images()->where('id', $image->id)->delete();
            }
        }

        $data = $this->storeImage();

        $newImage = $memo->images()->create([
            'path' => $data['path'],
            'width' => $data['width'],
            'height' => $data['height'],
            'location' => $data['location'],
        ]);

        $this->haveThumbnailImage($data, $memo);

        $memo->update(['updated_at' => now()]);

        return new ImageResource($newImage);
    }

    private function haveThumbnailImage($data, $object)
    {
        Image::make($data['image'])
            ->fit(round($data['width'] / 3, 0), round($data['height'] / 3, 0))
            ->save(storage_path('app/public/thumbnail/images/'.$data['image']->hashName()));

        $object->images()->create([
            'path' => "thumbnail/".$data['path'],
            'width' => round($data['width'] / 3, 0),
            'height' => round($data['height'] / 3, 0),
            'location' => $data['location']."-small",
        ]);
    }

    private function storeImage()
    {
        $data = request()->validate([
            'image' => 'required',
            'width' => 'required',
            'height' => 'required',
            'location' => 'required',
        ]);

        $data['path'] = $data['image']->store('images', 'public');

        Image::make($data['image'])
            ->fit($data['width'], $data['height'])
            ->save(storage_path('app/public/images/'.$data['image']->hashName()));

        return $data;
    }
}
