<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\GeneralSetting;
use App\Models\Payment;
use App\Models\RefferedCommission;
use App\Models\Transaction;
use App\Models\AssetTransaction;
use App\Models\User; 
use App\Models\UserInterest;
use App\Models\Withdraw;
use App\Models\EmailNotification;
use Illuminate\Http\Request;
use Auth;
use DB;


class ManageUserController extends Controller
{
    public function index()
    {

        $data['pageTitle'] = 'All Users';
        $data['navManageUserActiveClass'] = 'active';
        $data['subNavManageUserActiveClass'] = 'active';

        // $data['users'] = User::latest()->paginate();
        $data['users'] = User::orderby('id','DESC')->paginate();

        return view('backend.users.index')->with($data);
    }
    
    public function userSearch(Request $request)
{
    // 1. Set the Page Title for the View
    $pageTitle = "Search Results for: " . ($request->search ?? 'All Users');
    
    // 2. Start the Query
    $users = User::query()
        // Handle Text Search (Username, Email, Phone, Names)
        ->when($request->search, function ($query, $search) {
            return $query->where(function ($q) use ($search) {
                $q->where('username', 'LIKE', "%$search%")
                  ->orWhere('email', 'LIKE', "%$search%")
                  ->orWhere('phone', 'LIKE', "%$search%")
                  ->orWhere('fname', 'LIKE', "%$search%")
                  ->orWhere('lname', 'LIKE', "%$search%");
            });
        })
        // Handle Status Filter (Active/Inactive)
        ->when($request->status !== null && $request->status !== 'all', function ($query) use ($request) {
            return $query->where('status', $request->status);
        })
        // 3. Finalize and Paginate
        ->orderBy('id', 'DESC')
        ->paginate(20)
        ->withQueryString(); // This keeps the search term in the 'Next/Prev' links

    // 4. Return to your existing view
    return view('backend.users.index', compact('users', 'pageTitle'));
}
    
    
    public function search(Request $request)
{
    $pageTitle = 'User Search Results';
    $search = $request->search;
    $status = $request->status;

    // Start with a base query
    $users = User::query()
        // Search by multiple columns
        ->when($search, function ($query) use ($search) {
            return $query->where(function ($q) use ($search) {
                $q->where('username', 'LIKE', "%$search%")
                  ->orWhere('email', 'LIKE', "%$search%")
                  ->orWhere('fname', 'LIKE', "%$search%")
                  ->orWhere('lname', 'LIKE', "%$search%")
                  ->orWhere('phone', 'LIKE', "%$search%");
            });
        })
        // Filter by Status (0 or 1)
        ->when($status !== null && $status !== 'all', function ($query) use ($status) {
            return $query->where('status', $status);
        })
        ->orderBy('id', 'DESC')
        ->paginate(20)
        ->withQueryString(); // Keeps search params in pagination links

    return view('backend.users.index', compact('users', 'pageTitle'));
}

