<?php

namespace App\Models;

use App\Http\Helpers\StripeClient;
use App\Notifications\PayoutApproved;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class PayoutRequest extends Model
{
    use HasFactory;
    protected $guarded=[];
    protected $casts = [
        'approved_at' => 'datetime:Y-m-d',
    ];

    public function approver(){
        return $this->belongsTo(User::class)->withTrashed();
    }

    public function wallet()
    {
        return $this->belongsTo(Wallet::class);
    }


    public function approve()
    {
        $this->approved_at = now();
        $this->approved_by = Auth::user()->id;
        $this->save();
        $payout= StripeClient::payout([
            "amount" => $this->amount,
            'destination'=> $this->billing_data_id,
            "metadata"=>[
                'account'=>$this->stripe_account_id
            ]
        ], $this->stripe_account_id);

        Wallet::find(1)->releaseUpcomingMoneyActivity($this->amount/100);
        Wallet::find(1)->releaseMoneyActivity($this->amount/100, $this->wallet->owner->name . ' payout '. $this->id);
        $this->wallet->releaseMoneyActivity($this->amount/100, 'your withdrawal request',true);
        Transaction::create([
            'amount' => $this->amount/100,
            'type' => 'Payout',
            'from' => 1,
            "to" => $this->wallet->id,
            'status' => $payout->status,
            'milestone_id' => null,
            'stripe_id' => $payout->id,
            'stripe_type' => $payout->object,
            'stripe_data' => json_encode($payout),
        ]);
        $this->wallet->owner->notify(new PayoutApproved());
        return $payout;
    }
}
