<?php

namespace App\Http\Controllers\Subscription;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Membership;
use App\Models\User;
use App\Models\UserSubscription;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Models\ReferralIncome;
use App\Models\IncomeWallet;
use App\Models\WelcomeIncome;

class SubscriptionController extends Controller
{

    public function membership_list()
    {
        $membership_list = Membership::all();

        if ($membership_list) {

            return response()->json([
                'status' => 'success',
                'message' => 'Member List',
                'data' =>  $membership_list,
                'code' => 200,
            ], 200);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'No data Found!',
                'data' => [],
                'code' => 401,
            ], 401);
        }
    }

    public function add_subscription(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'user_id'        => 'required|exists:users,user_id',
                'membership_id'  => 'required|exists:memberships,membership_id',
                'transaction_id' => 'required|unique:user_subscriptions,transaction_id',
                'payment_image'  => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
            ]);

            if ($validator->fails()) {
                Log::error('Validation errors:', $validator->errors()->toArray());
                return response()->json([
                    'status'  => 'error',
                    'message' => 'Validation errors',
                    'code'    => 422,
                    'data'    => $validator->errors()
                ], 422);
            }

            $userdetails = User::where('user_id', $request->user_id)->first();
            $membership  = Membership::where('membership_id', $request->membership_id)->first();

            $imagepath = null;
            if ($request->hasFile('payment_image')) {
                $payment_image     = $request->file('payment_image');
                $payment_imagename = time() . '_' . $payment_image->getClientOriginalName();
                $payment_image->move(public_path('assets/images/payment_images'), $payment_imagename);
                $imagepath = 'assets/images/payment_images/' . $payment_imagename;
            }


            $data                 = new UserSubscription();
            $data->user_id        = $request->user_id;
            $data->name           = $userdetails->name;
            $data->membership_id  = $membership->membership_id;
            $data->title          = $membership->title;
            $data->amount         = $membership->amount;
            $data->days           = $membership->days;
            $data->transaction_id = $request->transaction_id;
            $data->payment_image  = $imagepath;
            $data->status         = "Requested";
            $data->remark         = "Subscripiton Requested";
            $data->save();

            return response()->json([
                'status'  => 'success',
                'message' => 'Subscription added successfully',
                'data'    => $data,
                'code'    => 200,
            ], 200);
        } catch (\Exception $e) {
            Log::error('Exception Error in add_subscription: ' . $e->getMessage());
            return response()->json([
                'status'  => 'error',
                'message' => 'Exception Error',
                'code'    => 500,
                'data'    => 'Something went wrong! Please try again.'
            ], 500);
        }
    }

    public function subscription_requests()
    {
        $datatables = UserSubscription::where('status', 'Requested')->get();
        return view('admin.subscription_requests', compact('datatables'));
    }


    public function accept_request(Request $request)
    {
        try {
            Log::info('Accept Request initiated.', ['accept_id' => $request->accept_id]);
    
            $subscription = UserSubscription::find($request->accept_id);
    
            if (!$subscription) {
                Log::warning('Subscription not found.', ['accept_id' => $request->accept_id]);
                return redirect()->route('subscription_requests')->with('errormessage', "Subscription not found!");
            }
    
            Log::info('Subscription found.', ['subscription_id' => $subscription->id, 'user_id' => $subscription->user_id]);
    
            $subscription->status    = "Accepted";
            $subscription->remark    = "Subscription Accepted";
            $subscription->action_at = now();
            $subscription->is_active = 1;
            $subscription->save();
    
            $user = User::where('user_id', $subscription->user_id)->first();
    
            if (!$user) {
                Log::warning('User not found.', ['user_id' => $subscription->user_id]);
                return redirect()->route('subscription_requests')->with('errormessage', "User not found!");
            }
    
            Log::info('User found.', ['user_id' => $user->id]);
    
            if (!empty($user->referral_id)) {
                Log::info('Processing referral income.', ['user_id' => $user->user_id]);
                $this->referral_income($user->user_id, $subscription->membership_id);
            }
    
            if (!is_null($subscription->welcome_bonus) && $subscription->welcome_bonus > 0) {
                Log::info('Processing welcome income.', ['user_id' => $user->user_id]);
                $this->welcome_income($user->user_id, $subscription->membership_id);
            }
    
            $user->membership    = $subscription->membership_id;
            $user->is_subscribed = 1;
            $user->save();
    
            Log::info('User subscription updated.', ['user_id' => $user->user_id]);
    
            return redirect()->route('subscription_requests')->with('successmessage', "Subscription accepted successfully!");
        } catch (\Exception $e) {
            Log::error('Exception Error in accept_request:', [
                'error_message' => $e->getMessage(),
                'stack_trace'   => $e->getTraceAsString(),
            ]);
            return redirect()->route('subscription_requests')->with('errormessage', "Exception Error: " . $e->getMessage());
        }
    }
    public function referral_income($user_id, $membership_id)
    {
        try {
            // Fetch User
            $user = User::where('user_id', $user_id)->first();
            if (!$user) {
                Log::error("User not found with user_id: {$user_id}");
                return false;
            }
    
            // Fetch Membership
            $membership = Membership::where('membership_id', $membership_id)->first();
            if (!$membership) {
                Log::error("Membership not found with membership_id: {$membership_id}");
                return false;
            }
    
            // Calculate Reward
            $reward = $membership->amount * $membership->referral_percentage / 100;
    
            // Save Referral Income
            $referralIncome                = new ReferralIncome();
            $referralIncome->user_id       = $user->referral_id;
            $referralIncome->membership_id = $membership_id;
            $referralIncome->amount        = $reward;
            $referralIncome->remark        = "Referral Income";
            $referralIncome->description   = $user_id;
            $referralIncome->type          = "referral";
            $referralIncome->save();
    
            Log::info("Referral income added for user_id: {$user_id}, amount: {$reward}");
    
            $income_wallet = IncomeWallet::where('user_id', $user_id)->first();
    
            if ($income_wallet) {
                $income_wallet->referral_income += $reward;
                $income_wallet->cash_wallet += $reward;
                $income_wallet->save();
                Log::info("Updated referral income wallet for user_id: {$user_id}, new amount: {$income_wallet->referral_income}");
            } else {
                $wallet                  = new IncomeWallet();
                $wallet->user_id         = $user_id;
                $wallet->referral_income = $reward;
                $wallet->cash_wallet     = $reward;
                $wallet->save();
                Log::info("Created new incoFme wallet for user_id: {$user_id} with amount: {$reward}");
            }
    
            return true;
        } catch (\Exception $e) {
            Log::error("Exception in referral_income: " . $e->getMessage(), [
                'user_id' => $user_id,
                'trace'   => $e->getTraceAsString(),
            ]);
            return false;
        }
    }

    public function welcome_income($user_id, $membership_id)
    {
        try {

            Log::info("welcome_income started");

            // Fetch User
            $user = User::where('user_id', $user_id)->first();
            if (!$user) {
                Log::info("User not found with user_id: {$user_id}");
                return false;
            }
            Log::info("welcome_income startedcccccccccccccccccccccccc");

            // Fetch Membership
            $membership = Membership::where('membership_id', $membership_id)->first();
            if (!$membership) {
                Log::info("Membership not found with membership_id: {$membership_id}");
                return false;
            }
            Log::info("welcome_income startedxxxxxxxxxxxxxxxxxxxx");

            // Add Welcome Income
            $welcome_bonus = $membership->welcome_bonus;
    
            $welcomeIncome                = new WelcomeIncome();
            $welcomeIncome->user_id       = $user_id;
            $welcomeIncome->membership_id = $membership->membership_id;
            $welcomeIncome->amount        = $welcome_bonus;
            $welcomeIncome->remark        = "Welcome Income";
            $welcomeIncome->type          = "welcome";
            $welcomeIncome->save();
    
            Log::info("Welcome income added for user_id: {$user_id}, amount: {$welcome_bonus}");
    
            // Update or Create Income Wallet
            $income_wallet = IncomeWallet::where('user_id', $user_id)->first();
    
            if ($income_wallet) {
                $income_wallet->welcome_income += $welcome_bonus;
                $income_wallet->shopping_wallet += $welcome_bonus;

                $income_wallet->save();
                Log::info("Updated income wallet for user_id: {$user_id}, new welcome income: {$income_wallet->welcome_income}");
            } else {
                // Create new Income Wallet
                $wallet                  = new IncomeWallet();
                $wallet->user_id         = $user_id;
                $wallet->welcome_income  = $welcome_bonus;
                $wallet->shopping_wallet = $welcome_bonus;

                $wallet->save();
                Log::info("Created new income wallet for user_id: {$user_id} with welcome income: {$welcome_bonus}");
            }
    
            return true;
        } catch (\Exception $e) {
            Log::info("Exception in welcome_income: " . $e->getMessage(), [
                'user_id' => $user_id,
                'trace'   => $e->getTraceAsString(),
            ]);
            return false;
        }
    }
    public function reject_request(Request $request)
    {

        try {
            $validator = Validator::make($request->all(), [
                'remark'    => 'required',
            ]);

            if ($validator->fails()) {
                return redirect()->back()->with('errormessage', $validator->errors()->first());
            }

            $subscription = UserSubscription::find($request->reject_id);

            if ($subscription) {

                $subscription->status    = "Rejected";
                $subscription->remark    = $request->remark;
                $subscription->action_at = now();
                $subscription->save();

                return redirect()->route('subscription_requests')->with('successmessage', "Subscription deleted successfully!");
            } else {
                return redirect()->route('subscription_requests')->with('errormessage', "Subscription not Found!");
            }
        } catch (\Exception $e) {
            return redirect()->route('subscription_requests')->with('errormessage', "Exception Error: " . $e->getMessage());
        }
    }

    public function bank_details()
    {
        return response()->json([
            'status'  => 'success',
            'message' => 'Bank Details',
            'data'    => [
                "id"              => 1,
                "acc_holder_name" => "Admin",
                "bank_name"       => "State Bank",
                "acc_no"          => 6256246115671,
                "ifsc"            => "S215261ggs",
                "branch_name"     => "Marthandam",
                "upi_id"          => "Admi887237627",
                "qr_code"         => asset("assets/images/payment_images/1739693087_qr_code.png"),   // Use asset() for correct URL
                "is_active"       => 1,
                "remark"          => "Admin Bank Details",
                "created_at"      => "2025-02-12T18:36:01.000000Z",
                "updated_at"      => "2025-02-12T18:36:01.000000Z"
            ],
            'code' => 200,
        ], 200);
    }

    public function income_wallet()
    {
        $incomewallet = IncomeWallet::where('user_id',Auth::user()->user_id)->first();

        if ($incomewallet) {

            return response()->json([
                'status'  => 'success',
                'message' => 'Income Wallet',
                'data'    => $incomewallet,
                'code'    => 200,
            ], 200);
        } else {
            return response()->json([
                'status'  => 'error',
                'message' => 'No data Found!',
                'data'    => [],
                'code'    => 401,
            ], 401);
        }
    }
}
