<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Wallet extends Model
{
    use HasFactory;
    use SoftDeletes;
    protected $guarded =[];
    public function payments(){
        return $this->hasMany(Transaction::class,'from');
    }
    public function payouts(){
        return $this->hasMany(Transaction::class,'to');
    }
    public function owner(){
        return $this->morphTo()->withTrashed();
    }
    public function payoutRequests(){
        return $this->hasMany(PayoutRequest::class);
    }
    public function activities(){
        return $this->hasMany(WalletActivity::class);
    }

    public function reserveMoneyActivity($amount, $milestoneName,?bool $user=true){

        if($user){
            $this->upcoming_payments += $amount;
            $this->reserved_funds += $amount;
        }else{
            $this->available_funds += $amount;
        }
        $this->activities()->create([
            'amount' => $amount,
            'activity_en' => $amount .' has been saved to your muhandisin wallet for ' . $milestoneName,
            'activity_ar' => $amount .' تم حفطهم في محفظة مهندسين من اجل ' . $milestoneName,
            'status' => 'reserved',
        ]);
        $this->save();
    }

    public function releaseMoneyActivity($amount, $milestoneName,?bool $worker=false){

        if($worker){
            $this->available_funds -= $amount;
        }else{
            $this->reserved_funds -= $amount;
        }
        $this->activities()->create([
            'amount' => $amount,
            'activity_en' => $amount .' has been released from your muhandisin wallet for ' . $milestoneName,
            'activity_ar' => $amount .' تم سحبههم من محفظة مهندسين من اجل ' . $milestoneName,
            'status' => 'paid',
        ]);
        $this->total_spent += $amount;
        $this->save();
    }

    public function addUpcomingMoneyActivity($amount, $milestoneName){
        $this->upcoming_payments += $amount;
        $this->activities()->create([
            'amount' => $amount,
            'activity_en' => $amount .' has been saved to your muhandisin upcoming payments for ' . $milestoneName,
            'activity_ar' => $amount .' تم حفطهم في محفظة مهندسين للمدفعوات القادمة من اجل ' . $milestoneName,
            'status' => 'reserved',
        ]);
        $this->save();
    }

    public function releaseUpcomingMoneyActivity($amount){
        $this->upcoming_payments -= $amount;
        if($this->upcoming_payments<0){
            $this->upcoming_payments=0;
        }
        $this->save();
    }
}
