<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

use App\Models\Photo;
use App\Models\ContentElement;
use App\Traits\SoftDeletesControllerTrait;
use App\Http\Requests\PhotoValidation;

use App\Models\Page;
use App\Models\Tag;
use App\Utilities\Paginate;

class PhotosController extends Controller
{
    use SoftDeletesControllerTrait;

    protected function getModel()
    {
        return new Photo();
    }

    public function paginate()
    {
        if (!auth()->user()->can('viewAny', Photo::class)) {
            return response()->json(['error' => 'You do not have permission to view photos'], 403);
        }

        $tags = null;

        if (request('terms')) {
            $tags = (new Tag())->search(request('terms'), true);
        }

        return Paginate::create(Photo::getPhotos($tags));
    }

    public function store(PhotoValidation $request, $id)
    {
        $photo = (new Photo())->savePhoto(requestInput(), $id);

        return response()->json([
            'success' => 'Photo Saved',
            'photo' => $photo,
        ]);
    }

    public function remove($id)
    {
        $photo = Photo::findOrFail($id);

        if (!auth()->check()) {
            return abort(401);
        }

        $remove = false;

        if (auth()->user()->can('update', $photo->content)) {
            $remove = true;
        }

        if (auth()->user()->can('update', $photo->content->contentElement)) {
            $remove = true;
        }

        if (auth()->user()->can('delete', $photo)) {
            $remove = true;
        }

        if (!$remove) {
            return response()->json(['error' => 'You do not have permission to remove that model'], 403);
        }

        $photo->delete();

        return response()->json(['success' => 'Photo Removed']);
    }

    public function hide($id)
    {
        $photo = Photo::findOrFail($id);

        if (!auth()->user()->can('delete', $photo)) {
            return response()->json(['error' => 'You do not have permission to hide that photo'], 403);
        }

        $photos = Photo::where('file_upload_id', $photo->fileUpload->id)->get()->each(function ($p) {
            if (!$p->hidden_at) {
                $p->hidden_at = now();
            } else {
                $p->hidden_at = null;
            }
            $p->save();
        });
        $photo->refresh();

        cache()->tags(['photos'])->flush();

        return response()->json(['success' => 'Photo '.($photo->hidden_at ? 'Hidden' : 'Unhidden')]);
    }

    public function download($id)
    {
        $photo = Photo::findOrFail($id);

        if (!auth()->user()->can('download', $photo)) {
            return response()->json(['error' => 'You do not have permission to download that photo'], 403);
        }

        return Storage::download($photo->fileUpload->storage_filename, $photo->fileUpload->name);
    }
}
