<?php

namespace App\Policies;

use App\Models\Item;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class ItemPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function add(User $user)
    {
        return $user->id > 0;
    }

    public function update(User $user, Item $item)
    {
        if (!$item) {
            $item = new Item();
        }

        if (Gate::allows('update', $item)) {
            return redirect()->back();
        }
        return $user->id === $item->user_id;
    }

    public function destroy(User $user, Item $item)
    {
        $user = $user ?: Auth::user();
        if ($user && $item) {
            return ($user->id === $item->user_id);
        }
        return false;
    }

    public function before(User $user)
    {
        $user = $user ?: Auth::user();
        if ($user->role()->first()->name === 'admin') {
            return true;
        }
    }
}