    public function userDetails(Request $request)
    {
        $user = User::where('id', $request->user)->firstOrFail();
        $created_at = User::where('id', $request->created_at);

        $totalRef = $user->refferals->count();

        $userInterest = $user->interest->sum('interest_amount');

        $userCommission = $user->commissions->sum('amount');

        $withdrawTotal = Withdraw::where('user_id', $user->id)->where('status', 1)->sum('withdraw_amount');

        $totalDeposit = $user->deposits()->where('payment_status', 1)->sum('amount');

        $totalInvest = $user->payments()->where('payment_status', 1)->sum('amount');

        $totalTicket = $user->tickets->count();



        $payment = Payment::with('plan')->where('user_id', $user->id)->where('payment_status', 1)->latest()->first();
           
            
        if ($payment && $payment->plan) {
             
            $plan = $payment->plan->plan_name;
        } else {
            $plan = 'N/A';
        }



        $months = collect([]);
        $totalAmount = collect([]);
        $data['users'] = User::latest()->paginate(5);
        Payment::where('payment_status', 1)->where('user_id', $user->id)
            ->select(DB::raw('SUM(final_amount) as total'), DB::raw('MONTHNAME(created_at) month'))
            ->groupby('month')
            ->get()
            ->map(function ($q) use ($months, $totalAmount) {
                $months->push($q->month);
                $totalAmount->push($q->total);
            });

        $months = $months;
        $totalAmount = $totalAmount;

        $withdrawMonths = collect([]);
        $withdrawTotalAmount = collect([]);
        Withdraw::where('status', 1)->where('user_id', $user->id)
            ->select(DB::raw('SUM(withdraw_amount) as total'), DB::raw('MONTHNAME(created_at) month'))
            ->groupby('month')
            ->get()
            ->map(function ($q) use ($withdrawMonths, $withdrawTotalAmount) {
                $withdrawMonths->push($q->month);
                $withdrawTotalAmount->push($q->total);
            });


        $withdrawMonths = $withdrawMonths;
        $withdrawTotalAmount = $withdrawTotalAmount;

        $pageTitle = "User Details";
              
        return view('backend.users.details', compact('pageTitle', 'user', 'plan', 'totalRef', 'userInterest', 'userCommission', 'withdrawTotal', 'totalDeposit', 'totalInvest', 'totalTicket','months','totalAmount','withdrawMonths','withdrawTotalAmount','created_at'));
    }

    public function userUpdate(Request $request, User $user)
    {



        $request->validate([
            'fname' => 'required',
            'lname' => 'required',
            // 'transfer_code' => 'unique:users,transfer_code',
            // 'trader' => 'users,trader',
            
        ]);


        $data = [
            'country' => $request->country,
            'city' => $request->city,
            'zip' => $request->zip,
            'state' => $request->state,
        ];


        $user->fname = $request->fname;
        $user->lname = $request->lname;
        $user->signal_strength = $request->signal_strength;
        $user->account_status = $request->account_status;

        $user->address = $data;
        $user->status = $request->status == 'on' ? 1 : 0;
        $user->sv = $request->sms_status == 'on' ? 1 : 0;
        $user->ev = $request->email_status == 'on' ? 1 : 0;
        $user->kyc = $request->kyc_status == 'on' ? 1 : 0;
        
        $user->transfer_code = $request->transfer_code;
        $user->trader = $request->trader;
        $user->currency = $request->currency;
        $user->acctmessage = $request->acctmessage;
        $user->deposit_bonus = $request->deposit_bonus;
        $user->investment_bonus = $request->investment_bonus;
        $user->level = $request->level;

        $user->save();



        $notify[] = ['success', 'User Updated Successfully'];

        return back()->withNotify($notify);
    }
    public function showUsersMailPage()
{
    $pageTitle = "Send Mail To All Users";
    return view('backend.users.mail-all', compact('pageTitle'));
}

    public function sendUserMail(Request $request, User $user)
    {
        $data = $request->validate([
            'subject' => 'required',
            "message" => 'required',
        ]);

        $data['name'] = $user->fullname;
        $data['email'] = $user->email;

 // Save the email details in the EmailNotification table
    EmailNotification::create([
        'user_id' => $user->id,
        'subject' => $data['subject'],
        'message' => $data['message'],
    ]);

        $message = $data['message'];
        sendMailbyblade(
            $user->email,
            $data['subject'],
            view(
                "emails.mail",
                compact("message")
            ),
            $user->username
        );

        $notify[] = ['success', 'Send Email To user Successfully'];

        return back()->withNotify($notify);
    }


public function sendUsersMail(Request $request)
{
    // Validate the input data
    $data = $request->validate([
        'subject' => 'required',
        'message' => 'required',
    ]);
 
    $users = User::all();
    foreach($users as $user) {
        // Prepare email data
       

        EmailNotification::create([
            'user_id' => $user->id,
            'subject' => $data['subject'],
            'message' => $data['message'],
        ]);

        // sendGeneralMail($emailData);
         $message = $data['message'];
        sendMailbyblade(
            $user->email,
            $data['subject'],
            view(
                "emails.mail",
                compact("message")
            ),
            $user->username
        );
    }

    $notify[] = ['success', 'Emails sent to all users successfully'];

    return back()->withNotify($notify);
}

    
    public function disabled(Request $request)
    {
        $pageTitle = 'Disabled Users';

        $search = $request->search;

        $users = User::when($search, function ($q) use ($search) {
            $q->where('name', 'LIKE', '%' . $search . '%')
                ->orWhere('company_name', 'LIKE', '%' . $search . '%')
                ->orWhere('email', 'LIKE', '%' . $search . '%')
                ->orWhere('mobile', 'LIKE', '%' . $search . '%');
        })->where('status', 0)->latest()->paginate();

        return view('backend.users.index', compact('pageTitle', 'users'));
    }
    
