<?php

namespace App\Models;

use App\Traits\hasCurrency;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    use HasFactory, hasCurrency;

    const TYPE_INCOME = 'income';
    const TYPE_EXPENSE = 'expense';

    const STATUS_SUCCESS = 'success';
    const STATUS_PENDING = 'pending';

    const CATEGORY_TRANSFER = 'transfer';
    const CATEGORY_TICKET = 'ticket';
    const CATEGORY_BOOKING = 'booking';
    const CATEGORY_BOARDING = 'boarding';

    protected $fillable = ['account_id', 'ticket_id', 'category', 'paid_at', 'amount', 'status', 'type', 'currency_code', 'exchange_rate','balance'];

    protected $attributes = [
        'status' => self::STATUS_SUCCESS,
    ];

    protected $currency_attributes = ['amount'];

    public function account()
    {
        return $this->belongsTo(Account::class, 'account_id', 'id');
    }
    
    public function ticket()
    {
        return $this->belongsTo(Ticket::class);
    }

    protected static function booted()
    {
        if(auth()->user()->office_id !=null)
        {
            
        
            static::addGlobalScope('transactionUser', function ($builder) {
                if (auth()->check()  && !auth()->user()->isAdmin()) {
                    $builder->whereHas('account', function ($query) {
                        $query->where('user_id', auth()->id());
                        if (auth()->user()->office_id) {
                            $query->orWhere('office_id', auth()->user()->office_id);
                        }
                    });
                }
            });
    
            static::creating(function ($transaction) {
                if ($transaction->type == self::TYPE_EXPENSE) {
                    $transaction->amount = -$transaction->amount;
                }
                $transaction->account->balance += $transaction->amount;
                $transaction->account->save();
            });
    
            static::deleting(function ($transaction) {
                $transaction->account->balance -= $transaction->amount;
                $transaction->account->save();
            });
       }
    }
     public function transfers()
    {
        return $this->hasmany('App\Models\Transfer');
    }
}
