<?php

namespace Ignite\Core\Entities;

use Illuminate\Database\Eloquent\Builder;

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',
    ];

    /**
     * Perform any actions required after the model boots.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope(app(Scopes\TransactionScope::class));
    }

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