<?php

namespace App\Http\Controllers;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class ImageController extends Controller
{
    public function createOn(Request $request, $service, $model, $id){
        $path = '/images/' . $service . '/' . $model;
        $imageName = Storage::disk('public')->putFile($path, $request->file('image'));
        $imagePath = implode('/', [env('APP_URL'), 'storage', $imageName]);
        $thumbnailsPath = public_path('storage'.$path.'/thumbnails');

        if(!File::isDirectory($thumbnailsPath))
            File::makeDirectory($thumbnailsPath, 0777, true, true);
            
        $thumbnail = \IImage::make('storage'.'/'.$imageName)->resize(300, 300, function ($constraint) {
            $constraint->aspectRatio();
        });

        $thumbnail->dirname = $thumbnailsPath;
        $thumbnail->save();
        if($service == 'cms') {
            $response = Http::withHeaders([
                'Authorization' => env('secret'),
                'Accept' => 'application/json' 
            ])->post(env('CMS_ADDRESS').'/api/admin/images/create/'.$id,  [
                'user_token' => auth()->user()->token,
                'alt' => "تصویر محصول",
                'path'      => $imagePath,
            ]);
            return response($response->json());
        }
        $response = Http::withHeaders([
            'Authorization' => env('secret'),
            'Accept' => 'application/json' 
        ])->post(env('PIM_ADDRESS').'/api/admin/images/create/on/'.$model.'/'.$id,  [
            'user_token' => auth()->user()->token,
            'primary' => 1,
            'title' => $request->title.'image',
            'alt' => "تصویر محصول",
            'path'      => $imagePath,
            'thumbnail' => implode('/', [env('APP_URL'), 'storage', substr($path, 1), 'thumbnails', $thumbnail->basename]),
        ]);
        return response($response->json());
    }
    public function delete(Request $request, $id){
        $response = Http::withHeaders([
            'Authorization' => env('secret'),
            'Accept' => 'application/json' 
        ])->delete(env('PIM_ADDRESS').'/api/admin/images/delete/'.$id,  [
            'user_token' => auth()->user()->token,
        ]);
        return response($response->json());
    }
}
