<?php

namespace Ignite\Core\Entities;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    /**
     * The name of the table.
     *
     * @var string
     */
    protected $table = 'core_transaction';

    /**
     * The guarded attributes.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The transaction types
     * @var array
     */
    protected $types = [
        // System applied
        'CANCELLED',
        'EARNED',
        'REDEEMED',
        // Manually applied
        'MANUAL-RECEIVE',
        'MANUAL-REDEEM',
        // Not implemented
        'EXPIRED',
        'RESET',
        'RETURN',
    ];

    /**
     * The default types.
     *
     * @return array
     */
    public function getTypes()
    {
        return $this->types;
    }

    /**
     * The relationship to the claim participant.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function claimParticipant()
    {
        return $this->morphTo('claimParticipant', 'related_type', 'related_id');
    }

    /**
     * The relationship to the offer.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     */
    public function offer()
    {
        return $this->morphTo('claim_offer', 'related_type', 'related_id');
    }

    /**
     * The participant associated with the transaction.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function participant()
    {
        return $this->belongsTo(Participant::class, 'user_id', 'user_id');
    }

    /**
     * Scope a query to the current user.
     *
     * @param  Builder $query
     * @return Builder
     */
    public function scopeByCurrentUser(Builder $query)
    {
        $query->where('user_id', auth()->user()->getKey());

        return $query;
    }

    /**
     * Scope a query to the current user.
     *
     * @param  Builder $query
     * @param  User|int $user
     * @return Builder
     */
    public function scopeByUser(Builder $query, $user)
    {
        if ($user instanceof User || $user instanceof Participant) {
            $query->where('user_id', $user->getKey());
        } else {
            $query->where('user_id', $user);
        }


        return $query;
    }
}
