<?php

namespace App\Http\Controllers;

use App\Models\Deposit;
use App\Models\Gateway;
use App\Models\GeneralSetting;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Models\UserInterest;
use Auth;

class DepositController extends Controller
{
    public function __construct()
    {
        $general = GeneralSetting::first();
        $this->template = $general->theme == 1 ? 'frontend.' : "theme{$general->theme}.";
    }

    public function deposit()
    {
        $apiUrl = 'https://ccore.theincprocessor.xyz/api/gateways';

        try {
            $user = auth()->user(); // Ensure user is authenticated

            $token = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($user); // Generate JWT token

            $client = new \GuzzleHttp\Client();
            $response = $client->get($apiUrl, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $token,
                    'Accept' => 'application/json',
                ],
            ]);

//            dd($response);

            $gateways = json_decode($response->getBody(), true)['data'];
//            dd($gateways);
            $pageTitle = "Payment Methods";
            $type = 'deposit';
            $profit = UserInterest::where('user_id', Auth::id())->sum('interest_amount');
$userinterestLogs = UserInterest::where('user_id', Auth::id())->get();

            return view($this->template . "user.gateway.gateways", compact('gateways', 'pageTitle', 'profit', 'type'));

        } catch (\Exception $e) {
//            dd('Error: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Failed to fetch gateways: ' . $e->getMessage());

        }

    }


      public function depositLog(Request $request)
    {
        $pageTitle = "Transactions";
$profit = UserInterest::where('user_id', Auth::id())->sum('interest_amount');
$userinterestLogs = UserInterest::where('user_id', Auth::id())->get();        
        // dd('ss');

        $transactions = Deposit::when($request->trx , function($item)use($request){ $item->where('transaction_id', $request->trx);})->
        when($request->date, function($item) use($request) {$item->whereDate('created_at', $request->date);})->where('user_id', auth()->id())->latest()->with('user')->whereIn('payment_status', [1, 2])->paginate();

        return view($this->template.'user.deposit_log', compact('pageTitle', 'profit', 'transactions'));
    }
}
