<?php

namespace App\Http\Controllers\Api\OLDLMS;

use App\Http\Controllers\Controller;
use App\Models\Member;
use App\Services\Duitku;
use Illuminate\Http\Request;
use Str;

class PaymentController extends Controller
{
    public function postponePay($memberId) 
    {
        $member = Member::where('member_id', $memberId)->with('postponedClaims')->firstOrFail();

        $totalBill = $member->postponedClaims->sum('total_claim');

        $config_duitku = [
            'merchant_code' =>  env('DUITKU_MERCHANT_CODE'),
            'merchant_key' =>  env('DUITKU_MERCHANT_KEY'),
        ];
        $paymentService = new Duitku($config_duitku);
        
        $invoice = (object) [
            'invoice_number' => 'INV'.Str::random(5, 5),
        ];
        
        $user = (object) [
            'email' => $member->email,
            'phone' => $member->phone,
            'name' => $member->name,
            'last_name' => $member->last_name ?? '',
            'address' => collect([
                'line' => 'Alamat',
                'city' => (object) [
                    'name' => 'Tangerang Selatan'
                ]
                ]),
            'postal_code' => '124123',
        ];

        $paymentCreate = (object) [
            'transaction_id' => Str::random(10, 10)
        ];
        $paymentMethod = (object) [
            'code' => 'BC',
            'timeout' => 60
        ];
        $paymentService->applyInvoice($user, $invoice, $paymentCreate,  $totalBill, $paymentMethod);
        $duitkuPayment = $paymentService->createPayment();

        return redirect($duitkuPayment->paymentUrl);
    }
}
