<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Wallet;
use App\Models\BankAccount;
use App\Models\Withdrawal;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class WalletController extends BaseController
{
    public function getWallet()
    {
        try {
            $wallet = Auth::user()->wallet;
            if (!$wallet) {
                $wallet = Wallet::create([
                    'user_id' => Auth::id(),
                    'balance' => 0
                ]);
            }

            // Menghitung total pending withdrawals
            $pendingWithdrawals = Withdrawal::where('wallet_id', $wallet->id)
                ->whereIn('status', ['pending', 'processing'])
                ->sum('amount');

            // Menghitung saldo yang tersedia
            $availableBalance = $wallet->balance - $pendingWithdrawals;

            return $this->sendResponse([
                'balance' => $wallet->balance,
                'pending_withdrawals' => $pendingWithdrawals,
                'available_balance' => $availableBalance,
                'transactions' => $wallet->transactions()->with('booking')->latest()->get()
            ], 'Wallet information retrieved successfully');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => $e->getMessage()], 500);
        }
    }

    public function registerBankAccount(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'bank_name' => 'required|string',
                'account_number' => 'required|string',
                'account_holder_name' => 'required|string'
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 422);
            }

            $bankAccount = BankAccount::create([
                'user_id' => Auth::id(),
                'bank_name' => $request->bank_name,
                'account_number' => $request->account_number,
                'account_holder_name' => $request->account_holder_name,
                'status' => 'pending'
            ]);

            return $this->sendResponse($bankAccount, 'Bank account registered successfully');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => $e->getMessage()], 500);
        }
    }

    public function requestWithdrawal(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'bank_account_id' => 'required|exists:bank_accounts,id',
                'amount' => 'required|numeric|min:10000'
            ]);

            if ($validator->fails()) {
                return $this->sendError('Validation Error.', $validator->errors(), 422);
            }

            $wallet = Auth::user()->wallet;
            if (!$wallet) {
                return $this->sendError('Wallet not found.', [], 404);
            }

            // Validasi saldo yang tersedia
            if ($wallet->balance < $request->amount) {
                return $this->sendError('Insufficient balance.', [
                    'balance' => $wallet->balance,
                    'requested_amount' => $request->amount
                ], 422);
            }

            $bankAccount = BankAccount::find($request->bank_account_id);
            if ($bankAccount->status !== 'active') {
                return $this->sendError('Invalid bank account.', [], 422);
            }

            // Kurangi saldo wallet
            $wallet->deductBalance(
                $request->amount,
                'Withdrawal request #' . time()
            );

            $withdrawal = Withdrawal::create([
                'wallet_id' => $wallet->id,
                'bank_account_id' => $bankAccount->id,
                'amount' => $request->amount,
                'status' => 'pending'
            ]);

            return $this->sendResponse([
                'withdrawal' => $withdrawal,
                'wallet' => [
                    'balance' => $wallet->balance,
                    'pending_withdrawals' => $request->amount,
                    'available_balance' => $wallet->balance
                ]
            ], 'Withdrawal request submitted successfully');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => $e->getMessage()], 500);
        }
    }

    public function getWithdrawalHistory(Request $request)
    {
        try {
            $wallet = Auth::user()->wallet;
            if (!$wallet) {
                return $this->sendResponse([], 'No withdrawal history found');
            }

            $query = $wallet->withdrawals()->with('bankAccount');

            // Filter berdasarkan status jika parameter status ada
            if ($request->has('status') && in_array($request->status, ['pending', 'processing', 'completed', 'rejected'])) {
                $query->where('status', $request->status);
            }

            $withdrawals = $query->latest()->get();

            return $this->sendResponse($withdrawals, 'Withdrawal history retrieved successfully');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => $e->getMessage()], 500);
        }
    }

    public function getBankAccounts()
    {
        try {
            $bankAccounts = Auth::user()->bankAccounts()
                ->orderBy('created_at', 'desc')
                ->get();

            return $this->sendResponse($bankAccounts, 'Bank accounts retrieved successfully');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => $e->getMessage()], 500);
        }
    }
}
