<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\Payout;
use App\Models\PurchasePlan;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Support\Facades\Auth;

class TransactionController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
        $this->theme = template();
    }

    public function index(Request $request)
    {
        $search = $request->all();
        $dateSearch = Carbon::parse($request->created_at);
        $user = Auth::user();
        $data['transactions'] = Transaction::with(['transactional' => function (MorphTo $morphTo) {
            $morphTo->morphWith([
                PurchasePlan::class => ['user','deposit','gateway:id,code,name,image,driver,status'],
                Order::class => ['user','deposit','userGateway:id,code,name,image,driver,status'],
            ]);
        }])
            ->whereHasMorph('transactional',
                [
                    PurchasePlan::class,
                    Order::class,
                ], function ($query, $type) use ($user) {
                    if ($type == PurchasePlan::class || $type == Order::class) {
                        $query->where('user_id', $user->id);
                    }
                })
            ->where('user_id',$this->user->id)
            ->when(isset($search['trx_id']), function ($query) use ($search) {
                return $query->where('trx_id', 'LIKE', $search['trx_id']);
            })
            ->when(isset($search['created_at']), function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->when(isset($search['type']), function ($query) use ($search) {
                return $query->where('transactional_type', $search['type']);
            })
            ->latest()->paginate(basicControl()->paginate);

        return view(template() . 'user.transaction.index', $data);
    }

}