      public function userStatusWiseFilter(Request $request)
    {
        $data['pageTitle'] = ucwords($request->status) . ' Users';
        $data['navManageUserActiveClass'] = 'active';
        if ($request->status == 'active') {
            $data['subNavActiveUserActiveClass'] = 'active';
        }elseif ($request->status == 'deactive') {
            $data['subNavDeactiveUserActiveClass'] = 'active';
        }
        else {
            $data['subNavUnverifyUserActiveClass'] = 'active';
        }

        $users = User::query();

         if ($request->status == 'active') {
            $users->where([['status', 1],['ev',1]]);
        } elseif ($request->status == 'deactive') {
            $users->where('status', 0);
        }
        elseif ($request->status == 'unverify') {
            $users->where('ev', 0);
        }


        // $data['users'] = $users->paginate();
        $data['users'] = $users->orderby('id','DESC')->paginate();


        return view('backend.users.index')->with($data);
    }

    // public function userStatusWiseFilter(Request $request)
    // {
    //     $data['pageTitle'] = ucwords($request->status) . ' Users';
    //     $data['navManageUserActiveClass'] = 'active';
    //     if ($request->status == 'active') {
    //         $data['subNavActiveUserActiveClass'] = 'active';
    //     } else {
    //         $data['subNavDeactiveUserActiveClass'] = 'active';
    //     }

    //     $users = User::query();

    //     if ($request->status == 'active') {
    //         $users->where('status', 1);
    //     } elseif ($request->status == 'deactive') {
    //         $users->where('status', 0);
    //     }


    //     $data['users'] = $users->paginate();


    //     return view('backend.users.index')->with($data);
    // }

