<?php

namespace App\Http\Controllers\API\User;

use Validator;
use Illuminate\Http\Request;

use App\Http\Controllers\API\ApiController;
use App\Http\Traits\FileSystemTrait;
use App\Models\User;

/**
 * Class Profile
 *
 * @package App\Http\Controllers\API\User
 */
class Profile extends ApiController
{

    use FileSystemTrait;

    /**
     * View logged user profile
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function view()
    {
        return $this->response
            ->setResponse([
                'user' => $this->user->apiOutputData(),
            ])
            ->setSuccess(true)
            ->toJson();
    }

    /**
     * Update logged user profile info
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request)
    {
        $errors = Validator::make($request->all(), [
            'mobile' => 'required'
        ])->messages();

        if (0 === count($errors->all())) {
            $this->user->mobile = $request->get('mobile');
            $this->user->save();

            $this->response->setMessage(trans('messages.profile_updated'));
        }

        return $this->response
            ->setResponse([
                'user' => $this->user->apiOutputData(),
            ])
            ->setSuccess((0 === count($errors->all())) ? true : false)
            ->setErrors($errors)
            ->toJson();
    }

    /**
     * Update user profile photo
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadProfilePhoto(Request $request)
    {
        $errors = Validator::make($request->all(), [
            'picture' => 'required'
        ])->messages();

        if (0 === count($errors->all())) {
            if (null !== $file = $this->handleUploadPicture($request)) {
                $this->user->picture = $file->getFilename();
                $this->user->save();

                $this->response
                    ->setResponse([ 'picture' => $this->user->getAvatar([ 'customerid' => $request->header('CustomerID'), 'width' => 180, 'height' => 180 ]) ])
                    ->setMessage(trans('messages.profile_image_updated'));
            }
        }

        return $this->response
            ->setSuccess((0 === count($errors->all())) ? true : false)
            ->setErrors($errors)
            ->toJson();
    }

    /**
     * Render profile picture
     *
     * @param \Illuminate\Http\Request $request
     * @param mixed                    $customerId
     * @param int                      $width
     * @param int                      $height
     * @param string                   $filename
     * @return string
     */
    public function showPicture(Request $request, $customerId, $width, $height, $filename)
    {
        $filename = storage_path('users_images/' . $customerId . '/' . $filename);
        //dd($filename);
        if ( ! file_exists($filename)) {
            return abort(404, 'Image not found.');
        }

        $setWidth = ($request->has('width') && $request->get('width') > 0) ? $request->get('width') : $width;
        $setHeight = ($request->has('height') && $request->get('height') > 0) ? $request->get('height') : $height;

        $img = \Image::make($filename)->orientate();
        if ($setWidth > 0) {
            if ($setHeight > 0) {
                $img->resize($setWidth, $setHeight);
            } else {
                $img->resize($setWidth, null, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });
            }
        }

        return $img->response();
    }

    /**
     * Handle upload picture
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\File|null
     */
    protected function handleUploadPicture(Request $request)
    {
        $image = null;

        if ($request->hasFile('picture') && $request->file('picture')->isValid()) {
            // Get file from post and upload on server
            $image = FileSystemTrait::uploadFileToStorage(
                User::ROOT_STORAGE_FILES . $this->getCustomerId(),
                $this->user->oid,
                $request->file('picture'));
        }

        return $image;
    }
}