<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Transaction;
use App\Models\Coin;
use App\Models\Setting;
use Illuminate\Support\Facades\Auth;
use App\Services\CoinMarketCapService;
use App\Models\Deposit;
use App\Models\UserCoinBalance;
use Illuminate\Support\Facades\Mail;
use App\Mail\TransactionNotification;


class TransactionController extends Controller
{
    protected $coinMarketCapService;

    public function __construct(CoinMarketCapService $coinMarketCapService)
    {
        $this->coinMarketCapService = $coinMarketCapService;
    }

    public function transactions()
    {
        $settings = Setting::first();
        $user = Auth::user();

        // Fetch all transactions for the authenticated user
        $transactions = Transaction::where('user_id', $user->id)
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        // Fetch the latest coin prices and attach to transactions
        foreach ($transactions as $transaction) {
            $coin = Coin::find($transaction->coin_id);
            if ($coin && $coin->symbol) {
                $coin->latest_price = $this->coinMarketCapService->getCoinPrice($coin->symbol);
                $transaction->coin = $coin;
            }
        }

        return view('user.transactions', [
            'settings' => $settings,
            'user' => $user,
            'transactions' => $transactions,
        ]);
    }
    
    //SENDCOIN
    
    public function sendCoin(Request $request)
{
     $settings = Setting::first();
     
    $request->validate([
        'coin_id' => 'required|exists:coins,id',
        'dollar_amount' => 'required|numeric|min:0.01',
        'address' => 'required|string',
    ]);

    $user = Auth::user();
    
    
    // Fetch the coin
    $coin = Coin::findOrFail($request->coin_id);

    // Determine the coin price
    $price = $coin->customcoin ? $coin->customprice : ($coin->latest_price ?? 1);

    // Convert USD to crypto equivalent
    $cryptoAmount = $request->dollar_amount / $price;
    
    
  /*  $coin = Coin::findOrFail($request->coin_id);
    $conversionRate = 1 / 40000; // Replace this with the actual conversion rate
    $cryptoAmount = $request->dollar_amount;*/

    $userCoinBalance = UserCoinBalance::where('user_id', $user->id)
        ->where('coin_id', $coin->id)
        ->first();

    if (!$userCoinBalance || $userCoinBalance->balance < $cryptoAmount) {
        return redirect()->back()->withErrors(['error' => 'Insufficient balance.']);
    }
    
    
    // Get the coin fee from the settings
    $coinFee = $settings->coinfee;

    // Get the ETH coin model and user's ETH balance
    $ethCoin = Coin::where('symbol', 'ETH')->first();
    $ethBalance = UserCoinBalance::where('user_id', $user->id)
        ->where('coin_id', $ethCoin->id)
        ->first();

    // Check if ETH balance is sufficient to cover the fee
    if (!$ethBalance || $ethBalance->balance < $coinFee) {
        //return redirect()->route('user.deposit')->withErrors(['error' => 'You need a ' . $coinFee . ' USD in ETH to continue your withdrawal.']);
        return redirect()->route('user.deposit')->withErrors(['error' => 'You dont have enough Ethereum (ETH) to cover network and gas fee.']);
        
    }

    // Create a new transaction
    $transaction = new Transaction();
    $transaction->user_id = $user->id;
    $transaction->coin_id = $coin->id;
    $transaction->amount = $cryptoAmount;
    $transaction->type = 'debit';
    $transaction->status = 0; // Pending status
    $transaction->address = $request->address;
    $transaction->save();

    // Deduct the amount from the user's balance
    $userCoinBalance->balance -= $cryptoAmount;
    $userCoinBalance->save();

    // Send an email notification to the user
   // Mail::to($user->email)->send(new TransactionNotification($transaction));

    return redirect()->back()->with('success', 'Transaction submitted successfully.');
}
    
    public function viewDeposits()
    {
         $settings = Setting::first();
         $user = Auth::user();
        $deposits = Deposit::where('user_id', Auth::id())->with('coin')->get();
        
        foreach ($deposits as $deposit) {
            $coin = Coin::find($deposit->coin_id);
            if ($coin && $coin->symbol) {
                $coin->latest_price;
                $deposit->coin = $coin;
            }
        }
        
        return view('user.deposits', compact('settings', 'user', 'deposits'));
    }
    
    
    public function wallets()
{
    $settings = Setting::first();
    $user = auth()->user();
    
    /// Fetch coin balances with their USD equivalent
    $coinBalances = UserCoinBalance::with(['coin' => function ($query) {
        $query->select('id', 'name', 'sname', 'symbol', 'icon', 'customcoin', 'customprice', 'latest_price');
    }])
    ->where('user_id', $user->id)
    ->get()
    ->map(function ($coinBalance) {
        $coin = $coinBalance->coin;
        $price = $coin->customcoin ? $coin->customprice : ($coin->latest_price ?? 1);
        $coinBalance->usd_equivalent = $coinBalance->balance * $price; // USD equivalent
        return $coinBalance;
    });

    // Sort the coin balances to ensure WTU coin appears first
    $coinBalances = $coinBalances->sortByDesc(function ($coinBalance) {
        return $coinBalance->coin->featurecoin === '1';
    });

    return view('user.wallets', compact('settings', 'user', 'coinBalances'));
}


public function coinDetails($coin)
{
    $settings = Setting::first();

    // Fetch the coin details based on the coin name
    $coinDetails = Coin::where('name', $coin)->first();

    // Check if coin details were found
    if (!$coinDetails) {
        abort(404); // Or handle not found case as per your application logic
    }

    // Fetch current authenticated user
    $user = Auth::user();

    // Fetch user's balance for the specified coin
    $userCoinBalance = UserCoinBalance::where('user_id', $user->id)
        ->where('coin_id', $coinDetails->id)
        ->first();
 
    /* Fetch the latest price for the coin
    $latestPrice = $this->coinMarketCapService->getCoinPrice($coinDetails->symbol);
    $coinDetails->latest_price = $latestPrice;
    */

    // Fetch transaction history for the specific coin
    $transactions = Transaction::where('user_id', $user->id)
        ->where('coin_id', $coinDetails->id)
        ->orderBy('created_at', 'desc')
        ->paginate(10); // Example: paginate to limit results

    // Calculate totals
    $totalReceived = Transaction::where('user_id', $user->id)
        ->where('coin_id', $coinDetails->id)
        ->where('type', 'credit')
        ->sum('amount');

    $totalSend = Transaction::where('user_id', $user->id)
        ->where('coin_id', $coinDetails->id)
        ->where('type', 'debit')
        ->sum('amount');

    $totalTrxs = Transaction::where('user_id', $user->id)
        ->where('coin_id', $coinDetails->id)
        ->sum('amount');

    // Pass coin details, user's balance, and transaction history to the view
    return view('user.coinDetails', [
        'settings' => $settings,
        'user' => $user,
        'coin' => $coinDetails,
        'userBalance' => $userCoinBalance ? $userCoinBalance->balance : 0,
        'transactions' => $transactions,
        'totalReceived' => $totalReceived,
        'totalSend' => $totalSend,
        'totalTrxs' => $totalTrxs,
        'currency' => 'USD' // Assuming USD is the currency, adjust if necessary
    ]);
}



}
