<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;

use App\Models\User;
use App\Models\SilverLevelMaster;
use App\Models\SilverDepositRequest;
use App\Models\SilverRoiUser;
use App\Models\SilverRoiHistory;
use App\Models\SilverReferralMaster;
use App\Models\SilverAccount;
use App\Models\DiamondDepositRequest;
use App\Models\DiamondRoiUser;
use App\Models\FinAdminRequest;
use App\Models\UserCashWallet;

class DepositController extends Controller
{
    public function load_deposit()
    {
        $users  = User::select('id', 'user_id', 'name')->get();
        return view('Admin.load_deposit', compact('users'));
    }


    public function deposit_form(Request $request)
    {
        Log::info('Admin deposit request received', [
            'request_data' => $request->all(),
        ]);

        $request->validate([

            'user_id'         => 'required|string|exists:users,user_id',
            'package'         => 'required',
            'utr'             => 'required|string',
            'wallet_value'    => 'required|numeric',
            'pay_mode'        => 'required',
            'days'            => 'required|numeric',
            'roi_percentage'  => 'required|numeric|min:0|max:100',
            'give_spot'       => 'required',
            'deposited_by'    => 'required',

        ]);

        DB::beginTransaction();
        try {

            Log::info('Deposit process started', [
                'user_id' => $request->user_id,
                'package' => $request->package,
            ]);

            $wallet = UserCashWallet::firstOrCreate(

                [
                    'user_id' => $request->user_id
                ],

                [
                    'diamond_investment' => 0,
                    'silver_investment'  => 0,
                    'gold_investment'    => 0,
                ]
            );

            // SILVER PACKAGE
            if ($request->package == 'silver') {

                Log::info('Silver package selected');

                // $levelReward = SilverLevelMaster::orderBy('id', 'desc')->first();

                // Log::info('Silver level fetched', [
                //     'level_data' => $levelReward
                // ]);

                // if (!$levelReward) {

                //     Log::warning('Silver level master not found');

                //     return back()->with('error', 'Silver level master not found');
                // }

                // Deposit Request
                $deposit = SilverDepositRequest::create([
                    'user_id'      => $request->user_id,
                    'wallet_value' => $request->wallet_value,
                    'pay_mode'     => $request->pay_mode,
                    'status'       => 'Accepted',
                    'utr'          => $request->utr,
                    'entry_date'   => now(),
                    'deposited_by' => 'Admin',
                ]);

                Log::info('Silver deposit created', [
                    'deposit_id' => $deposit->id
                ]);

                // ROI User
                $roiUser = SilverRoiUser::create([
                    'inv_id'         => $deposit->id,
                    'user_id'        => $request->user_id,
                    'wallet_value'   => $request->wallet_value,
                    'reward'         => ($request->wallet_value * $request->roi_percentage) / 100,
                    'roi_percentage' => $request->roi_percentage,
                    'entry_date'     => now(),
                    'days'           => 1001,
                ]);

                Log::info('Silver ROI user created', [
                    'roi_user' => $roiUser
                ]);

                // ROI History
                $roiHistory = SilverRoiHistory::create([
                    'inv_id'         => $deposit->id,
                    'user_id'        => $request->user_id,
                    'roi_percentage' => $request->roi_percentage,
                    'entry_date'     => now(),
                    'days'           => 1001,
                ]);

                Log::info('Silver ROI history created', [
                    'roi_history' => $roiHistory
                ]);

                $wallet->increment(
                    'silver_investment',
                    $request->wallet_value
                );

                Log::info('Silver investment wallet updated', [
                    'user_id'           => $request->user_id,
                    'wallet_value'      => $request->wallet_value,
                    'silver_investment' => $wallet->fresh()->silver_investment,
                ]);

                // Referral Income
                // $refPre = SilverReferralMaster::latest('id')->value('ref_pre') ?? 0;

                // Log::info('Referral percentage fetched', [
                //     'ref_pre' => $refPre
                // ]);

                // $refIncome = ($request->wallet_value * $refPre) / 100;

                // $user = User::where('user_id', $request->user_id)->first();

                // Log::info('User fetched', [
                //     'user' => $user
                // ]);

                // if ($refPre > 0 && $user) {

                //     $silverAccount = SilverAccount::create([
                //         'user_id'    => $user->ref_id,
                //         'credit'     => $refIncome,
                //         'entry_date' => now(),
                //         'remark'     => 'Referral Income',
                //         'inv_id'     => $deposit->id,
                //         'pre'        => $refPre,
                //         'type'       => 'Referral',
                //     ]);

                //     Log::info('Referral income added', [
                //         'silver_account' => $silverAccount
                //     ]);
                // }

                // Log::info('Calling silver_level function');

                // $this->silver_level(
                //     $request->user_id,
                //     $request->wallet_value,
                //     $deposit->id
                // );

                // Log::info('silver_level function completed');
            }

            // DIAMOND PACKAGE
            elseif ($request->package == 'diamond') {

                Log::info('Diamond package selected');

                $deposit = DiamondDepositRequest::create([
                    'user_id'      => $request->user_id,
                    'wallet_value' => $request->wallet_value,
                    'pay_mode'     => $request->pay_mode,
                    'status'       => 'Accepted',
                    'utr'          => $request->utr,
                    'entry_date'   => now(),
                    'give_spot'    => $request->give_spot,
                    'deposited_by' => $request->deposited_by,
                ]);

                Log::info('Diamond deposit created', [
                    'deposit_id' => $deposit->id
                ]);

                $diamondRoi = DiamondRoiUser::create([
                    'inv_id'         => $deposit->id,
                    'user_id'        => $request->user_id,
                    'wallet_value'   => $request->wallet_value,
                    'reward'         => ($request->wallet_value * $request->roi_percentage) / 100,
                    'roi_percentage' => $request->roi_percentage,
                    'deposited_by'   => $request->deposited_by,
                    'sponsor_status' => 'Active',
                    'entry_date'     => now(),
                    'days'           => $request->days,
                    'give_spot'      => $request->give_spot,
                ]);

                $wallet->increment(
                    'diamond_investment',
                    $request->wallet_value
                );

                Log::info('Diamond investment wallet updated', [
                    'user_id'            => $request->user_id,
                    'wallet_value'       => $request->wallet_value,
                    'diamond_investment' => $wallet->fresh()->diamond_investment,
                ]);

                Log::info('Diamond ROI created', [
                    'diamond_roi' => $diamondRoi
                ]);
            }

            // NORMAL PACKAGE
            else {

                Log::info('Normal package selected');

                $deposit = FinAdminRequest::create([
                    'user_id'      => $request->user_id,
                    'wallet_value' => $request->wallet_value,
                    'pay_mode'     => $request->pay_mode,
                    'package'      => $request->package,
                    'utr'          => $request->utr,
                    'entry_date'   => now(),
                    'approve_date' => now(),
                    'deposited_by' => 'Admin',
                    'status'       => 'Accepted',
                    'remark'       => 'Admin deposit',
                ]);

                Log::info('Normal deposit created', [
                    'deposit' => $deposit
                ]);

                $wallet->increment(
                    'gold_investment',
                    $request->wallet_value
                );
                Log::info('Gold investment wallet updated', [
                    'user_id'         => $request->user_id,
                    'wallet_value'    => $request->wallet_value,
                    'gold_investment' => $wallet->fresh()->gold_investment,
                ]);
            }

            DB::commit();

            Log::info('Deposit transaction committed successfully', [
                'user_id' => $request->user_id,
                'package' => $request->package,
            ]);

            return redirect()
                ->back()
                ->with('success', 'Deposit successful');
        } catch (\Throwable $e) {

            DB::rollBack();

            Log::error('Admin deposit failed', [
                'message' => $e->getMessage(),
                'line'    => $e->getLine(),
                'file'    => $e->getFile(),
                'trace'   => $e->getTraceAsString(),
            ]);

            return back()
                ->with('error', 'Something went wrong')
                ->withInput();
        }
    }
}
