<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\DepositAddress;
use App\Models\Deposit;

class DepositController extends Controller
{
    public function index(Request $request)
    {
        if (!$request->user()->hasVerifiedEmail()) {
            return redirect('/dashboard')->with([
                'message' => 'Please verify your email first',
                'type'    => 'error'
            ]);
        }

        $userId = Auth::id();
        $addresses = DepositAddress::where('user_id', $userId)->get();

        return view('deposit', [
            'page'      => 'Deposit',
            'addresses' => $addresses
        ]);
    }
    public function fetchHistory(Request $request)
    {
        if (!$request->ajax()) {
            return response()->json(['error' => 'Invalid request'], 400);
        }
        $perPage = 10;
        $query = Deposit::orderBy('created_at', 'desc')->where('user_id', Auth::id());
    
        $Deposit = $query->paginate($perPage);
    
        $records = $Deposit->map(function ($item) {
            return [
                'method' => $item->method,
                'status' => $this->getStatusLabel($item->status),
                'amount' => $item->amount,
                'txn_id' => $item->txn_id,
                'date' => $item->updated_at->diffForHumans(),
            ];
        });
    
        return response()->json([
            'records' => $records,
            'current_page' => $Deposit->currentPage(),
            'total_pages' => $Deposit->lastPage(),
            'prev_page' => $Deposit->previousPageUrl() ? $Deposit->currentPage() - 1 : null,
            'next_page' => $Deposit->nextPageUrl() ? $Deposit->currentPage() + 1 : null,
        ]);
    }
    private function getStatusLabel($status)
    {
        $statusLabels = [
            'pending' => ['text' => 'Pending', 'color' => 'warning'],
            'completed' => ['text' => 'Completed', 'color' => 'success'],
            'failed' => ['text' => 'Failed', 'color' => 'error'],
        ];
    
        return $statusLabels[$status] ?? ['text' => 'Unknown', 'color' => 'secondary'];
    }
}
