<?php

namespace App\Http\Controllers\Admin;

use App\Model\Photo;
use DB;


trait Photos
{

    public function process($item, $request, $model)
    {
        // we got a re-arange of photos.
        if ($photos = $request->get('priority')) {
            foreach ($photos as $key => $current_photo) {
                // or $user->photos()->whereId($item['id'])->get()->first();
                $photo = $item->photos()->find($current_photo['id']);
                $photo->priority = $current_photo['priority'];
                $photo->save();
            }
            return;
        }

        // delete photo
        if ($request->isMethod('delete')) {
            $photo = $item->photos()->find($request->get('id'));
            if ($photo) {
                $photo->delete();
            }
            return;
        }

        // initialize a new photo for current $item.
        $photo = new $model;
        $photo->item()->associate($item->id);

        // go ask for a upload.
        $photo->upload($request->file('photo'));

        // save photo to the article
        $item->photos()->save($photo);

        // return the view again
        return view('admin.parts.photo.item', compact('item', 'photo'));
    }

    public function list($item)
    {
        // return in froala style
        return $item->photos->map(function ($item) {
            $item->use_absolute_path = false;
            $url = $item->getPhotoUrl();
            return [
                'url' => $url,
                'basename' => basename($url),
                'thumb' => $item->getThumbUrl(),
            ];
        });
    }

}
