<?php

namespace App\Http\Controllers\Frontend\Graphics;

use App\Http\Controllers\Controller;
use App\Models\Graphics\CustomGraphicsRequest;
use App\Models\Graphics\CustomGraphicsRequestMedia;
use App\Models\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class CustomGraphicsRequestController extends Controller
{

    // show a list of requests for this user, filtered by status
    public function myRequestList($status = null)
    {
        $custom_graphics_requests = CustomGraphicsRequest::where('user_id', \Auth::user()->id)->get();
        $tags = Tag::all();
        return view('frontend.custom_graphics_request.list')
            ->with('tags', $tags)
            ->with('custom_graphics_requests', $custom_graphics_requests);
    }

    // show a list of requests to the admin, filtered by status
    public function adminRequestList($status = null)
    {
        return view('backend.custom_graphics_request.list');
    }

    // the public facing index page for a single request
    public function viewFrontend($id)
    {
        return view('frontend.custom_graphics_request.view');
    }

    // the admin interface
    public function viewBackend($id)
    {
        return view('backend.custom_graphics_request.view');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     * @todo validation
     */
    public function store(Request $request)
    {
        dd($request->file);
        // store the thread
        $thread = CustomGraphicsRequest::create([
            'name' => $request['name'],
            'description' => $request['description'],
            'status' => 'new',
            'user_id' => auth()->id(),
        ]);

        // save tags
        if (isset($request['tags'])) {
            $thread->tags()->sync($request['tags']);
        }
        //store any associated media
        foreach ($request->file as $image) {
            $type = strtolower($image->getClientOriginalExtension());
            $originalname = $image->getClientOriginalName();
            $filename = $image->getFilename();
            $path = $image->getPath();
            $size = $image->getSize();
            // is this an allowed type?
            if (!in_array($type, ['jpg', 'jpeg', 'png'])) {
                throw new GeneralException('You must supply a jpg or png image.');
            }

            // get the md5 hash of the contents. This allows for different files with the same name in teh same directory...
            $md5name = md5(file_get_contents($path . DIRECTORY_SEPARATOR . $filename));

            // Intervention image
            $img = Image::make($image);

            // fix any weird mobile orientation issues
            $img->orientate();

//        // Make the image a 200x200 square
            $img->resize(($img->getHeight() > $img->getWidth()) ? 640 : 960, null, function ($constraint) {
                $constraint->aspectRatio();
            });
//        // crop to square
//        $img->crop(200, 200);

            // save with the UUID as a filename
            $img->save(Storage::disk('forum_media')->path('/') . $md5name);
            $media = CustomGraphicsRequestMedia::updateOrCreate(['name' => $originalname,
                'size' => $size,
                'type' => $type,
                'location' => $md5name,
                'comment'=>'',
                'path' => Storage::disk('custom_graphics_request_media')->path('/') . $md5name,
                'custom_graphics_requests_id' => $thread->id]);

            // $user->avatar_location = 'avatars/' . $user->uuid . '.jpg';
//            return array(
//                'location' => route('frontend.customgraphicsrequest.displaymedia', $media->id),
//            );
        }


        return array(
            'status' => (($thread->id > 0) ? 0 : 1),
        );

    }


    public function update(Request $request, $id)
    {
        //validation part
        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect(@route('frontend.lab.index', ['id' => $id]) . "?edit=open")
                ->withErrors($validator)
                ->withInput();
        }
    }


}
