<?php

namespace App\Http\Controllers\Api;

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

class AdminWithdrawalController extends BaseController
{
    public function getPendingWithdrawals()
    {
        try {
            $withdrawals = Withdrawal::with(['wallet.user', 'bankAccount'])
                ->where('status', 'pending')
                ->latest()
                ->get();

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

    public function getPendingBankAccounts()
    {
        try {
            $pendingBankAccounts = BankAccount::with('user')
                ->where('status', 'pending')
                ->latest()
                ->get();

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

    public function processWithdrawal(Request $request, Withdrawal $withdrawal)
    {
        try {
            $validator = Validator::make($request->all(), [
                'status' => 'required|in:completed,rejected',
                'rejection_reason' => 'required_if:status,rejected|string|nullable',
                'proof_of_payment' => 'required_if:status,completed|file|image|max:2048'
            ]);

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

            // Pastikan status masih pending
            if ($withdrawal->status !== 'pending') {
                return $this->sendError('Error.', ['status' => ['Withdrawal sudah diproses sebelumnya']], 422);
            }

            if ($request->status === 'rejected') {
                // Kembalikan saldo ke wallet
                $withdrawal->wallet->addBalance(
                    $withdrawal->amount,
                    'Refund for rejected withdrawal #' . $withdrawal->id
                );

                $withdrawal->update([
                    'status' => 'rejected',
                    'rejection_reason' => $request->rejection_reason,
                    'processed_at' => now()
                ]);

                return $this->sendResponse($withdrawal, 'Withdrawal rejected successfully');
            } else {
                // Status completed
                if ($request->hasFile('proof_of_payment')) {
                    $path = $request->file('proof_of_payment')->store('proof_of_payments', 'public');

                    $withdrawal->update([
                        'status' => 'completed',
                        'rejection_reason' => null,
                        'proof_of_payment' => $path,
                        'processed_at' => now()
                    ]);

                    return $this->sendResponse($withdrawal, 'Withdrawal completed successfully');
                }
            }

            return $this->sendError('Error.', ['proof_of_payment' => ['Bukti pembayaran wajib diupload untuk status completed']], 422);
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => $e->getMessage()], 500);
        }
    }

    public function verifyBankAccount(Request $request, BankAccount $bankAccount)
    {
        try {
            $validator = Validator::make($request->all(), [
                'status' => 'required|in:active,rejected',
                'rejection_reason' => 'required_if:status,rejected|string|nullable'
            ]);

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

            $data = [
                'status' => $request->status,
                'verified_at' => now()
            ];

            // Hanya tambahkan rejection_reason jika status rejected
            if ($request->status === 'rejected') {
                $data['rejection_reason'] = $request->rejection_reason;
            } else {
                $data['rejection_reason'] = null; // Set null ketika status active
            }

            $bankAccount->update($data);

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

    public function getVerifiedBankAccounts(Request $request)
    {
        try {
            $query = BankAccount::with('user')
                ->whereIn('status', ['active', 'rejected'])
                ->where('verified_at', '!=', null);

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

            // Filter berdasarkan pencarian nama pengguna atau nomor rekening
            if ($request->has('search')) {
                $search = $request->search;
                $query->whereHas('user', function($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%");
                })->orWhere('account_number', 'like', "%{$search}%")
                  ->orWhere('account_holder_name', 'like', "%{$search}%")
                  ->orWhere('bank_name', 'like', "%{$search}%");
            }

            $verifiedBankAccounts = $query->latest('verified_at')->get();

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

    public function getWithdrawalHistory(Request $request)
    {
        try {
            $query = Withdrawal::with(['wallet.user', 'bankAccount'])
                ->whereIn('status', ['completed', 'rejected']);

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

            // Filter berdasarkan pencarian nama pengguna, nomor rekening atau bank
            if ($request->has('search')) {
                $search = $request->search;
                $query->whereHas('wallet.user', function($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%");
                })->orWhereHas('bankAccount', function($q) use ($search) {
                    $q->where('account_number', 'like', "%{$search}%")
                      ->orWhere('account_holder_name', 'like', "%{$search}%")
                      ->orWhere('bank_name', 'like', "%{$search}%");
                });
            }

            // Filter berdasarkan periode tanggal
            if ($request->has('from_date')) {
                $query->whereDate('created_at', '>=', $request->from_date);
            }

            if ($request->has('to_date')) {
                $query->whereDate('created_at', '<=', $request->to_date);
            }

            // Pengurutan
            $sortBy = $request->get('sort_by', 'processed_at');
            $sortOrder = $request->get('sort_order', 'desc');

            if (in_array($sortBy, ['created_at', 'amount', 'processed_at'])) {
                $query->orderBy($sortBy, $sortOrder);
            }

            // Paginasi hasil
            $perPage = $request->get('per_page', 15);
            $withdrawals = $query->paginate($perPage);

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

    public function getBankAccountDetail(BankAccount $bankAccount)
    {
        try {
            // Load user dan riwayat withdrawal
            $bankAccount->load(['user', 'withdrawals']);

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