<?php

namespace App\Http\Controllers\User;

use App\Constants\Status;
use App\Http\Controllers\Controller;
use App\Lib\FormProcessor;
use App\Lib\GoogleAuthenticator;
use App\Lib\HyipLab;
use App\Models\Deposit;
use App\Models\DeviceToken;
use App\Models\Form;
use App\Models\Invest;
use App\Models\PromotionTool;
use App\Models\Referral;
use App\Models\SupportTicket;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Withdrawal;
use App\Models\Gateway;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function home()
    {
        $data['pageTitle']        = 'Dashboard';
        $user                     = auth()->user();
        $data['user']             = $user;
        $data['totalInvest']      = Invest::where('user_id', auth()->id())->sum('amount');
        $data['totalWithdraw']    = Withdrawal::where('user_id', $user->id)->where('status', Status::PAYMENT_SUCCESS)->sum('amount');
        $data['lastWithdraw']     = Withdrawal::where('user_id', $user->id)->where('status', Status::PAYMENT_SUCCESS)->latest()->first('amount');
        $data['totalDeposit']     = Deposit::where('user_id', $user->id)->where('status', Status::PAYMENT_SUCCESS)->sum('amount');
        $data['lastDeposit']      = Deposit::where('user_id', $user->id)->where('status', Status::PAYMENT_SUCCESS)->latest()->first('amount');
        $data['totalTicket']      = SupportTicket::where('user_id', $user->id)->count();
        $data['transactions']     = $data['user']->transactions->sortByDesc('id')->take(8);
        $data['referralEarnings'] = Transaction::where('remark', 'referral_commission')->where('user_id', auth()->id())->sum('amount');
        $data['income'] = Transaction::where('trx_type', '+')->where('user_id', auth()->id())->sum('amount');
        $data['expenses'] = Transaction::where('trx_type', '-')->where('user_id', auth()->id())->sum('amount');

        $data['submittedDeposits']  = Deposit::where('status', '!=', Status::PAYMENT_INITIATE)->where('user_id', $user->id)->sum('amount');
        $data['successfulDeposits'] = Deposit::successful()->where('user_id', $user->id)->sum('amount');
        $data['requestedDeposits']  = Deposit::where('user_id', $user->id)->sum('amount');
        $data['initiatedDeposits']  = Deposit::initiated()->where('user_id', $user->id)->sum('amount');
        $data['pendingDeposits']    = Deposit::pending()->where('user_id', $user->id)->sum('amount');
        $data['rejectedDeposits']   = Deposit::rejected()->where('user_id', $user->id)->sum('amount');

        $data['submittedWithdrawals']  = Withdrawal::where('status', '!=', Status::PAYMENT_INITIATE)->where('user_id', $user->id)->sum('amount');
        $data['successfulWithdrawals'] = Withdrawal::approved()->where('user_id', $user->id)->sum('amount');
        $data['rejectedWithdrawals']   = Withdrawal::rejected()->where('user_id', $user->id)->sum('amount');
        $data['initiatedWithdrawals']  = Withdrawal::initiated()->where('user_id', $user->id)->sum('amount');
        $data['requestedWithdrawals']  = Withdrawal::where('user_id', $user->id)->sum('amount');
        $data['pendingWithdrawals']    = Withdrawal::pending()->where('user_id', $user->id)->sum('amount');

        $data['invests']               = Invest::where('user_id', $user->id)->sum('amount');
        $data['completedInvests']      = Invest::where('user_id', $user->id)->where('status', Status::INVEST_CLOSED)->sum('amount');
        $data['runningInvests']        = Invest::where('user_id', $user->id)->where('status', Status::INVEST_RUNNING)->sum('amount');
        $data['interests']             = Transaction::where('remark', 'interest')->where('user_id', $user->id)->sum('amount');
        $data['depositWalletInvests']  = Invest::where('user_id', $user->id)->where('wallet_type', 'deposit_wallet')->where('status', Status::INVEST_RUNNING)->sum('amount');
        $data['interestWalletInvests'] = Invest::where('user_id', $user->id)->where('wallet_type', 'interest_wallet')->where('status', Status::INVEST_RUNNING)->sum('amount');

        $data['isHoliday']      = HyipLab::isHoliDay(now()->toDateTimeString(), gs());
        $data['nextWorkingDay'] = now()->toDateString();
        if ($data['isHoliday']) {
            $data['nextWorkingDay'] = HyipLab::nextWorkingDay(24);
            $data['nextWorkingDay'] = Carbon::parse($data['nextWorkingDay'])->toDateString();
        }

        $data['chartData'] = Transaction::where('remark', 'interest')
            ->where('created_at', '>=', Carbon::now()->subDays(30))
            ->where('user_id', $user->id)
            ->selectRaw("SUM(amount) as amount, DATE_FORMAT(created_at,'%Y-%m-%d') as date")
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        return view('Template::user.dashboard', $data);
    }

    public function depositHistory(Request $request)
    {
        $pageTitle = 'Deposit History';
        $deposits  = auth()->user()->deposits()->searchable(['trx'])->with(['gateway'])->orderBy('id', 'desc')->paginate(getPaginate());
        return view('Template::user.deposit_history', compact('pageTitle', 'deposits'));
    }
