<?php

namespace App\Http\Controllers;

use App\Facades\Cart;
use App\Models\Order;
use App\Models\Wallet;
use App\Models\Payment;
use Illuminate\Http\Request;
use Shetabit\Multipay\Invoice;
use App\Enums\PaymentStatusEnum;
use App\Services\Models\OrderService;
use Illuminate\Container\Attributes\Auth;
use Shetabit\Payment\Facade\Payment as shetabitPayment;

class PaymentController extends Controller
{
    public function show($uuid)
    {
        $payment = Payment::uuid($uuid);

        $is_mobile = false;
        return view('pages.payment', compact('payment', 'is_mobile'));
    }

    public function create(Request $request)
    {

        if (isset($request->uuid) && isset($request->tracking_code)) {
            $payable = Order::where('uuid', $request->uuid)->where('tracking_code', $request->tracking_code)->first();
        }

        if (isset($payable)) {
            $isOrder = $payable instanceof Order;
        } else {
            $payable = OrderService::createOrder(
                purchaser: $request->user(),
                purchasable: $request->user()->wallet,
                data: [
                    'amount' => $request->amount,
                    'description' => $request->description,
                ]
            );
            $isOrder = true;
        }



        $payment = Payment::create([
            'user_id' => auth()->user()->id,
            'payed_by_type' => $isOrder ? $payable->ordered_by_type : get_class($request->user()),
            'payed_by_id' => $isOrder ? $payable->ordered_by_id : $request->user()->id,
            'payable_type' => get_class($payable),
            'payable_id' => $payable->id,
            // 'gateway' => PaymentService::{$request->gateway}()::class,
            'status' => PaymentStatusEnum::Awaiting,
            'amount' => $isOrder ? $payable->amount : $request->amount,
            'data' => $request->description ? json_encode(['description' => $request->description]) : null
        ]);

        return redirect()->route('payment', ['uuid' => $payment->uuid]);
    }

    public function pay(Request $request, $uuid)
    {
        $payment = Payment::uuid($uuid);


        $invoice = (new Invoice)->amount($payment->amount);
        $invoice->uuid($payment->uuid);
        $invoice->detail(['factorId' => $payment->tracking_code]);

        return ShetabitPayment::purchase($invoice, function ($driver, $transactionId) use ($payment) {
            $payment->update(['transaction_id' => $transactionId]);
        })->pay()->render();
    }
}
