<?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 WithdrawalController 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 withdrawals.
     *
     * @return \Illuminate\Http\Response
     */
    public function pending()
    {
        try {
            $response = $this->apiService->get('admin/withdrawals/pending');
            
            if ($response->successful()) {
                $withdrawals = $response->json()['data'] ?? [];
                return view('admin.withdrawals.pending', compact('withdrawals'));
            }
            
            // 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 penarikan: ' . ($response->json()['message'] ?? 'Unknown error'));
            
        } catch (\Exception $e) {
            Log::error('Withdrawal Pending Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return back()->with('error', 'Terjadi kesalahan saat memuat data penarikan');
        }
    }

    /**
     * Display a listing of processed withdrawals history.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function history(Request $request)
    {
        try {
            // Siapkan query parameters
            $query = [];
            
            // Filter berdasarkan status
            if ($request->filled('status')) {
                $query['status'] = $request->status;
            }
            
            // Pencarian
            if ($request->filled('search')) {
                $query['search'] = $request->search;
            }
            
            // Filter rentang tanggal
            if ($request->filled('from_date')) {
                $query['from_date'] = $request->from_date;
            }
            
            if ($request->filled('to_date')) {
                $query['to_date'] = $request->to_date;
            }
            
            // Pengurutan
            if ($request->filled('sort_by')) {
                $query['sort_by'] = $request->sort_by;
            }
            
            if ($request->filled('sort_order')) {
                $query['sort_order'] = $request->sort_order;
            }
            
            // Paginasi
            if ($request->filled('per_page')) {
                $query['per_page'] = $request->per_page;
            }
            
            // Halaman saat ini
            if ($request->filled('page')) {
                $query['page'] = $request->page;
            }
            
            $response = $this->apiService->get('admin/withdrawals/history', $query);
            
            if ($response->successful()) {
                $withdrawalHistory = $response->json()['data'] ?? [];
                return view('admin.withdrawals.history', compact('withdrawalHistory'));
            }
            
            // 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 riwayat penarikan: ' . ($response->json()['message'] ?? 'Unknown error'));
            
        } catch (\Exception $e) {
            Log::error('Withdrawal History Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return back()->with('error', 'Terjadi kesalahan saat memuat riwayat penarikan');
        }
    }

    /**
     * Show the form for processing a withdrawal.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function showProcess($id)
    {
        try {
            // Ambil semua data withdrawal pending
            $response = $this->apiService->get('admin/withdrawals/pending');
            
            if ($response->successful()) {
                $withdrawals = $response->json()['data'] ?? [];
                
                // Cari withdrawal dengan ID yang sesuai
                $withdrawal = null;
                foreach ($withdrawals as $item) {
                    if ($item['id'] == $id) {
                        $withdrawal = $item;
                        break;
                    }
                }
                
                if ($withdrawal) {
                    return view('admin.withdrawals.process', compact('withdrawal'));
                }
                
                // Jika tidak ditemukan
                return redirect()->route('admin.withdrawals.pending')
                    ->with('error', 'Penarikan dengan ID tersebut tidak ditemukan');
            }
            
            // 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.withdrawals.pending')
                ->with('error', 'Gagal memuat data penarikan: ' . ($response->json()['message'] ?? 'Unknown error'));
            
        } catch (\Exception $e) {
            Log::error('Withdrawal Show Process Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return redirect()->route('admin.withdrawals.pending')
                ->with('error', 'Terjadi kesalahan saat memuat data penarikan');
        }
    }

    /**
     * Process the specified withdrawal request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function process(Request $request, $id)
    {
        try {
            // Validasi request sesuai dengan API yang diupdate
            $request->validate([
                'status' => 'required|in:completed,rejected',
                'rejection_reason' => 'required_if:status,rejected',
                'proof_of_payment' => 'required_if:status,completed|file|mimes:jpeg,png,jpg,pdf|max:2048',
            ]);
            
            // Persiapkan data untuk API
            $data = [
                'status' => $request->status,
                'rejection_reason' => $request->rejection_reason,
            ];
            
            // Siapkan file bukti pembayaran jika ada
            if ($request->status === 'completed' && $request->hasFile('proof_of_payment')) {
                $response = $this->apiService->post("admin/withdrawals/{$id}/process", $data, [
                    'proof_of_payment' => $request->file('proof_of_payment')
                ]);
            } else {
                $response = $this->apiService->post("admin/withdrawals/{$id}/process", $data);
            }
            
            if ($response->successful()) {
                $statusMessage = $request->status === 'completed' ? 'diselesaikan' : 'ditolak';
                return redirect()->route('admin.withdrawals.pending')
                    ->with('success', "Penarikan berhasil {$statusMessage}");
            }
            
            // 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 memproses penarikan: ' . ($response->json()['message'] ?? 'Unknown error'))
                ->withInput();
            
        } catch (\Exception $e) {
            Log::error('Withdrawal Process Error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return back()->with('error', 'Terjadi kesalahan saat memproses penarikan')
                ->withInput();
        }
    }
} 