    public function interestLog($user = '')
    {

        $interestLogs = UserInterest::query();

        $user = User::find($user);

        $pageTitle = "User Interest Log";

        if ($user) {

            $interestLogs->where('user_id', $user->id);
        }

        $interestLogs = $interestLogs->latest()->paginate();


        return view('backend.userinterestlog', compact('interestLogs', 'pageTitle'));
    }

public function userBalanceUpdate(Request $request)
{
    $request->validate([
        'user_id' => 'required|exists:users,id',
        'balance' => 'required|numeric|min:0',
        'balanceType' => 'required|string',
        'type' => 'required|in:add,minus',
    ]);

    $user = User::findOrFail($request->user_id);
    $balanceAmount = $request->balance;
    $balanceType = $request->balanceType;
    $actionType = $request->type; 

    $general = GeneralSetting::first();
    $sendEmail = false;

    if ($balanceType === 'balance') {
        if ($actionType === 'add') {
            $user->balance += $balanceAmount;
            $logAmount = $balanceAmount;
            $sendEmail = true;
        } else {
            if ($user->balance < $balanceAmount) {
                return back()->withNotify([['error', 'Insufficient balance']]);
            }
            $user->balance -= $balanceAmount;
            $logAmount = -$balanceAmount;
        }

        \App\Models\BalanceLog::create([
            'user_id' => $user->id,
            'amount' => $logAmount,
            'type' => $actionType,
            'remark' => 'Balance Update',
        ]);
    } else {
        if ($actionType === 'add') {
            switch ($balanceType) {
                case 'withdraws':
                    Withdraw::create(['user_id' => $user->id, 'withdraw_amount' => $balanceAmount, 'status' => 1]);
                    break;
                case 'totalInvest':
                    $user->totalInvest += $balanceAmount;
                    break;
                case 'profit':
                    UserInterest::create(['user_id' => $user->id, 'interest_amount' => $balanceAmount]);
                    $user->balance += $balanceAmount;
                    $sendEmail = true;
                    
                    // ADDED: Log this as a notification-triggering event
                    \App\Models\BalanceLog::create([
                        'user_id' => $user->id,
                        'amount' => $balanceAmount,
                        'type' => 'add',
                        'remark' => 'Profit Credited',
                    ]);
                    break;
                case 'deposit':
                    Deposit::create(['user_id' => $user->id, 'amount' => $balanceAmount, 'final_amount' => $balanceAmount, 'payment_status' => 1]);
                    $user->balance += $balanceAmount;
                    break;
                case 'ref_bonus':
                    RefferedCommission::create(['reffered_by' => $user->id, 'amount' => $balanceAmount]);
                    $user->balance += $balanceAmount;
                    break;
            }
        } else {
            switch ($balanceType) {
                case 'withdraws':
                    Withdraw::create(['user_id' => $user->id, 'withdraw_amount' => -$balanceAmount, 'status' => 1]);
                    break;
                case 'profit':
                    UserInterest::create(['user_id' => $user->id, 'interest_amount' => -$balanceAmount]);
                    $user->balance -= $balanceAmount;

                    // ADDED: Log this as a notification-triggering event
                    \App\Models\BalanceLog::create([
                        'user_id' => $user->id,
                        'amount' => -$balanceAmount,
                        'type' => 'minus',
                        'remark' => 'Profit Adjusted',
                    ]);
                    break;
                case 'deposit':
                    Deposit::create(['user_id' => $user->id, 'amount' => -$balanceAmount, 'final_amount' => -$balanceAmount, 'payment_status' => 1]);
                    $user->balance -= $balanceAmount;
                    break;
                case 'ref_bonus':
                    RefferedCommission::create(['reffered_by' => $user->id, 'amount' => -$balanceAmount]);
                    $user->balance -= $balanceAmount;
                    break;
            }
        }
    }

    $user->save();

    if ($sendEmail && $general->is_email_credit_on == 1) {
        $username = $user->username;
        $balance = $user->balance;
        $input_balance = $balanceAmount;
        $userInterest = $user->interest->sum('interest_amount');
        $currency = $user->currency;
        $htmlBody = view('emails.creditEmail', compact('username', 'currency', 'balance', 'input_balance', 'userInterest'));
        sendMailbyblade($user->email, "Account Update | " . $general->sitename, $htmlBody, $user->username);
    }

    return back()->withNotify([['success', 'Successfully ' . $actionType . ' balance']]);
}


// public function userBalanceUpdate(Request $request)
// {
//     $request->validate([
//         'user_id' => 'required|exists:users,id',
//         'balance' => 'required|numeric|min:0',
//         'balanceType' => 'required|string',
//         'type' => 'required|in:add,minus',
//     ]);

//     $user = User::findOrFail($request->user_id);
//     $balanceAmount = $request->balance;
//     $balanceType = $request->balanceType;
//     $actionType = $request->type; 

//     $general = GeneralSetting::first();
//     $sendEmail = false;

//     // --- SHARED BALANCE CASE ---
//     // If the balanceType is 'balance', we handle both add/minus here 
//     // to avoid duplicating the BalanceLog logic.
//     if ($balanceType === 'balance') {
//         if ($actionType === 'add') {
//             $user->balance += $balanceAmount;
//             $logAmount = $balanceAmount;
//             $sendEmail = true;
//         } else {
//             if ($user->balance < $balanceAmount) {
//                 return back()->withNotify([['error', 'Insufficient balance']]);
//             }
//             $user->balance -= $balanceAmount;
//             $logAmount = -$balanceAmount;
//         }

//         \App\Models\BalanceLog::create([
//             'user_id' => $user->id,
//             'amount' => $logAmount,
//             'type' => $actionType,
//             'remark' => 'Balance Update',
//         ]);
//     } else {
//         // --- ALL OTHER CASES (Withdraws, Profit, etc.) ---
//         if ($actionType === 'add') {
//             switch ($balanceType) {
//                 case 'withdraws':
//                     Withdraw::create(['user_id' => $user->id, 'withdraw_amount' => $balanceAmount, 'status' => 1]);
//                     break;
//                 case 'totalInvest':
//                     $user->totalInvest += $balanceAmount;
//                     break;
//                 case 'profit':
//                     UserInterest::create(['user_id' => $user->id, 'interest_amount' => $balanceAmount]);
//                     $user->balance += $balanceAmount;
//                     $sendEmail = true;
//                     break;
//                 case 'deposit':
//                     Deposit::create(['user_id' => $user->id, 'amount' => $balanceAmount, 'final_amount' => $balanceAmount, 'payment_status' => 1]);
//                     $user->balance += $balanceAmount;
//                     break;
//                 case 'ref_bonus':
//                     RefferedCommission::create(['reffered_by' => $user->id, 'amount' => $balanceAmount]);
//                     $user->balance += $balanceAmount;
//                     break;
//             }
//         } else {
//             switch ($balanceType) {
//                 case 'withdraws':
//                     Withdraw::create(['user_id' => $user->id, 'withdraw_amount' => -$balanceAmount, 'status' => 1]);
//                     break;
//                 case 'profit':
//                     UserInterest::create(['user_id' => $user->id, 'interest_amount' => -$balanceAmount]);
//                     $user->balance -= $balanceAmount;
//                     break;
//                 case 'deposit':
//                     Deposit::create(['user_id' => $user->id, 'amount' => -$balanceAmount, 'final_amount' => -$balanceAmount, 'payment_status' => 1]);
//                     $user->balance -= $balanceAmount;
//                     break;
//                 case 'ref_bonus':
//                     RefferedCommission::create(['reffered_by' => $user->id, 'amount' => -$balanceAmount]);
//                     $user->balance -= $balanceAmount;
//                     break;
//             }
//         }
//     }

//     $user->save();

//     // Email logic
//     if ($sendEmail && $general->is_email_credit_on == 1) {
//         $username = $user->username;
//         $balance = $user->balance;
//         $input_balance = $balanceAmount;
//         $userInterest = $user->interest->sum('interest_amount');
//         $currency = $user->currency;
//         $htmlBody = view('emails.creditEmail', compact('username', 'currency', 'balance', 'input_balance', 'userInterest'));
//         sendMailbyblade($user->email, "Account Update | " . $general->sitename, $htmlBody, $user->username);
//     }

//     return back()->withNotify([['success', 'Successfully ' . $actionType . ' balance']]);
// }

    
    


