<?php

namespace App\Http\Controllers\Api\V1\Customer;

use App\Http\Controllers\Controller;
use App\Models\AffiliateCommission;
use App\Models\WithdrawalRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AffiliateController extends Controller
{
    public function withdraw(Request $request)
    {
        $request->validate([
            'bank_name' => 'required|string|max:255',
            'account_number' => 'required|string|max:255',
            'account_name' => 'required|string|max:255',
        ]);

        $user = auth()->user();

        // Calculate available commission
        $availableAmount = AffiliateCommission::where('affiliate_user_id', $user->id)
            ->where('status', 'approved')
            ->whereNull('withdrawal_request_id')
            ->sum('commission_amount');

        if ($availableAmount <= 0) {
            return response()->json([
                'success' => false,
                'message' => 'Anda tidak memiliki komisi yang disetujui untuk ditarik.'
            ], 422);
        }

        return DB::transaction(function () use ($request, $user, $availableAmount) {
            $withdrawal = WithdrawalRequest::create([
                'user_id' => $user->id,
                'amount' => $availableAmount,
                'bank_name' => $request->bank_name,
                'account_number' => $request->account_number,
                'account_name' => $request->account_name,
                'status' => 'pending'
            ]);

            // Link those commissions to this withdrawal request
            AffiliateCommission::where('affiliate_user_id', $user->id)
                ->where('status', 'approved')
                ->whereNull('withdrawal_request_id')
                ->update(['withdrawal_request_id' => $withdrawal->id]);

            return response()->json([
                'success' => true,
                'message' => 'Permintaan penarikan komisi sebesar Rp ' . number_format($availableAmount, 0, ',', '.') . ' berhasil diajukan.',
                'withdrawal' => $withdrawal
            ]);
        });
    }

    public function updateBankDetails(Request $request)
    {
        $request->validate([
            'bank_name' => 'required|string|max:255',
            'bank_account_number' => 'required|string|max:255',
            'bank_account_name' => 'required|string|max:255',
        ]);

        $user = auth()->user();
        $user->update([
            'bank_name' => $request->bank_name,
            'bank_account_number' => $request->bank_account_number,
            'bank_account_name' => $request->bank_account_name,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Catatan rekening bank berhasil disimpan.',
            'user' => $user
        ]);
    }
}
