<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Furkanmeclis\Paytr\Paytr;
use Illuminate\Support\Facades\Auth;

class PaymentController extends Controller
{
    public function index()
    {
        return view('payment.index');
    }

    public function pay(Request $request)
    {
        $user = Auth::user();
        $amount = $request->input('amount');
        $merchant_oid = uniqid();
        $user_basket = base64_encode(json_encode([
            ["Product 1", $amount, 1],
        ]));

        $paytr = new Paytr();
        $token = $paytr->getFrame([
            'merchant_oid' => $merchant_oid,
            'email' => $user->email,
            'payment_amount' => $amount * 100,
            'user_basket' => $user_basket,
            'user_name' => $user->name,
            'user_address' => 'Test Address',
            'user_phone' => '05555555555',
            'user_ip' => $request->ip(),
            'no_installment' => 1,
            'max_installment' => 1,
            'currency' => 'TL',
        ]);

        if (!$token['status']) {
            return redirect()->route('payment.index')->with('error', $token['message']);
        }

        return view('payment.iframe', ['token' => $token['token']]);
    }

    public function callback(Request $request)
    {
        $paytr = new Paytr();
        $callback = $paytr->callback($request);

        if (!$callback['status']) {
            return response($callback['message'], 400);
        }

        // Ödeme başarılıysa yapılacak işlemler
        // Örneğin: Siparişi güncelle, kullanıcı bakiyesini artır vb.

        return response('OK', 200);
    }
}