    public function loginAsUser($id)
    {
        $user = User::findOrFail($id);

        Auth::loginUsingId($user->id);

        return redirect()->route('user.dashboard');
    }


    public function kyc()
    {
        $data['subNavkycUserActiveClass'] = 'active';

        $data['pageTitle'] = 'KYC Settings';

        return view('backend.users.kyc')->with($data);
    }


    public function kycUpdate(Request $request)
    {
        $request->validate([
            "kyc" => 'required|array',
        ]);

        $general = GeneralSetting::first();


        $general->kyc = $request->kyc;

        $general->save();


        return back()->with('success', 'Kyc settings updated successfully');
    }

    public function kycAll()
    {
        // $data['infos'] = User::where('kyc', 2)->paginate();
        // $data['infos'] = User::whereIn('kyc', [1, 2])->paginate();
        $data['infos'] = User::whereIn('kyc', [1, 2])->orderby('id','DESC')->paginate();



        $data['pageTitle'] = 'KYC Requests';
        $data['subNavkycReqUserActiveClass'] = 'active';
        $data['navManageUserActiveClass'] = 'active';

        return view('backend.users.kyc_req')->with($data);
    }

    public function kycDetails($id)
    {
        $data['user'] = User::findOrFail($id);

        $data['pageTitle']  = 'KYC Details';


        $data['subNavkycReqUserActiveClass'] = 'active';
        $data['navManageUserActiveClass'] = 'active';

        return view('backend.users.kyc_details')->with($data);
    }