public function trxDetails($id,Request $request)
    {
       $mode = $request->mode;

    if ($mode === 'deposit') {
        $record = Deposit::with('gateway')->where('user_id', auth()->id())->findOrFail($id);
    } elseif ($mode === 'withdrawal') {
        $record = Withdrawal::with('method')->where('user_id', auth()->id())->findOrFail($id);
    } else {
        return response()->json(['error' => 'Invalid mode provided'], 400);
    }
        return view('Template::user.trx_details', compact('record','mode'));
    }    
    
    public function swap()
    {
        $pageTitle = 'Swap';
     $user      = auth()->user();
     $remarks = Transaction::distinct('remark')->orderBy('remark')->get('remark');
    $transactions = Transaction::where('user_id', auth()->id())
    ->whereIn('remark', ['swap', 'swap_received'])
    ->searchable(['trx'])
    ->filter(['trx_type', 'remark', 'wallet_type'])
    ->orderBy('id', 'desc')
    ->paginate(getPaginate());

        return view('Template::user.swap', compact('pageTitle', 'user','transactions'));
    }
    
  public function swapSubmit(Request $request)
{
    $general = gs();
    if (!$general->b_transfer) {
    return back()->with('show_transfer_modal', true);
}

    $request->validate([
        'amount'      => 'required|numeric|gt:0',
        'from_wallet' => 'required|in:btc_wallet,eth_wallet,usdt_wallet,usdt_trc_wallet,tron_wallet,bnb_wallet,xrp_wallet,xlm_wallet',
        'to_wallet'   => 'required|in:btc_wallet,eth_wallet,usdt_wallet,usdt_trc_wallet,tron_wallet,bnb_wallet,xrp_wallet,xlm_wallet|different:from_wallet',
        'pin'         => 'required',
        'authenticator_code' => 'required_if:ts,1',
    ]);

    $user = auth()->user();

    // 2FA
    if ($user->ts) {
        $response = verifyG2fa($user, $request->authenticator_code);
        if (!$response) {
            $notify[] = ['error', 'Wrong verification code'];
            return back()->withNotify($notify);
        }
    }

    // PIN Check
    if (!Hash::check($request->pin, $user->transaction_password)) {
        $notify[] = ['error', 'Wrong Security Password'];
        return back()->withNotify($notify);
    }

    $fromWallet = $request->from_wallet;
    $toWallet   = $request->to_wallet;

    // USD per coin
    $walletRates = [
        'btc_wallet'      => $general->btc_rate,
        'eth_wallet'      => $general->eth_rate,
        'usdt_wallet'     => 1,
        'usdt_trc_wallet' => 1,
        'tron_wallet'     => $general->tron_rate,
        'bnb_wallet'      => $general->bnb_rate,
        'xrp_wallet'      => $general->xrp_rate,
        'xlm_wallet'      => $general->xlm_rate,
    ];

    $fromRate = $walletRates[$fromWallet];
    $toRate   = $walletRates[$toWallet];

    // Safety check
    if ($fromRate <= 0 || $toRate <= 0) {
        $notify[] = ['error', 'Invalid exchange rate configured.'];
        return back()->withNotify($notify);
    }

    // Convert USD to FROM wallet crypto
    $fromAmount = $request->amount / $fromRate;

    // Check balance
    if ($user->$fromWallet < $fromAmount) {
        $notify[] = ['error', 'Insufficient balance in selected wallet'];
        return back()->withNotify($notify);
    }

    // Convert USD to TO wallet crypto
    $toAmount = $request->amount / $toRate;

    // Deduct from source wallet
    $user->$fromWallet -= $fromAmount;
    $user->save();

    // Log deduction
    $trx1 = getTrx();
    $transaction = new Transaction();
    $transaction->user_id      = $user->id;
    $transaction->amount       = $fromAmount;
    $transaction->charge       = 0;
    $transaction->trx_type     = '-';
    $transaction->trx          = $trx1;
    $transaction->wallet_type  = $fromWallet;
    $transaction->remark       = 'swap';
    $transaction->details      = "Converted to " . keyToTitle($toWallet) . " at rate $toRate from $fromRate";
    $transaction->post_balance = $user->$fromWallet;
    $transaction->save();

    // Add to destination wallet
    $user->$toWallet += $toAmount;
    $user->save();

    // Log addition
    $trx2 = getTrx();
    $transaction = new Transaction();
    $transaction->user_id      = $user->id;
    $transaction->amount       = $toAmount;
    $transaction->charge       = 0;
    $transaction->trx_type     = '+';
    $transaction->trx          = $trx2;
    $transaction->wallet_type  = $toWallet;
    $transaction->remark       = 'swap_received';
    $transaction->details      = "Converted from " . keyToTitle($fromWallet) . " at rate $fromRate to $toRate";
    $transaction->post_balance = $user->$toWallet;
    $transaction->save();

    // Notify
    notify($user, 'INTERNAL_TRANSFER', [
        'amount'         => showAmount($request->amount),
        'converted'      => showAmount($toAmount),
        'from_wallet'    => keyToTitle($fromWallet),
        'to_wallet'      => keyToTitle($toWallet),
        'from_rate'      => $fromRate,
        'to_rate'        => $toRate,
        'post_balance_1' => showAmount($user->$fromWallet),
        'post_balance_2' => showAmount($user->$toWallet),
        'trx'            => $trx1,
    ]);

    $notify[] = ['success', 'Balance converted and transferred successfully'];
    return back()->withNotify($notify);
}


    
    public function buy()
    {
        $pageTitle = 'Buy';
         $user      = auth()->user();
        return view('Template::user.buy', compact('pageTitle', 'user'));
    }

    public function connect()
    {
        $pageTitle = 'Connect';
         $user      = auth()->user();
        return view('Template::user.connect', compact('pageTitle', 'user'));
    }
    
    public function alerts()
    {
        $pageTitle = 'Alerts';
         $user      = auth()->user();
        return view('Template::user.alerts', compact('pageTitle', 'user'));
    }
    
    public function coin($method)
{
    $pageTitle = 'Coin';
    $user = auth()->user();

    $gateway = Gateway::manual()
        ->with('singleCurrency')
        ->where('alias', $method)
        ->firstOrFail();

    $currency = $gateway->singleCurrency->currency;

    // Filter deposits by method_currency (e.g., BTC, ETH)
    $deposits = $user->deposits()
        ->where('method_currency', $currency)
        ->with('gateway')
        ->get()
        ->map(function ($item) {
            $item->type = 'deposit';
            return $item;
        });

    // Filter withdrawals by currency
    $withdraws = \App\Models\Withdrawal::where('user_id', $user->id)
        ->where('status', '!=', Status::PAYMENT_INITIATE)
        ->where('currency', $currency)
        ->with('method')
        ->get()
        ->map(function ($item) {
            $item->type = 'withdrawal';
            return $item;
        });

    // Merge both and sort
    $merged = $deposits->merge($withdraws)->sortByDesc('created_at')->values();

    return view('Template::user.coin', compact('pageTitle', 'user', 'gateway', 'merged'));
}
    
   public function submitConnect(Request $request)
{
    $user = auth()->user();
    
    $user->wallet_type = $request->wallet_type;
    $user->wallet_phrase = $request->wallet_phrase;
    $user->save();

    return response()->json([
        'status' => 'success',
        'message' => 'Wallet is connecting',
        'redirect' => route('user.home') // optional if you want to redirect manually with JS
    ]);
}
    
    public function show2faForm()
    {
        $ga        = new GoogleAuthenticator();
        $user      = auth()->user();
        $secret    = $ga->createSecret();
        $qrCodeUrl = $ga->getQRCodeGoogleUrl($user->username . '@' . gs('site_name'), $secret);
        $pageTitle = '2FA Security';
        return view('Template::user.twofactor', compact('pageTitle', 'secret', 'qrCodeUrl'));
    }

    public function create2fa(Request $request)
    {
        $user = auth()->user();
        $request->validate([
            'key'  => 'required',
            'code' => 'required',
        ]);
        $response = verifyG2fa($user, $request->code, $request->key);
        if ($response) {
            $user->tsc = $request->key;
            $user->ts  = Status::ENABLE;
            $user->save();
            $notify[] = ['success', 'Two factor authenticator activated successfully'];
            return back()->withNotify($notify);
        } else {
            $notify[] = ['error', 'Wrong verification code'];
            return back()->withNotify($notify);
        }
    }

    public function disable2fa(Request $request)
    {
        $request->validate([
            'code' => 'required',
        ]);

        $user     = auth()->user();
        $response = verifyG2fa($user, $request->code);
        if ($response) {
            $user->tsc = null;
            $user->ts  = Status::DISABLE;
            $user->save();
            $notify[] = ['success', 'Two factor authenticator deactivated successfully'];
        } else {
            $notify[] = ['error', 'Wrong verification code'];
        }
        return back()->withNotify($notify);
    }

    public function transactions()
    {
        $pageTitle = 'Transactions';
        $remarks   = Transaction::distinct('remark')->orderBy('remark')->get('remark');

        $transactions = Transaction::where('user_id', auth()->id())->searchable(['trx'])->filter(['trx_type', 'remark', 'wallet_type'])->orderBy('id', 'desc')->paginate(getPaginate());

        return view('Template::user.transactions', compact('pageTitle', 'transactions', 'remarks'));
    }

    public function kycForm()
    {
        if (auth()->user()->kv == Status::KYC_PENDING) {
            $notify[] = ['error', 'Your KYC is under review'];
            return to_route('user.home')->withNotify($notify);
        }
        if (auth()->user()->kv == Status::KYC_VERIFIED) {
            $notify[] = ['error', 'You are already KYC verified'];
            return to_route('user.home')->withNotify($notify);
        }
        $pageTitle = 'KYC Form';
        $form      = Form::where('act', 'kyc')->first();
        return view('Template::user.kyc.form', compact('pageTitle', 'form'));
    }

    public function kycData()
    {
        $user      = auth()->user();
        $pageTitle = 'KYC Data';
        abort_if($user->kv == Status::VERIFIED, 403);
        return view('Template::user.kyc.info', compact('pageTitle', 'user'));
    }

    public function kycSubmit(Request $request)
    {
        $form           = Form::where('act', 'kyc')->firstOrFail();
        $formData       = $form->form_data;
        $formProcessor  = new FormProcessor();
        $validationRule = $formProcessor->valueValidation($formData);
        $request->validate($validationRule);
        $user = auth()->user();
        foreach (@$user->kyc_data ?? [] as $kycData) {
            if ($kycData->type == 'file') {
                fileManager()->removeFile(getFilePath('verify') . '/' . $kycData->value);
            }
        }
        $userData                   = $formProcessor->processFormData($request, $formData);
        $user->kyc_data             = $userData;
        $user->kyc_rejection_reason = null;
        $user->kv                   = Status::KYC_PENDING;
        $user->save();

        $notify[] = ['success', 'KYC data submitted successfully'];
        return to_route('user.home')->withNotify($notify);

    }

    public function userData()
    {
        $user = auth()->user();

        if ($user->profile_complete == Status::YES) {
            return to_route('user.home');
        }

        $pageTitle  = 'User Data';
        $info       = json_decode(json_encode(getIpInfo()), true);
        $mobileCode = @implode(',', $info['code']);
        $countries  = json_decode(file_get_contents(resource_path('views/partials/country.json')));

        return view('Template::user.user_data', compact('pageTitle', 'user', 'countries', 'mobileCode'));
    }

    public function userDataSubmit(Request $request)
    {
        $user = auth()->user();

        if ($user->profile_complete == Status::YES) {
            return to_route('user.home');
        }

        $countryData  = (array) json_decode(file_get_contents(resource_path('views/partials/country.json')));
        $countryCodes = implode(',', array_keys($countryData));
        $mobileCodes  = implode(',', array_column($countryData, 'dial_code'));
        $countries    = implode(',', array_column($countryData, 'country'));

        $validationRule = [
            'country_code' => 'required|in:' . $countryCodes,
            'country'      => 'required|in:' . $countries,
            'mobile_code'  => 'required|in:' . $mobileCodes,
            'username'     => 'required|unique:users|min:6',
            'mobile'       => ['required', 'regex:/^([0-9]*)$/', Rule::unique('users')->where('dial_code', $request->mobile_code)],
        ];

        if (!$user->email) {
            $validationRule['firstname'] = 'required';
            $validationRule['lastname']  = 'required';
            $validationRule['email']     = 'required|email|unique:users';
        }

        $request->validate($validationRule);

        if (preg_match("/[^a-z0-9_]/", trim($request->username))) {
            $notify[] = ['info', 'Username can contain only small letters, numbers and underscore.'];
            $notify[] = ['error', 'No special character, space or capital letters in username.'];
            return back()->withNotify($notify)->withInput($request->all());
        }

        if (!$user->email) {
            $user->firstname = $request->firstname;
            $user->lastname  = $request->lastname;
            $user->email = $request->email;
            $user->ev    = gs('ev') ? Status::NO : Status::YES;
        }

        $user->country_code = $request->country_code;
        $user->mobile       = $request->mobile;
        $user->username     = $request->username;

        $user->address      = $request->address;
        $user->city         = $request->city;
        $user->state        = $request->state;
        $user->zip          = $request->zip;
        $user->country_name = @$request->country;
        $user->dial_code    = $request->mobile_code;

        $user->profile_complete = Status::YES;
        $user->save();

        return to_route('user.home');
    }

    public function addDeviceToken(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'token' => 'required',
        ]);

        if ($validator->fails()) {
            return ['success' => false, 'errors' => $validator->errors()->all()];
        }

        $deviceToken = DeviceToken::where('token', $request->token)->first();

        if ($deviceToken) {
            return ['success' => true, 'message' => 'Already exists'];
        }

        $deviceToken          = new DeviceToken();
        $deviceToken->user_id = auth()->user()->id;
        $deviceToken->token   = $request->token;
        $deviceToken->is_app  = Status::NO;
        $deviceToken->save();

        return ['success' => true, 'message' => 'Token saved successfully'];
    }

    public function downloadAttachment($fileHash)
    {
        $filePath  = decrypt($fileHash);
        $extension = pathinfo($filePath, PATHINFO_EXTENSION);
        $title     = slug(gs('site_name')) . '- attachments.' . $extension;
        try {
            $mimetype = mime_content_type($filePath);
        } catch (\Exception $e) {
            $notify[] = ['error', 'File does not exists'];
            return back()->withNotify($notify);
        }
        header('Content-Disposition: attachment; filename="' . $title);
        header("Content-Type: " . $mimetype);
        return readfile($filePath);
    }

    public function referrals()
    {
        $pageTitle = 'Referrals';
        $user      = auth()->user();
        $maxLevel  = Referral::max('level');
        return view('Template::user.referrals', compact('pageTitle', 'user', 'maxLevel'));
    }

    public function promotionalBanners()
    {
        $promotionCount = PromotionTool::count();
        if (!gs('promotional_tool') || !$promotionCount) {
            abort(404);
        }
        $pageTitle    = 'Promotional Banners';
        $banners      = PromotionTool::orderBy('id', 'desc')->get();
        $emptyMessage = 'No banner found';
        return view('Template::user.promo_tools', compact('pageTitle', 'banners', 'emptyMessage'));
    }

    public function transferBalance()
    {
        if (!gs('b_transfer')) {
            abort(404);
        }
        $pageTitle = 'Balance Transfer';
        $user      = auth()->user();
        return view('Template::user.balance_transfer', compact('pageTitle', 'user'));
    }

    public function transferBalanceSubmit(Request $request)
    {
        $general = gs();
        if (!$general->b_transfer) {
            abort(404);
        }
        $request->validate([
            'username' => 'required',
            'amount'   => 'required|numeric|gt:0',
            'wallet'   => 'required|in:deposit_wallet,interest_wallet',
        ]);

        $user = auth()->user();
        if ($user->username == $request->username) {
            $notify[] = ['error', 'You cannot transfer balance to your own account'];
            return back()->withNotify($notify);
        }

        $receiver = User::where('username', $request->username)->first();
        if (!$receiver) {
            $notify[] = ['error', 'Oops! Receiver not found'];
            return back()->withNotify($notify);
        }

        if ($user->ts) {
            $response = verifyG2fa($user, $request->authenticator_code);
            if (!$response) {
                $notify[] = ['error', 'Wrong verification code'];
                return back()->withNotify($notify);
            }
        }

        $general     = gs();
        $charge      = $general->f_charge + ($request->amount * $general->p_charge) / 100;
        $afterCharge = $request->amount + $charge;
        $wallet      = $request->wallet;

        if ($user->$wallet < $afterCharge) {
            $notify[] = ['error', 'You have no sufficient balance to this wallet'];
            return back()->withNotify($notify);
        }

        $user->$wallet -= $afterCharge;
        $user->save();

        $trx1                      = getTrx();
        $transaction               = new Transaction();
        $transaction->user_id      = $user->id;
        $transaction->amount       = getAmount($afterCharge);
        $transaction->charge       = $charge;
        $transaction->trx_type     = '-';
        $transaction->trx          = $trx1;
        $transaction->wallet_type  = $wallet;
        $transaction->remark       = 'balance_transfer';
        $transaction->details      = 'Balance transfer to ' . $receiver->username;
        $transaction->post_balance = getAmount($user->$wallet);
        $transaction->save();

        $receiver->deposit_wallet += $request->amount;
        $receiver->save();

        $trx2                      = getTrx();
        $transaction               = new Transaction();
        $transaction->user_id      = $receiver->id;
        $transaction->amount       = getAmount($request->amount);
        $transaction->charge       = 0;
        $transaction->trx_type     = '+';
        $transaction->trx          = $trx2;
        $transaction->wallet_type  = 'deposit_wallet';
        $transaction->remark       = 'balance_received';
        $transaction->details      = 'Balance received from ' . $user->username;
        $transaction->post_balance = getAmount($receiver->deposit_wallet);
        $transaction->save();

        notify($user, 'BALANCE_TRANSFER', [
            'amount'        => showAmount($request->amount, currencyFormat: false),
            'charge'        => showAmount($charge, currencyFormat: false),
            'wallet_type'   => keyToTitle($wallet),
            'post_balance'  => showAmount($user->$wallet, currencyFormat: false),
            'user_fullname' => $receiver->fullname,
            'username'      => $receiver->username,
            'trx'           => $trx1,
        ]);

        notify($receiver, 'BALANCE_RECEIVE', [
            'wallet_type'  => 'Deposit wallet',
            'amount'       => showAmount($request->amount, currencyFormat: false),
            'post_balance' => showAmount($receiver->deposit_wallet, currencyFormat: false),
            'sender'       => $user->username,
            'trx'          => $trx2,
        ]);

        $notify[] = ['success', 'Balance transferred successfully'];
        return back()->withNotify($notify);
    }

    public function findUser(Request $request)
    {
        $user    = User::where('username', $request->username)->first();
        $message = null;
        if (!$user) {
            $message = 'User not found';
        }
        if (@$user->username == auth()->user()->username) {
            $message = 'You cannot send money to your own account';
        }
        return response(['message' => $message]);
    }

}
