<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\ApiService;
use Illuminate\Support\Facades\Log;

class BankAccountController extends Controller
{
    /**
     * API Service
     *
     * @var ApiService
     */
    protected $apiService;

    /**
     * Constructor
     *
     * @param ApiService $apiService
     */
    public function __construct(ApiService $apiService)
    {
        $this->apiService = $apiService;
    }

    /**
     * Display a listing of pending bank accounts.
     *
     * @return \Illuminate\Http\Response
     */
    public function pending()
    {
        try {
            // Gunakan endpoint yang benar sesuai dengan API
            $response = $this->apiService->get('admin/bank-accounts/pending');
            
            // Log API response untuk debugging
            \Log::debug('Bank Account Pending API Response:', [
                'url' => 'admin/bank-accounts/pending',
                'status' => $response->status(),
                'body' => $response->json()
            ]);
            
            if ($response->successful()) {
                $bankAccounts = $response->json()['data'] ?? [];
                return view('admin.bank-accounts.pending', compact('bankAccounts'));
            }
            
            // Jika response error 401, redirect ke login
            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }
            
            // Jika terjadi error lain
            return back()->with('error', 'Gagal memuat data akun bank: ' . ($response->json()['message'] ?? 'Unknown error'));
            
        } catch (\Exception $e) {
            \Log::error('Bank Account Pending Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return back()->with('error', 'Terjadi kesalahan saat memuat data akun bank');
        }
    }

    /**
     * Display a listing of verified bank accounts.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function verified(Request $request)
    {
        try {
            // Buat query parameters dari request
            $params = [];
            if ($request->has('status')) {
                $params['status'] = $request->status;
            }
            if ($request->has('search')) {
                $params['search'] = $request->search;
            }
            
            // Gunakan endpoint untuk mendapatkan akun bank yang sudah diverifikasi
            $response = $this->apiService->get('admin/bank-accounts/verified', $params);
            
            // Log API response untuk debugging
            \Log::debug('Bank Account Verified API Response:', [
                'url' => 'admin/bank-accounts/verified',
                'params' => $params,
                'status' => $response->status(),
                'body' => $response->json()
            ]);
            
            if ($response->successful()) {
                $bankAccounts = $response->json()['data'] ?? [];
                return view('admin.bank-accounts.verified', compact('bankAccounts'));
            }
            
            // Jika response error 401, redirect ke login
            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }
            
            // Jika terjadi error lain
            return back()->with('error', 'Gagal memuat data akun bank: ' . ($response->json()['message'] ?? 'Unknown error'));
            
        } catch (\Exception $e) {
            \Log::error('Bank Account Verified Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return back()->with('error', 'Terjadi kesalahan saat memuat data akun bank');
        }
    }

    /**
     * Display details of specific bank account with withdrawal history.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function detail($id)
    {
        try {
            // Gunakan endpoint untuk mendapatkan detail akun bank
            $response = $this->apiService->get("admin/bank-accounts/{$id}");
            
            // Log API response untuk debugging
            \Log::debug('Bank Account Detail API Response:', [
                'url' => "admin/bank-accounts/{$id}",
                'status' => $response->status(),
                'body' => $response->json()
            ]);
            
            if ($response->successful()) {
                $bankAccount = $response->json()['data'] ?? null;
                
                if ($bankAccount) {
                    return view('admin.bank-accounts.detail', compact('bankAccount'));
                }
            }
            
            // Jika response error 401, redirect ke login
            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }
            
            // Jika terjadi error lain
            return back()->with('error', 'Akun bank tidak ditemukan: ' . ($response->json()['message'] ?? 'Unknown error'));
            
        } catch (\Exception $e) {
            \Log::error('Bank Account Detail Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return back()->with('error', 'Terjadi kesalahan saat memuat data akun bank');
        }
    }

    /**
     * Show the form for verifying a bank account.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function showVerify($id)
    {
        try {
            // Gunakan data yang sudah ada dari daftar bank-accounts/pending
            // Karena API route untuk mengambil detail bank account sepertinya tidak tersedia
            $response = $this->apiService->get("admin/bank-accounts/pending");
            
            // Log API response untuk debugging
            \Log::debug('Bank Account Show Detail API Response:', [
                'url' => "admin/bank-accounts/pending",
                'status' => $response->status(),
                'body' => $response->json()
            ]);
            
            if ($response->successful()) {
                $bankAccounts = $response->json()['data'] ?? [];
                
                // Cari akun bank dengan ID yang sesuai
                $bankAccount = null;
                foreach ($bankAccounts as $account) {
                    if ($account['id'] == $id) {
                        $bankAccount = $account;
                        break;
                    }
                }
                
                if ($bankAccount) {
                    return view('admin.bank-accounts.verify', compact('bankAccount'));
                }
            }
            
            // Jika response error 401, redirect ke login
            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }
            
            // Jika terjadi error lain
            return redirect()->route('admin.bank-accounts.pending')
                ->with('error', 'Akun bank tidak ditemukan: ' . ($response->json()['message'] ?? 'Unknown error'));
            
        } catch (\Exception $e) {
            \Log::error('Bank Account Show Verify Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return redirect()->route('admin.bank-accounts.pending')
                ->with('error', 'Terjadi kesalahan saat memuat data akun bank');
        }
    }

    /**
     * Verify the specified bank account.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function verify(Request $request, $id)
    {
        try {
            // Validasi request
            $request->validate([
                'status' => 'required|in:active,rejected',
                'rejection_reason' => 'required_if:status,rejected',
            ]);
            
            $data = [
                'status' => $request->status,
                'rejection_reason' => $request->rejection_reason,
            ];
            
            // Pastikan path API sudah benar - gunakan /admin bukan /api/admin
            $response = $this->apiService->post("admin/bank-accounts/{$id}/verify", $data);
            
            // Log API response untuk debugging
            \Log::debug('Bank Account Verify API Response:', [
                'url' => "admin/bank-accounts/{$id}/verify",
                'data' => $data,
                'status' => $response->status(),
                'body' => $response->json()
            ]);
            
            if ($response->successful()) {
                return redirect()->route('admin.bank-accounts.pending')
                    ->with('success', 'Akun bank berhasil diverifikasi');
            }
            
            // Jika response error 401, redirect ke login
            if ($response->status() === 401) {
                return redirect()->route('admin.login')
                    ->with('error', 'Sesi anda telah berakhir. Silakan login kembali.');
            }
            
            // Jika terjadi error validasi
            if ($response->status() === 422) {
                return back()->withErrors($response->json()['data'] ?? [])
                    ->withInput();
            }
            
            // Jika terjadi error lain
            return back()->with('error', 'Gagal memverifikasi akun bank: ' . ($response->json()['message'] ?? 'Unknown error'))
                ->withInput();
            
        } catch (\Exception $e) {
            \Log::error('Bank Account Verify Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return back()->with('error', 'Terjadi kesalahan saat memverifikasi akun bank')
                ->withInput();
        }
    }
} 