<?php

namespace App\Http\Controllers\Provider\Duitku;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use App\Models\Topup;

class DuitkuCallbackController extends Controller
{

    private $allowedIps = [
        '127.0.0.1',
        '182.23.85.8',
        '182.23.85.9',
        '182.23.85.10',
        '182.23.85.13',
        '182.23.85.14',
        '103.177.101.184',
        '103.177.101.185',
        '103.177.101.186',
        '103.177.101.189',
        '103.177.101.190',
        '182.23.85.11', 
        '182.23.85.12', 
        '103.177.101.187', 
        '103.177.101.188'
    ];

    public function handle(Request $request)
    {
        if (!$this->isValidIp($request->ip())) {
            Log::warning("Unauthorized Duitku callback attempt from IP: " . $request->ip());
            return response()->json(['success' => false, 'message' => 'Unauthorized IP'], 403);
        }
        
        $data = $request->all();
        
        $topupId = $data['merchantOrderId'] ?? null;
        $statusCode = $data['resultCode'] ?? null;
        $receivedSignature = $data['signature'] ?? null;
        $amount = $data['amount'] ?? null;
        
        if (!$topupId || !$statusCode || !$amount || !$receivedSignature) {
            return response()->json(['success' => false, 'message' => 'Incomplete callback data'], 400);
        }

        $calculatedSignature = md5(config('services.duitku.merchant') . $amount . $topupId . config('services.duitku.api_key'));
        if (strtolower($receivedSignature) !== strtolower($calculatedSignature)) {
            Log::warning("Invalid signature for topup: $topupId");
            return response()->json(['success' => false, 'message' => 'Invalid signature'], 401);
        }

        $topup = Topup::where('topup_id', $topupId)
            ->where('status', 'Pending')
            ->lockForUpdate()
            ->first();

        if (!$topup) {
            return response()->json(['success' => false, 'message' => "No pending topup found: $topupId"], 404);
        }

        switch ($statusCode) {
            case '00':
                $topup->update([
                    'status' => 'Paid',
                    'note' => 'Pembayaran Berhasil',
                    'paid_at' => now(),
                ]);

                  $user = $topup->user;
                  $balanceBefore = $user->balance;
                  $user->increment('balance', $topup->amount);
                  $balanceAfter = $balanceBefore + $topup->amount;

                  $user->walletLogs()->create([
                      'type'            => 'credit',
                      'source'          => 'otomatis',
                      'amount'          => $topup->amount,
                      'balance_before'  => $balanceBefore,
                      'balance_after'   => $balanceAfter,
                      'description'     => 'Topup via ' . $topup->paymentMethod->name,
                      'ref_id'          => $topup->topup_id,
                  ]);
                
                break;

            case '01':
            case '02':
                $topup->update([
                    'status' => $statusCode === '01' ? 'Failed' : 'Expired',
                ]);
                break;

            default:
                return response()->json(['success' => false, 'message' => 'Unknown statusCode'], 400);
        }

        return response()->json(['success' => true]);
    }
    
    private function isValidIp($ip)
    {
        return in_array($ip, $this->allowedIps);
    }
    
}