<?php

namespace Ignite\Core\Entities;

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

class Transaction extends Base
{
    const EARNED = 'EARNED';
    const REDEEMED = 'REDEEMED';
    const CANCELLED = 'CANCELLED';
    const MANUAL_RECEIVE = 'MANUAL-RECEIVE';
    const MANUAL_REDEEM = 'MANUAL-REDEEM';
    const EXPIRED = 'EXPIRED';
    const RESET = 'RESET';
    const RETURN = 'RETURN';

    /**
     * The name of the table.
     *
     * @var string
     */
    protected $table = 'core_transaction';

    /**
     * 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 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;
    }
}