    public function kycStatus($status, $id)
    {
        $user = User::findOrFail($id);

        if ($status === 'approve') {
            $user->kyc = 1;
        } else {
            $user->kyc = 3;
        }

        $user->save();

        return back()->with('success', 'Successfull');
    }


    public function userDelete($user){
        
        $user = User::where('id', $user)->first();
       
        
           if($user){
            $user->delete();

            return redirect(route('admin.user'))->with('success', 'User deleted successfully!');

          //  return back()->with('success', 'User deleted Successfully');
        }else{
           

            return redirect(route('admin.user'))->with('error', 'User not found!');

        }
       
       

    }
    
   public function investmentLog()
{
    $pageTitle = "Investment Log";

    // We removed 'next_payment_date != null' so paused plans (which are null) still show up.
    // We keep 'payment_status', 1 to ensure we only show successful investments.
    $investmentLogs = Payment::where('payment_status', 1)
        ->latest()
        ->paginate(20);

    return view('backend.investmentlog', compact('investmentLogs', 'pageTitle'));
}
    
     public function destroy($id)
{
    // Find the payment log
    $payment = Payment::with('userInterests')->findOrFail($id);

    // 1. Stop future returns
    $payment->status = 0; // Mark as cancelled
    $payment->next_payment_date = null; // stop next payout generation
    $payment->save();

    // 2. Delete related user interests (optional but recommended)
    if ($payment->userInterests()->exists()) {
        $payment->userInterests()->delete();
    }

    // 3. Now delete the main plan/payment
    $payment->delete();

    return back()->with('success', 'Investment has been cancelled and deleted successfully.');
}
public function pause($id)
{
    // Fetch payment
    $payment = Payment::findOrFail($id);

    // Stop the plan from generating new interest
    $payment->status = 0; // Set to cancelled/paused
    $payment->next_payment_date = null; // Prevent further interest cycles
    $payment->save();

    return back()->with('success', 'Investment has been paused successfully.');
}

public function resume($id)
{
    $payment = Payment::with('plan')->findOrFail($id);

    // Set Status back to Active (1)
    $payment->status = 1;

    // Recalculate next payment date based on plan interval
    $hours = $payment->plan->every_hours ?? 24; 
    $payment->next_payment_date = now()->addHours($hours);
    
    $payment->save();

    return back()->with('success', 'Trade resumed. Next payout: ' . $payment->next_payment_date->format('d M, H:i'));
}
    
    
       public function assetTrade()
    {

       $asset_transactions = AssetTransaction::all();

        $pageTitle = "Asset Trade";

        return view('backend.assetTrade', compact('asset_transactions', 'pageTitle'));
    }
    
    
    public function assetTradeApprove($id)
{

    // Update the status to 'Approved'
    $updated = DB::table('asset_transactions') // Replace with your actual table name
        ->where('id', $id)
        ->where('status', 'Pending') // Ensure only Pending transactions are updated
        ->update(['status' => 'Approved']);

    // Check if the update was successful
    if ($updated) {
        $notify[] = ['success', 'Asset approved successfully'];
    } else {
        $notify[] = ['error', 'Asset could not be approved or is already approved'];
    }

    return back()->withNotify($notify);
}
    
}
