<?php

namespace App\Http\Controllers;

use App\Http\Helpers\StripeClient;
use App\Models\Milestone;
use App\Models\Project;
use App\Models\Proposal;
use App\Models\Transaction;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class WalletController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $user = Auth::user();
        if (Auth::user()->engineer != null) {
            $entity = Auth::user()->engineer;
        } elseif (Auth::user()->firm != null) {
            $entity = Auth::user()->firm;
        } else {
            $entity = Auth::user();
        }
        $wallet = $entity->wallet;
        $billingAccounts=[];
        foreach ($entity->billingAccounts as $account){
            if(StripeClient::stripe()->accounts->retrieve($account->stripe_id)->external_accounts->total_count>0){
                $billingAccounts[]= StripeClient::stripe()->accounts->retrieve($account->stripe_id)->external_accounts->data[0];
            }
        }
//        dd($billingAccounts);
        $wallet->load([
            'owner' //=> ['billingAccounts'],
//            'payments' => ['fromWallet.owner', 'toWallet.owner'],
//            'payouts' => ['fromWallet.owner', 'toWallet.owner'],
        ]);
     // dd($wallet);
        $transactions= [];
        foreach ($wallet->payments as $payment){
            $payment->load(
                ['fromWallet.owner', 'toWallet.owner'],
            );
            $transactions[]=$payment;
        }
        foreach ($wallet->payouts as $payment){
            $payment->load(
                ['fromWallet.owner', 'toWallet.owner'],
            );
            $transactions[]=$payment;
        }
        usort($transactions, fn($a, $b) => strtotime($a->updated_at)- strtotime($b->updated_at));
        $transactions= array_reverse($transactions);

//        $transactions = Transaction::where('from',$wallet->id)->orWhere('to',$wallet->id)->orderBy('updated_at','desc')->get();
//        dd($transactions);

        return Inertia::render('Wallet/Index', [
            'user' => $user,
            'wallet' => $wallet,
            'activities' => $wallet->activities()
                ->whereDate('updated_at',Carbon::today())
                ->orderByDesc('created_at')->get(),
            'transactions' => $transactions,
            'accounts'=> $billingAccounts??[],
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Transaction $payment)
    {
        $user = Auth::user();
        if (Auth::user()->engineer != null) {
            $entity = Auth::user()->engineer;
        } elseif (Auth::user()->firm != null) {
            $entity = Auth::user()->firm;
        } else {
            $entity = Auth::user();
        }
        if ($payment->from != $entity->wallet->id && $payment->to != $entity->wallet->id){
            return redirect('/u/wallet')->with('error', 'You are not allowed to access this.');
        }
        $payout=null;
        $loadedData=[
            'fromWallet.owner.location',
            'toWallet.owner.location',
        ];
        if($payment->milestone !=null){
            $loadedData['milestone']= [ $payment->milestone->milestonable()->getModel() instanceof Proposal ?'milestonable.project':'milestonable.service', 'deliverables'];
        }
            $payment->load($loadedData);
        if($payment->stripe_id && $payment->type=="Payout") {
            $payout = StripeClient::stripe()->payouts->retrieve(
                $payment->stripe_id,
                [],
                ['stripe_account' => json_decode($payment->stripe_data)->metadata->account]
            );
            $payment->status= $payout->status;
            $payment->save();
        }


        return Inertia::render('Wallet/Payment/Index', [
            'payment'=>$payment,
            'payout'=>$payout,
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
