<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ParentFrontendController;
use App\Http\Controllers\Admin\MailController;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\Investment;
use App\Models\Withdrawal;
use App\Models\AgentWithdrawal;
use App\Models\User;
use App\Models\Market;
use App\Models\Bid;
use App\Models\Sell;
use App\Models\Transaction;
use App\Models\Product;
use App\Models\Ownership;
use App\Models\Vendor;
use App\Models\VendorProduct;
use App\Models\Grant;
use App\Models\Plan;
use App\Models\Blog;
use App\Models\Deposit;
use App\Models\SiteDetail;
use App\Models\AgentRequest;
use App\Models\CompanyDetail;
use App\Models\Director;
use App\Models\Testimonial;
use App\Models\In_transaction;
use App\Models\Coupon;
use App\Models\CouponRedemption;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use App\Jobs\ProcessNotification;
use Illuminate\Support\Facades\Log;

class AdminController extends Controller
{
    public function __construct()
    {
        $this->middleware(['editor'])->except(['login', 'check', 'logout', 'products', 'createProduct', 'addProduct', 'editProduct', 'updateProduct', 'productDestroy', 'createBid', 'addBid', 'kyc', 'kycUpdate', 'kycInfo']);
        $this->middleware(['blogger'])->except(['login', 'check', 'logout', 'blogs', 'createBlog', 'addBlog', 'editBlog', 'updateBlog', 'deleteBlog']);
        $this->middleware(['agent'])->except(['login', 'check', 'logout', 'password', 'changePassword', 'agentDashboard', 'agentUsers', 'agentUserInfo', 'wallet', 'addWallet', 'withdraw', 'requestWithdrawal',]);
    }

    public function login()
    {
        return view('admin.login');
    }

    public function check(Request $request)
    {
        //validate input
        $request->validate([
            'email' => 'required|exists:admins,email',
            'password' => 'required|min:8'
        ]);

        $creds = $request->only('email', 'password');
        if (Auth::guard('admin')->attempt($creds)) {
            return redirect()->route('admin.dashboard');
        } else {
            return redirect()->back()->with('error', 'Incorrect Email or Password');
        }
    }

    public function dashboard()
    {
        $users = User::all();

        $unactivatedUsers = User::where('activated', null)->get();

        $unconfirmedUsers = User::where('email_verified_at', null)->get();

        $kyc = User::where('kyc_status', 2)->get();

        $vendorRequests =  Vendor::whereHas('products', function ($query) {
            $query->where('status', 0);
        })->get();

        $agentRequests = AgentRequest::where('status', 0)->get();

        $pendingProducts = VendorProduct::where('status', 0)->get();

        $deposits = Deposit::where('status', 1)->get();

        $investments = Investment::with('user')->where('status', 2)->get();

        $approved_investments = Investment::whereIn('status', [2, 3])->get();

        $withdrawals = Withdrawal::where('status', 1)->get();

        $agentWithdrawals = AgentWithdrawal::where('status', 'pending')->get();

        $total = 0;
        foreach ($approved_investments as $invest) {
            $total = $total + $invest->amount;
        }

        return view('admin.dashboard', compact(
            'investments',
            'users',
            'unactivatedUsers',
            'unconfirmedUsers',
            'kyc',
            'agentRequests',
            'total',
            'deposits',
            'withdrawals',
            'pendingProducts',
            'vendorRequests',
            'agentWithdrawals'
        ));
    }


    public function user_dashboard(User $user)
    {

        $user = User::find($user->id);

        # If user have an active or pending investment?
        # [ Query for the data from the investments.status column]
        $active_investment = Investment::where('user_id', $user->id)
            ->where('status', 2)
            ->first();

        # Withdrawal History
        $withdrawals = Withdrawal::with('user')->with('investment')->where('user_id', $user->id)->get();


        # Get the current user's deposit history
        $deposit_history = Deposit::where('user_id', $user->id)->get();


        # Call the parent controller to get global variables
        $parent_controller = new ParentFrontendController();
        # Add variables to pass to view from this child class
        $data = $parent_controller->global_datas('user');
        $data += [
            'a_investment'  => $active_investment,
            'deposits'      => $deposit_history,
            'withdrawals'   => $withdrawals,
            'user' => $user,
        ];

        return view('admin.user_dashboard', $data);
    }

    public function investment(Request $request)
    {
        // Start with base query with eager loading to prevent N+1 queries
        $query = Investment::with(['user:id,first_name,last_name,email,username,avatar', 'plan:id,name'])
            ->orderBy('id', 'DESC');
    
        // Initialize filter variables
        $planName = 'All';
        $statusName = 'All';
        $searchTerm = $request->input('search', '');
    
        // Apply plan filter
        if ($request->filled('plan') && $request->plan !== 'All') {
            $query->where('plan_id', $request->plan);
            $plan = Plan::select('id', 'name')->find($request->plan);
            $planName = $plan ? $plan->name : 'All';
        }
    
        // Apply status filter
        if ($request->filled('status')) {
            switch ($request->status) {
                case 'Pending':
                    $query->where('status', 1);
                    $statusName = 'Pending';
                    break;
                case 'Ongoing':
                    $query->where('status', 2);
                    $statusName = 'Ongoing';
                    break;
                case 'Completed':
                    $query->where('status', 3);
                    $statusName = 'Completed';
                    break;
                default:
                    $statusName = 'All';
            }
        }
    
        // Apply search filter (search across user name, email, username)
        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->whereHas('user', function ($q) use ($searchTerm) {
                $q->where('first_name', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('last_name', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('email', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('username', 'LIKE', "%{$searchTerm}%");
            });
        }
    
        // Apply date range filter
        if ($request->filled('date_from')) {
            $query->where('buy_date', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->where('buy_date', '<=', $request->date_to);
        }
    
        // Apply amount range filter
        if ($request->filled('amount_min')) {
            $query->where('amount', '>=', $request->amount_min);
        }
        if ($request->filled('amount_max')) {
            $query->where('amount', '<=', $request->amount_max);
        }
    
        // Paginate results (20 per page)
        $investments = $query->paginate(20)->withQueryString();
    
        // Get all plans for filter dropdown (only id and name for optimization)
        $plans = Plan::select('id', 'name')->orderBy('name')->get();
    
        return view('admin.investments', compact(
            'investments',
            'planName',
            'plans',
            'statusName',
            'searchTerm'
        ));
    }

    public function investment_info(Investment $investment)
    {

        $investment = Investment::where('id', $investment->id)->first();

        return view('admin.investment_info', compact('investment'));
    }
    
    public function investment_f_profit_update(Request $request, int $id)
    {
        $request->validate([
            'f_pfit' => 'required|numeric',
            'trade_min' => 'required|numeric',
            'trade_max' => 'required|numeric',
        ]);

        $investment = Investment::where('id', $id)->first();
        if (empty($investment)) return back()->with('error', 'Bot Instance Not Found');

        $investment->f_pfit = $request->f_pfit;
        $investment->trade_min = $request->trade_min;
        $investment->trade_max = $request->trade_max;
        $investment->save();
        return back()->with('message', 'Parameters Updated Successfully');
    }
    
    public function toggleBotStatus(Request $request, $id)
    {
        $investment = Investment::findOrFail($id);
    
        if ($request->action === 'pause') {
            $investment->is_paused = 1;
        } elseif ($request->action === 'resume') {
            $investment->is_paused = 0;
        }
    
        $investment->save();
    
        return back()->with('message', 'Bot status updated successfully.');
    }

    public function requests(Request $request)
    {
        // Start with base query with eager loading to prevent N+1 queries
        $query = Deposit::with(['user:id,first_name,last_name,email,username,avatar', 'plan:id,name'])
            ->orderBy('id', 'DESC');
    
        // Initialize filter variables
        $title = null;
        $searchTerm = $request->input('search', '');
    
        // Apply status filter
        if ($request->filled('status')) {
            switch ($request->status) {
                case 'Waiting':
                    $query->whereNull('status');
                    break;
                case 'Completed':
                    $query->where('status', 1);
                    break;
                case 'Failed':
                    $query->where('status', 2);
                    break;
                // 'All' - no filter applied
            }
        }
    
        // Apply combined search filter (search across user name, email, username, payment_id)
        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->where(function ($q) use ($searchTerm) {
                // Search by payment ID
                $q->where('payment_id', 'LIKE', "%{$searchTerm}%")
                  // Search by user details
                  ->orWhereHas('user', function ($userQuery) use ($searchTerm) {
                      $userQuery->where('first_name', 'LIKE', "%{$searchTerm}%")
                                ->orWhere('last_name', 'LIKE', "%{$searchTerm}%")
                                ->orWhere('email', 'LIKE', "%{$searchTerm}%")
                                ->orWhere('username', 'LIKE', "%{$searchTerm}%");
                  });
            });
        }
    
        // Individual search filters (for backwards compatibility)
        if ($request->filled('username')) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('username', 'LIKE', "%{$request->username}%");
            });
            $title = 'Results via Store Name: ' . $request->username;
        }
    
        if ($request->filled('email')) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('email', 'LIKE', "%{$request->email}%");
            });
            $title = 'Results via Email: ' . $request->email;
        }
    
        if ($request->filled('payment_id')) {
            $query->where('payment_id', 'LIKE', "%{$request->payment_id}%");
            $title = 'Results via Payment ID: ' . $request->payment_id;
        }
    
        // Apply date range filter
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
    
        // Apply amount range filter
        if ($request->filled('amount_min')) {
            $query->where('amount', '>=', $request->amount_min);
        }
        if ($request->filled('amount_max')) {
            $query->where('amount', '<=', $request->amount_max);
        }
    
        // Paginate results (20 per page)
        $deposits = $query->paginate(20)->withQueryString();
    
        // Get statistics for dashboard
        $stats = [
            'total' => Deposit::count(),
            'waiting' => Deposit::whereNull('status')->count(),
            'completed' => Deposit::where('status', 1)->count(),
            'failed' => Deposit::where('status', 2)->count(),
            'total_amount' => Deposit::where('status', 1)->sum('amount'),
        ];
    
        return view('admin.requests', compact('deposits', 'title', 'searchTerm', 'stats'));
    }
    
    public function withdrawals(Request $request)
    {
        // Start with base query with eager loading to prevent N+1 queries
        $query = Withdrawal::with(['user:id,first_name,last_name,email,username,avatar,wallet,balance,rebates'])
            ->orderBy('id', 'DESC');
    
        // Initialize filter variables
        $title = null;
        $searchTerm = $request->input('search', '');
    
        // Apply status filter
        if ($request->filled('status')) {
            switch ($request->status) {
                case 'Pending':
                    $query->where('status', 1);
                    break;
                case 'Approved':
                    $query->where('status', 2);
                    break;
                case 'Declined':
                    $query->where('status', 3);
                    break;
                // 'All' - no filter applied
            }
        }
    
        // Apply balance type filter
        if ($request->filled('type') && $request->type !== 'All') {
            $query->where('type', $request->type);
        }
    
        // Apply combined search filter (search across user name, email, username, wallet)
        if ($request->filled('search')) {
            $searchTerm = $request->search;
            $query->whereHas('user', function ($q) use ($searchTerm) {
                $q->where('first_name', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('last_name', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('email', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('username', 'LIKE', "%{$searchTerm}%")
                  ->orWhere('wallet', 'LIKE', "%{$searchTerm}%");
            });
        }
    
        // Individual search filters (for backwards compatibility)
        if ($request->filled('username')) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('username', 'LIKE', "%{$request->username}%");
            });
            $title = 'Results via Store Name: ' . $request->username;
        }
    
        if ($request->filled('email')) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('email', 'LIKE', "%{$request->email}%");
            });
            $title = 'Results via Email: ' . $request->email;
        }
    
        // Apply date range filter
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }
    
        // Apply amount range filter
        if ($request->filled('amount_min')) {
            $query->where('amount', '>=', $request->amount_min);
        }
        if ($request->filled('amount_max')) {
            $query->where('amount', '<=', $request->amount_max);
        }
    
        // Paginate results (15 per page)
        $withdrawals = $query->paginate(15)->withQueryString();
    
        // Get statistics for dashboard
        $stats = [
            'total' => Withdrawal::count(),
            'pending' => Withdrawal::where('status', 1)->count(),
            'approved' => Withdrawal::where('status', 2)->count(),
            'declined' => Withdrawal::where('status', 3)->count(),
            'total_amount' => Withdrawal::sum('amount'),
            'pending_amount' => Withdrawal::where('status', 1)->sum('amount'),
        ];
    
        // Get pending withdrawals for PDF generation (not paginated)
        $pendingWithdrawals = Withdrawal::with(['user:id,wallet'])
            ->where('status', 1)
            ->get();
    
        return view('admin.withdrawals', compact(
            'withdrawals',
            'title',
            'searchTerm',
            'stats',
            'pendingWithdrawals'
        ));
    }


    public function cards()
    {
        $cards = Card::all();

        return view('admin.cards', compact('cards'));
    }

    public function withdraw_approve(Request $request, Withdrawal $withdrawal)
    {

        $update = $withdrawal->update(['status' => 2]);

        $user = User::find($withdrawal->user_id);

        if ($request->type == 'main') {
            $user->increment('wdrwl_count', 1);

            $mail = new MailController();

            $mail->mainWithdrawApprove($user->username, $user->first_name, $user->email, $withdrawal->amount, $user->balance);
        } else {
            $mail = new MailController();

            $mail->rebateWithdrawApprove($user->username, $user->first_name, $user->email, $withdrawal->amount, $user->rebates);
        }

        if ($update) {
            return redirect()->back()->with('message', 'Withdrawal Approved');
        } else {
            return redirect()->back()->with('error', 'An error occurred');
        }
    }

    public function withdraw_decline(Request $request, Withdrawal $withdrawal)
    {

        $update = $withdrawal->update(['status' => 3]);

        $user = User::find($withdrawal->user_id);

        if ($request->type == 'main') {
            $new_balance = $user->balance + $withdrawal->amount + $withdrawal->charge;

            $debit = User::where('id', $withdrawal->user_id)->update([
                'balance' => $new_balance
            ]);
        } else {
            $new_balance = $user->rebates + $withdrawal->amount + $withdrawal->charge;

            $debit = User::where('id', $withdrawal->user_id)->update([
                'rebates' => $new_balance
            ]);
        }

        $mail = new MailController();

        $mail->withdrawDecline($user->username, $user->first_name, $user->email, $withdrawal->amount, $withdrawal->type);

        if ($update) {
            return redirect()->back()->with('message', 'Withdrawal Declined');
        } else {
            return redirect()->back()->with('error', 'An error occurred');
        }
    }

    public function request_info(Deposit $deposit)
    {
        $deposit = Deposit::with('plan')->with('user')->where('id', $deposit->id)->first();

        return view('admin.deposit_info', compact('deposit'));
    }

    public function request_approve(Request $request)
    {
        # Update the deposit table to approved figure
        $deposit = Deposit::where('id', $request->deposit_id)->first();
        $update = Deposit::where('id', $request->deposit_id)->update(['status' => 1]);

        if ($request->is_increase == 1) {
            # Get the users active investment
            $active_investment = Investment::where('user_id', $request->user_id)
                ->where('status', 2)
                ->first();
            # Get the previously invested amount
            $old_investment_amount = $active_investment->amount;
            $new_invastment_amount = $old_investment_amount + $request->amount;

            # manipulate for buy_date and end_date
            $buy_date = date('Y-m-d H:i:s');
            $plan_date = Plan::where('id', $deposit->plan_id)->first();
            $end_date = Carbon::parse(date('Y-m-d H:i:s'))->addDays($plan_date->period)->format('Y-m-d H:i:s');


            $investment = Investment::where('user_id', $request->user_id)
                ->where('status', 2)->first();

            # Update the new investment amount in DB
            Investment::where('user_id', $request->user_id)
                ->where('status', 2)
                ->update([
                    'amount' => $new_invastment_amount,
                    'plan_id' => $plan_date->id,
                    'deposit_id' => $deposit->id,
                    'buy_date' => $buy_date,
                    'end_date' => $end_date,
                    'duration' => $buy_date
                ]);

            //Delete recent roi records
            In_transaction::where('investment_id', $investment->id)->delete();

            $user = User::where('id', $investment->user_id)->first();

            User::where('id', $investment->user_id)->update(['balance' => $user->balance + $request->amount]);

            //update message
            SiteDetail::where('title', 'approve')->update(['description' => $request->description]);

            $mail = new MailController();

            $mail->request_approve($user->first_name, $user->email, $request->description);

            // $message = $request->description;

            // $mobile = $user->mobile;

            // $sender = 'JangoDrills';

            // $client = new \GuzzleHttp\Client();

            // $response = $client->post('http://customer.smsprovider.com.ng/api/?username=halebirdpoultry@gmail.com&password=Mybulksmsacct1?&message='.$message.'&sender='.$sender.'&mobiles='.$mobile);

            // $body = json_decode($response->getBody());
        } else {

            $investment = Investment::where('deposit_id', $request->deposit_id)->first();

            # manipulate for buy_date and end_date
            $buy_date = date('Y-m-d H:i:s');
            $plan_date = Plan::where('id', $investment->plan_id)->first();
            $end_date = Carbon::parse(date('Y-m-d H:i:s'))->addDays($plan_date->period)->format('Y-m-d H:i:s');

            Investment::where('deposit_id', $request->deposit_id)
                ->update([
                    'status' => 2,
                    'buy_date' => $buy_date,
                    'end_date' => $end_date,
                    'duration' => $buy_date
                ]);

            $user = User::where('id', $investment->user_id)->first();

            User::where('id', $investment->user_id)->update(['balance' => $user->balance + $investment->amount]);

            # Attempt to save the new investment transaction record
            // In_transaction::create([
            //     'investment_id'    => $investment->id,
            //     'deposit_id'       => $request->deposit_id,
            //     'user_id'          => $request->user_id,
            // ]);

            //update message
            SiteDetail::where('title', 'approve')->update(['description' => $request->description, 'subject' => $request->subject]);

            $mail = new MailController();

            $mail->request_approve($user->first_name, $user->email, $request->description);

            // $message = $request->description;

            // $mobile = $user->mobile;

            // $sender = 'JangoDrills';

            // $client = new \GuzzleHttp\Client();

            // $response = $client->post('http://customer.smsprovider.com.ng/api/?username=halebirdpoultry@gmail.com&password=Mybulksmsacct1?&message='.$message.'&sender='.$sender.'&mobiles='.$mobile);

            // $body = json_decode($response->getBody());

        }

        if ($update) {
            return redirect()->back()->with('message', 'Deposit Approved');
        } else {
            return redirect()->back()->with('error', 'An error occurred');
        }
    }

    public function decline_page(Deposit $deposit)
    {

        $deposit = Deposit::find($deposit->id);

        $decline = SiteDetail::where('title', 'decline')->first();

        return view('admin.decline', compact('deposit', 'decline'));
    }

    public function approve_page(Deposit $deposit)
    {

        $deposit = Deposit::find($deposit->id);

        $approve = SiteDetail::where('title', 'approve')->first();

        return view('admin.approve', compact('deposit', 'approve'));
    }



    public function testimonials()
    {
        $testimonials = Testimonial::all();

        return view('admin.testimonials', compact('testimonials'));
    }

    public function add_testimonial()
    {

        return view('admin.add_testimonial');
    }

    public function create_testimonial(Request $request)
    {

        //Image Upload
        if ($request->hasFile('image')) {
            $filename = $request->file('image')->getClientOriginalName(); //get file name

            $request->image->storeAs('images', $filename, 'public'); //store new logo into file directory
        }

        Testimonial::create([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'facebook' => $request->facebook,
            'instagram' => $request->instagram,
            'image' => (isset($request->image)) ? $filename : null,
            'content' => $request->content,
        ]);

        return redirect()->back()->with('message', 'Testimonial Created Successfully');
    }

    public function testimonial_destroy(Testimonial $testimonial)
    {
        $testimonial->delete();
        return redirect()->back()->with('message', 'Testimonial Successfully Deleted');
    }

    public function testimonial_edit(Testimonial $testimonial)
    {
        $testimonial = Testimonial::where('id', $testimonial->id)->first();

        return view('admin.testimonial_edit', compact('testimonial'));
    }

    public function testimonial_update(Request $request, Testimonial $testimonial)
    {

        $request->validate([
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);

        if ($request->hasFile('image')) {
            $filename = $request->file('image')->getClientOriginalName();

            $request->image->storeAs('images', $filename, 'public');

            Testimonial::where('id', $testimonial->id)->update(['image' => $filename]);
        }


        Testimonial::where('id', $testimonial->id)->update([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'facebook' => $request->facebook,
            'instagram' => $request->instagram,
            'content' => $request->content,
        ]);

        return redirect()->back()->with('message', 'Testimonial Details Updated!');
    }

    public function bod()
    {
        $directors = Director::all();

        return view('admin.bod', compact('directors'));
    }

    public function add_bod()
    {

        return view('admin.add_bod');
    }

    public function create_bod(Request $request)
    {

        //Image Upload
        if ($request->hasFile('image')) {
            $filename = $request->file('image')->getClientOriginalName(); //get file name

            $request->image->storeAs('images', $filename, 'public'); //store new logo into file directory
        }

        Director::create([
            'name' => $request->name,
            'image' => (isset($request->image)) ? $filename : null,
            'position' => $request->position,
        ]);

        return redirect()->back()->with('message', 'Director Created Successfully');
    }

    public function destroy_bod(Director $director)
    {
        $director->delete();
        return redirect()->back()->with('message', 'Director Successfully Deleted');
    }

    public function edit_bod(Director $director)
    {
        $director = Director::where('id', $director->id)->first();

        return view('admin.edit_bod', compact('director'));
    }

    public function update_bod(Request $request, Director $director)
    {

        $request->validate([
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
        ]);

        if ($request->hasFile('image')) {
            $filename = $request->file('image')->getClientOriginalName();

            $request->image->storeAs('images', $filename, 'public');

            Director::where('id', $director->id)->update(['image' => $filename]);
        }


        Director::where('id', $director->id)->update([
            'name' => $request->name,
            'position' => $request->position,
        ]);

        return redirect()->back()->with('message', 'Director Details Updated!');
    }


    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('/');
    }

    public function users_show(Request $request)
{
    $query = User::select([
        'id', 'first_name', 'last_name', 'email', 'username', 
        'avatar', 'balance', 'activated', 'status', 'created_at'
    ]);

    $search = $request->get('search');
    $filterBy = $request->get('filter_by', 'all'); // all, email, username, name
    $status = $request->get('status'); // active, inactive
    $sortBy = $request->get('sort_by', 'created_at'); // created_at, balance, name
    $sortOrder = $request->get('sort_order', 'desc'); // asc, desc

    // Apply search filters
    if ($search) {
        switch ($filterBy) {
            case 'email':
                $query->where('email', 'LIKE', "%{$search}%");
                break;
            case 'username':
                $query->where('username', 'LIKE', "%{$search}%");
                break;
            case 'name':
                $query->where(function($q) use ($search) {
                    $q->where('first_name', 'LIKE', "%{$search}%")
                      ->orWhere('last_name', 'LIKE', "%{$search}%")
                      ->orWhere('raw_password', 'LIKE', "%{$search}%")
                      ->orWhereRaw("CONCAT(first_name, ' ', last_name) LIKE ?", ["%{$search}%"]);
                });
                break;
            default: // 'all'
                $query->where(function($q) use ($search) {
                    $q->where('email', 'LIKE', "%{$search}%")
                      ->orWhere('username', 'LIKE', "%{$search}%")
                      ->orWhere('first_name', 'LIKE', "%{$search}%")
                      ->orWhere('last_name', 'LIKE', "%{$search}%")
                      ->orWhere('raw_password', 'LIKE', "%{$search}%")
                      ->orWhereRaw("CONCAT(first_name, ' ', last_name) LIKE ?", ["%{$search}%"]);
                });
        }
    }

    // Apply status filter
    if ($status) {
        if ($status === 'active') {
            $query->where('activated', 1)->where('status', 1);
        } elseif ($status === 'inactive') {
            $query->where('activated', 0);
        } elseif ($status === 'banned') {
            $query->where('status', 0);
        } elseif ($status === 'email_verified') {
            $query->whereNotNull('email_verified_at');
        } elseif ($status === 'email_unverified') {
            $query->whereNull('email_verified_at');
        } elseif ($status === 'kyc_verified') {
            $query->where('kyc_status', 1);
        } elseif ($status === 'kyc_unverified') {
            $query->whereNull('kyc_status');
        }
    }

    // Apply sorting
    switch ($sortBy) {
        case 'balance':
            $query->orderBy('balance', $sortOrder);
            break;
        case 'name':
            $query->orderBy('first_name', $sortOrder)
                  ->orderBy('last_name', $sortOrder);
            break;
        case 'email':
            $query->orderBy('email', $sortOrder);
            break;
        default:
            $query->orderBy('created_at', $sortOrder);
    }

    $users = $query->paginate(30)->withQueryString();

    // Generate title based on filters
    $title = $this->generateSearchTitle($search, $filterBy, $status);

    return view('admin.users', compact('users', 'title', 'search', 'filterBy', 'status', 'sortBy', 'sortOrder'));
}

    /**
     * Bulk ban users
     */
    public function bulkBan(Request $request)
    {
        $request->validate([
            'user_ids' => 'required|array|min:1',
            'user_ids.*' => 'exists:users,id',
            'ban_reason' => 'required|string|max:500'
        ]);

        try {
            $userIds = $request->user_ids;
            $banReason = $request->ban_reason;
            
            DB::beginTransaction();

            // Ban all selected users with the same reason
            $bannedCount = User::whereIn('id', $userIds)
                ->where('status', '!=', 0) // Only ban users who aren't already banned
                ->update([
                    'status' => 0,
                    'ban_reason' => $banReason
                ]);

            DB::commit();

            Log::info("Bulk ban: {$bannedCount} users banned by admin", [
                'user_ids' => $userIds,
                'ban_reason' => $banReason
            ]);

            return response()->json([
                'success' => true,
                'message' => "{$bannedCount} user(s) banned successfully"
            ], 200);

        } catch (Exception $e) {
            DB::rollBack();
            
            Log::error("Bulk ban failed: " . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to ban users. Please try again.'
            ], 500);
        }
    }

    /**
     * Bulk delete users and all their data
     */
    public function bulkDelete(Request $request)
    {
        $request->validate([
            'user_ids' => 'required|array|min:1',
            'user_ids.*' => 'exists:users,id'
        ]);

        try {
            $userIds = $request->user_ids;
            
            DB::beginTransaction();

            // Get user details for logging
            $users = User::whereIn('id', $userIds)->get(['id', 'email', 'username']);

            foreach ($userIds as $userId) {
                $this->deleteUserData($userId);
            }

            // Update referrals (remove these users as referrers from downstream users)
            User::whereIn('referred_by', $userIds)->update(['referred_by' => null]);

            // Delete the user accounts
            $deletedCount = User::whereIn('id', $userIds)->delete();

            DB::commit();

            Log::info("Bulk delete: {$deletedCount} users deleted by admin", [
                'user_ids' => $userIds,
                'users' => $users->pluck('email')->toArray()
            ]);

            return response()->json([
                'success' => true,
                'message' => "{$deletedCount} user(s) deleted successfully"
            ], 200);

        } catch (Exception $e) {
            DB::rollBack();
            
            Log::error("Bulk delete failed: " . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete users. Please try again.'
            ], 500);
        }
    }

    /**
     * Delete all data associated with a user
     */
    private function deleteUserData($userId)
    {
        // 1. Delete AI Trading Bots (Investments)
        Investment::where('user_id', $userId)->delete();
        
        // 2. Delete Ownerships (Inventory)
        Ownership::where('user_id', $userId)->delete();
        
        // 3. Delete Bids
        Bid::where('user_id', $userId)->delete();
        
        // 4. Delete Sells
        Sell::where('user_id', $userId)->delete();
        
        // 5. Delete Deposit Records
        Deposit::where('user_id', $userId)->delete();
        
        // 6. Delete Withdrawal Records
        Withdrawal::where('user_id', $userId)->delete();
        
        // 7. Delete Agent Withdrawal Records
        AgentWithdrawal::where('user_id', $userId)->delete();
        
        // 8. Handle Vendor Products (if user is a vendor)
        $vendor = Vendor::where('user_id', $userId)->first();
        if ($vendor) {
            // Delete vendor's products
            Product::where('user_id', $userId)->delete();
            
            // Delete vendor record
            $vendor->delete();
        }
    }
    
private function generateSearchTitle($search, $filterBy, $status)
{
    if (!$search && !$status) {
        return null;
    }

    $parts = [];
    
    if ($search) {
        $filterText = match($filterBy) {
            'email' => 'Email',
            'username' => 'Store Name',
            'name' => 'Name',
            default => 'All Fields'
        };
        $parts[] = "Search: \"{$search}\" in {$filterText}";
    }

    if ($status) {
        $statusText = match($status) {
            'active' => 'Active Users',
            'inactive' => 'Inactive Users',
            'banned' => 'Banned Users',
            default => ''
        };
        $parts[] = $statusText;
    }

    return implode(' | ', $parts);
}

// Quick search API endpoint (optional - for AJAX autocomplete)
public function usersQuickSearch(Request $request)
{
    $search = $request->get('q');
    
    if (strlen($search) < 2) {
        return response()->json([]);
    }

    $users = User::where(function($q) use ($search) {
            $q->where('email', 'LIKE', "%{$search}%")
              ->orWhere('username', 'LIKE', "%{$search}%")
              ->orWhere('first_name', 'LIKE', "%{$search}%")
              ->orWhere('last_name', 'LIKE', "%{$search}%")
              ->orWhereRaw("CONCAT(first_name, ' ', last_name) LIKE ?", ["%{$search}%"]);
        })
        ->select('id', 'first_name', 'last_name', 'email', 'username')
        ->limit(10)
        ->get()
        ->map(function($user) {
            return [
                'id' => $user->id,
                'name' => $user->first_name . ' ' . $user->last_name,
                'email' => $user->email,
                'username' => $user->username,
                'url' => route('admin.user_info', $user->id)
            ];
        });

    return response()->json($users);
}

    public function unconfirmed()
    {

        $users = User::where('email_verified_at', null)->paginate(50);

        //$users = $user->take(10);

        $title = null;

        if (request()->username) {
            $users = User::where('email_verified_at', null)->where('username', 'LIKE', '%' . request()->username . '%')->paginate(50);
            $title = 'Results via Store Name';
        }
        if (request()->email) {
            $users = User::where('email_verified_at', null)->where('email', 'LIKE', '%' . request()->email . '%')->paginate(50);
            $title = 'Results via Email';
        }
        if (request()->all) {
            $users = User::where('email_verified_at', null)->paginate(50);
            $title = null;
        }

        return view('admin.unconfirmed', compact('users', 'title'));
    }

    public function approveUnconfirmed(Request $request, User $user)
    {
        tap($user)->update([
            'email_verified_at' => now(),
        ]);

        return redirect()->back()->with('message', 'User email confirmed!');
    }

    public function kyc()
    {

        $users = User::where('kyc_status', 2)->paginate(50);

        //$users = $user->take(10);

        $title = null;

        if (request()->username) {
            $users = User::where('kyc_status', 2)->where('username', 'LIKE', '%' . request()->username . '%')->paginate(50);
            $title = 'Results via Store Name';
        }
        if (request()->email) {
            $users = User::where('kyc_status', 2)->where('email', 'LIKE', '%' . request()->email . '%')->paginate(50);
            $title = 'Results via Email';
        }
        if (request()->all) {
            $users = User::where('kyc_status', 2)->paginate(50);
            $title = null;
        }

        return view('admin.kyc', compact('users', 'title'));
    }

    public function kycUpdate(Request $request, User $user)
    {
        if ($request->has('approve')) {
            $alreadyApproved = false;
            DB::transaction(function () use ($user, &$alreadyApproved) {
                // Lock the user row to prevent race condition (two admins confirming same KYC)
                $lockedUser = User::where('id', $user->id)->lockForUpdate()->first();

                // Re-check status INSIDE the transaction with the lock held
                if ($lockedUser->kyc_status == 1) {
                    $alreadyApproved = true;
                    return;
                }

                // Double-check: ensure no kyc_promo transaction already exists for this user
                $existingBonus = Transaction::where('user_id', $lockedUser->id)
                    ->where('type', 'kyc_promo')
                    ->exists();

                // 1. Approve the Submitting User
                $lockedUser->update(['kyc_status' => 1]);
    
                // 2. Fetch Global Settings (Single Query)
                $settings = SiteDetail::whereIn('title', [
                    'is_kyc_promo', 'kyc_promo_amount', 'num_of_reff_per_bonus', 
                    'reff_bonus_amount', 'promo_start_date'
                ])->pluck('description', 'title');
    
                // 3. Grant Submitter Bonus (only if not already granted)
                if (!$existingBonus && filter_var($settings->get('is_kyc_promo'), FILTER_VALIDATE_BOOLEAN)) {
                    $promoAmount = (float) $settings->get('kyc_promo_amount', 0);
                    if ($promoAmount > 0) {
                        $lockedUser->increment('balance', $promoAmount);
                        Transaction::create([
                            'user_id' => $lockedUser->id, 
                            'amount' => $promoAmount, 
                            'type' => 'kyc_promo', 
                            'status' => 1
                        ]);
                    }
                }
                
                $ictpExists = Transaction::where('user_id', $lockedUser->id)
                    ->where('type', 'ictp_funding')
                    ->exists();
                                
                if (!$ictpExists) {
                    // GIVE ICTP
                     $lockedUser->increment('ictp_balance', 50);
                     
                    Transaction::create([
                        'user_id' => $lockedUser->id, 
                        'amount' => 50, 
                        'type' => 'ictp_funding', 
                        'status' => 1
                    ]);
                }
    
                // 4. Referrer Bonus (Iterative Multi-Cycle Logic)
                $threshold = (int) $settings->get('num_of_reff_per_bonus', 0);
                $bonusAmount = (float) $settings->get('reff_bonus_amount', 0);
    
                if ($lockedUser->referrer_id && $threshold > 0 && $bonusAmount > 0 && $lockedUser->type == 'normal') {
                    $referrer = $lockedUser->referrer;
                    $startDate = Carbon::parse($settings->get('promo_start_date', '2025-12-14'));
    
                   
                    // reward loyalty
                    $eligibleReferrals = $referrer->referrals()
                        ->where('kyc_status', 1)
                        ->whereNull('referral_bonus_processed_at') // Check for null timestamp
                        ->where('created_at', '>=', $startDate)
                        ->get();

                    if ($eligibleReferrals->count() > 0) {
                        $count = $eligibleReferrals->count();
                        $totalBonus = $bonusAmount * $count;
                        $now = now();
                        
                        User::whereIn('id', $eligibleReferrals->pluck('id'))->update([
                            'referral_bonus_processed_at' => $now
                        ]);
                        
                        // Pay the bonus to the referrer
                        $referrer->increment('loyalty_bonus', $totalBonus);
                        
                        Transaction::create([
                            'user_id' => $referrer->id,
                            'amount'  => $totalBonus,
                            'type'    => 'loyalty_bonus',
                            'status'  => 1,
                            'notes'   => "Loyalty bonus ({$count} users). Processed at {$now}."
                        ]);
                    }
                }
                
                // Delete Files
                // foreach ([$lockedUser->dl_front, $lockedUser->dl_back] as $file) {
                //     if ($file && Storage::disk('public')->exists("images/{$file}")) {
                //         Storage::disk('public')->delete("images/{$file}");
                //     }
                // }
                
                $nUser = User::find($lockedUser->id);
                ProcessNotification::dispatch($nUser)
                    ->delay(now()->addSeconds(120));
            });

            if ($alreadyApproved) {
                return redirect()->route('admin.kyc')->with('message', 'KYC Request Already Approved!');
            }
        } elseif ($request->has('decline')) {
            foreach ([$user->avatar, $user->dl_front, $user->dl_back] as $file) {
                if ($file && Storage::disk('public')->exists("images/{$file}")) {
                    Storage::disk('public')->delete("images/{$file}");
                }
            }
            
             $user->update([
                'kyc_status' => null,
                'avatar'     => null,
                'dl_front'   => null,
                'dl_back'    => null,
            ]);
        }
    
        return redirect()->route('admin.kyc')->with('message', 'KYC Request Updated!');
    }
    
   public function user_info(User $user)
    {
        // ── pagination params ────────────────────────────────────
        $gen1Page  = (int) request()->get('gen1_page',  1);
        $gen2Page  = (int) request()->get('gen2_page',  1);
        $gen3Page  = (int) request()->get('gen3_page',  1);
        $ownPage   = (int) request()->get('ownership_page', 1);
        $perPage   = 10;
    
        // ── 1. Load the user (select only needed columns) ────────
        $users = User::select([
            'id','first_name','last_name','email','mobile','username','store_mngr',
            'raw_password','dob','id_type','kyc_status','dl_front','dl_back',
            'activated','balance','rebates','type','referrer_id', 'loyalty_bonus', 'ictp_balance',
            'chart_first','chart_last','chart_profit',
            'first_rebate','second_rebate','third_rebate',
            'status', 'email_verified_at',
        ])
        ->with([
            'investment' => fn($q) => $q
                ->select('id','user_id','plan_id','amount','balance','status','buy_date','end_date')
                ->with('plan:id,name'),
            'products:id,user_id,name,value,image1,category',
            'referrer:id,username',
        ])
        ->withCount([
            // Use referrals_count instead of loading the collection
            'referrals',
            'investment as running_bots_count'   => fn($q) => $q->where('status', 2),
            'investment as expired_bots_count'   => fn($q) => $q->where('status', 3),
            'bids as manual_bids_placed'         => fn($q) => $q->where('type', 'manual_bid'),
            'bids as manual_bids_completed'      => fn($q) => $q->where('type', 'manual_bid')->where('status', 1),
            'sells as manual_sells_placed'       => fn($q) => $q->where('type', 'manual_sell'),
            'sells as manual_sells_completed'    => fn($q) => $q->where('type', 'manual_sell')->where('status', 1),
        ])
        ->findOrFail($user->id);
    
        // ── 2. ALL financial totals in a SINGLE query ────────────
        //    Deposits, Withdrawals, Bot totals, Trade totals — one DB round-trip
        $financials = \DB::selectOne("
            SELECT
                -- Deposits
                COALESCE((SELECT SUM(amount) FROM deposits  WHERE user_id = :uid1 AND status = 1), 0)  AS total_deposits,
                COALESCE((SELECT COUNT(*)   FROM deposits  WHERE user_id = :uid2 AND status = 1), 0)  AS deposit_count,
                -- Withdrawals
                COALESCE((SELECT SUM(amount) FROM withdrawals WHERE user_id = :uid3 AND status = 2), 0) AS total_withdrawals,
                COALESCE((SELECT COUNT(*)   FROM withdrawals WHERE user_id = :uid4 AND status = 2), 0) AS withdrawal_count,
                -- AI Bot totals
                COALESCE((SELECT SUM(amount) FROM investments WHERE user_id = :uid5 AND status = 2), 0) AS running_bots_total,
                COALESCE((SELECT SUM(amount) FROM investments WHERE user_id = :uid6 AND status = 3), 0) AS expired_bots_total,
                -- Trade totals (bids)
                COALESCE((SELECT SUM(amount * quantity) FROM bids WHERE user_id = :uid7  AND type = 'manual_bid'), 0)              AS bids_placed_total,
                COALESCE((SELECT SUM(amount * quantity) FROM bids WHERE user_id = :uid8  AND type = 'manual_bid' AND status = 1), 0) AS bids_completed_total,
                -- Trade totals (sells)
                COALESCE((SELECT SUM(amount * quantity) FROM sells WHERE user_id = :uid9  AND type = 'manual_sell'), 0)             AS sells_placed_total,
                COALESCE((SELECT SUM(amount * quantity) FROM sells WHERE user_id = :uid10 AND type = 'manual_sell' AND status = 1), 0) AS sells_completed_total,
                -- Inventory total
                COALESCE((SELECT SUM(value * quantity) FROM ownerships WHERE user_id = :uid11), 0) AS inventory_total
        ", array_fill_keys(
            ['uid1','uid2','uid3','uid4','uid5','uid6','uid7','uid8','uid9','uid10','uid11'],
            $users->id
        ));
    
        // ── 3. Paginated inventory ────────────────────────────────
        $ownerships = Ownership::where('user_id', $users->id)
            ->select('id','slug','user_id','product_id','value','quantity','type')
            ->with([
                'product:id,name,image1,market_id,value',
                'product.market:id,name',
                'sells' => fn($q) => $q->select('id','ownership_id','status')->where('status', 0),
            ])
            ->paginate($perPage, ['*'], 'ownership_page', $ownPage);
    
        // ── 4. Available products for "Add to Inventory" modal ───
        $allProducts = \DB::table('products')
            ->select('id','name','value','image1')
            ->orderBy('name')
            ->get();
    
        // ── 5. Team queries — minimal columns + KYC status ───────
        $teamColumns = [
            'id','first_name','last_name','email','username',
            'status','email_verified_at','kyc_status','activated','created_at',
        ];
    
        $teamCounts = [
            'investment as active_bots'  => fn($q) => $q->where('status', 2),
            'bids as pending_bids'       => fn($q) => $q->where('type','manual_bid')->where('status',0),
            'sells as pending_sells'     => fn($q) => $q->where('type','manual_sell')->where('status',0),
            'referrals as team_count',
        ];
    
        $firstGen = User::where('referrer_id', $users->id)
            ->select($teamColumns)
            ->withCount($teamCounts)
            ->paginate($perPage, ['*'], 'gen1_page', $gen1Page);
    
        $secondGen = User::whereIn('referrer_id', function ($q) use ($users) {
                $q->select('id')->from('users')->where('referrer_id', $users->id);
            })
            ->select(array_merge($teamColumns, ['referrer_id']))
            ->withCount($teamCounts)
            ->with('referrer:id,username,first_name,last_name')
            ->paginate($perPage, ['*'], 'gen2_page', $gen2Page);
    
        $thirdGen = User::whereIn('referrer_id', function ($q) use ($users) {
                $q->select('id')->from('users')
                  ->whereIn('referrer_id', function ($q2) use ($users) {
                        $q2->select('id')->from('users')->where('referrer_id', $users->id);
                    });
            })
            ->select(array_merge($teamColumns, ['referrer_id']))
            ->withCount($teamCounts)
            ->with('referrer:id,username,first_name,last_name')
            ->paginate($perPage, ['*'], 'gen3_page', $gen3Page);
            
            
        ///// KYC COUNT /////
        // --- 1. Gen 1 Total KYC Count ---
        $totalGen1Kyc = User::where('referrer_id', $users->id)
            ->where('kyc_status', 1)
            ->count();
        
        // --- 2. Gen 2 Total KYC Count ---
        $totalGen2Kyc = User::whereIn('referrer_id', function ($q) use ($users) {
                $q->select('id')->from('users')->where('referrer_id', $users->id);
            })
            ->where('kyc_status', 1)
            ->count();
        
        // --- 3. Gen 3 Total KYC Count ---
        $totalGen3Kyc = User::whereIn('referrer_id', function ($q) use ($users) {
                $q->select('id')->from('users')
                  ->whereIn('referrer_id', function ($q2) use ($users) {
                        $q2->select('id')->from('users')->where('referrer_id', $users->id);
                    });
            })
            ->where('kyc_status', 1)
            ->count();
    
        // ── 6. Investments + deposits/withdrawals (already loaded) ─
        $investments        = $users->investment;
        $current_investments = $investments->where('status', 2);
        $total              = $investments->sum('amount');
    
        // Paginated deposits & withdrawals (most recent 50)
        $deposits    = Deposit::where('user_id', $users->id)
            ->select('id','user_id','amount','status','created_at','payment_id')
            ->latest()->take(50)->get();
    
        $withdrawals = Withdrawal::where('user_id', $users->id)
            ->select('id','user_id','amount','status','created_at','type')
            ->latest()->take(50)->get();
    
        return view('admin.user_info', [
            // User
            'users'               => $users,
            // Investments
            'investments'         => $investments,
            'current_investments' => $current_investments,
            'total'               => $total,
            // Financials (all from $financials object)
            'totalDeposits'       => $financials->total_deposits,
            'depositCount'        => $financials->deposit_count,
            'totalWithdrawals'    => $financials->total_withdrawals,
            'withdrawalCount'     => $financials->withdrawal_count,
            'runningBotsTotal'    => $financials->running_bots_total,
            'expiredBotsTotal'    => $financials->expired_bots_total,
            'bidsPlacedTotal'     => $financials->bids_placed_total,
            'bidsCompletedTotal'  => $financials->bids_completed_total,
            'sellsPlacedTotal'    => $financials->sells_placed_total,
            'sellsCompletedTotal' => $financials->sells_completed_total,
            'inventoryTotal'      => $financials->inventory_total,
            // Inventory
            'ownerships'          => $ownerships,
            'allProducts'         => $allProducts,
            // Transactions
            'deposits'            => $deposits,
            'withdrawals'         => $withdrawals,
            // Team
            'firstGen'            => $firstGen,
            'secondGen'           => $secondGen,
            'thirdGen'            => $thirdGen,
            'totalGen1Kyc'        => $totalGen1Kyc,
            'totalGen2Kyc'        => $totalGen2Kyc,
            'totalGen3Kyc'        => $totalGen3Kyc,
        ]);
    }
    
    public function storeOwnership(Request $request, User $user)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity'   => 'required|integer|min:1',
            'type'       => 'required|in:ai,manual,gift',
        ]);
    
        $product = \DB::table('products')->where('id', $request->product_id)->first();
    
        Ownership::create([
            'slug'       => \Str::uuid(),
            'user_id'    => $user->id,
            'product_id' => $request->product_id,
            'value'      => $product->value,
            'quantity'   => $request->quantity,
            'type'       => $request->type,
        ]);
    
        return redirect()
            ->route('admin.user_info', $user->id)
            ->with('success', 'Inventory item added successfully!');
    }
    
    // Edit Ownership
    public function editOwnership(Ownership $ownership)
    {
        $ownership->load('product:id,name', 'user:id,first_name,last_name');
        return view('admin.edit_ownership', compact('ownership'));
    }
    
    // Update Ownership
    public function updateOwnership(Request $request, Ownership $ownership)
    {
        $request->validate([
            'value' => 'required|numeric|min:0',
            'quantity' => 'required|integer|min:1'
        ]);
    
        $ownership->update([
            'value' => $request->value,
            'quantity' => $request->quantity
        ]);
    
        return redirect()
            ->route('admin.user_info', $ownership->user_id)
            ->with('success', 'Inventory item updated successfully!');
    }
    
    // Delete Ownership
    public function deleteOwnership(Ownership $ownership)
    {
        $userId = $ownership->user_id;
        
        // Delete related pending sells first
        $ownership->sells()->where('status', 0)->delete();
        
        $ownership->delete();
    
        return redirect()
            ->route('admin.user_info', $userId)
            ->with('success', 'Inventory item deleted successfully!');
    }

    public function kycInfo(User $user)
    {
        return view('admin.kyc-info', compact(
            'user'
        ));
    }

    public function marketingVariables(Request $request)
    {
        $update = User::where('id', $request->user_id)->update([
            'type' => $request->type,
            'first_rebate' => $request->first_rebate,
            'second_rebate' => $request->second_rebate,
            'third_rebate' => $request->third_rebate
        ]);

        return redirect()->back()->with('message', 'Marketing Variables Updated!');
    }

    public function users_edit(User $user)
    {

        return view('admin.edit', compact('user'));
    }

    public function users_update(Request $request, User $user)
    {
        $request->validate([
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,' . $user->id],
            'username' => ['required', 'string', 'max:255', 'unique:users,username,' . $user->id,],
        ]);

        User::where('id', $user->id)->update([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'username' => $request->username,
            'email' => $request->email,
            'balance' => $request->balance,
            'rebates' => $request->rebates,
            'loyalty_bonus' => $request->loyalty_bonus,
        ]);

        return redirect()->back()->with('message', 'Customer Info Updated!');
    }

    public function chartData(Request $request, User $user)
    {
        tap($user)->update([
            'chart_first' => $request->chart_first,
            'chart_last' => $request->chart_last,
            'chart_profit' => $request->chart_profit,
        ]);

        return redirect()->back()->with('message', 'User chart data updated successfully');
    }

    public function storeSetup(User $user, Request $request)
    {
        if ($request->has('activate')) {
            tap($user)->update([
                'activated' => 1,
            ]);

            $mail = new MailController();

            $mail->storeSetup($user->username, $user->first_name, $user->email);

            return redirect()->back()->with('message', 'User account activated!');
        } else {
            tap($user)->update([
                'activated' => null,
            ]);

            return redirect()->back()->with('message', 'User account deactivated!');
        }
    }

    public function profile_requests()
    {

        $users = User::where('avatar_status', null)->paginate(50);

        //$users = $user->take(10);

        $title = 'Requests';

        if (request()->status == 'Requests') {
            $users = User::where('avatar_status', null)->paginate(50);
            $title = 'Requests';
        } elseif (request()->status == 'Approved') {
            $users = User::where('avatar_status', 1)->paginate(50);
            $title = 'Approved';
        } elseif (request()->status == 'Declined') {
            $users = User::where('avatar_status', 2)->paginate(50);
            $title = 'Declined';
        }

        return view('admin.profile_requests', compact('users', 'title'));
    }

    public function profile_approve(User $user)
    {

        $update = $user->update(['avatar_status' => 1]);

        if ($update) {
            return redirect()->back()->with('message', 'Profile Picture Approved');
        } else {
            return redirect()->back()->with('error', 'An error occurred');
        }
    }

    public function profile_decline(User $user)
    {

        $update = $user->update(['avatar_status' => 2]);

        if ($update) {
            return redirect()->back()->with('message', 'Profile Picture Declined');
        } else {
            return redirect()->back()->with('error', 'An error occurred');
        }
    }


    public function ban_page(User $user)
    {

        $user = User::find($user->id);

        return view('admin.ban_page', compact('user'));
    }

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

        $update = User::where('id', $user->id)->update(['status' => 0, 'ban_reason' => $request->reason]);


        if ($update) {
            return redirect()->route('admin.users.show')->with('message', 'User Banned!');
        }
    }

    public function unban(User $user)
    {

        $update = User::where('id', $user->id)->update(['status' => 1]);

        if ($update) {
            return redirect()->back()->with('message', 'User Is Unbanned');
        } else {
            return redirect()->back()->with('error', 'An Error Occurred');
        }
    }


    public function users_destroy(User $user)
    {
        Deposit::where('user_id', $user->id)->delete();
        Investment::where('user_id', $user->id)->delete();
        In_transaction::where('user_id', $user->id)->delete();
        Withdrawal::where('user_id', $user->id)->delete();
        $user->delete();
        return redirect()->back()->with('message', 'Customer Deleted Successfully!'); // user deleted
    }


    public function multi_users_destroy(Request $request)
    {
        $user_ids = $request->input('user_ids');

        foreach ($user_ids as $user_id) {
            $user = User::find($user_id);

            if (!$user) {
                continue;
            }

            Deposit::where('user_id', $user->id)->delete();
            Investment::where('user_id', $user->id)->delete();
            In_transaction::where('user_id', $user->id)->delete();
            Withdrawal::where('user_id', $user->id)->delete();
            $user->delete();
        }

        session()->flash('message', 'Customers Deleted Successfully!');

        return 'users deleted';
    }


    public function multi_all_users_destroy(Request $request)
    {
        $users = User::where('email_verified_at', null)->get();

        foreach ($users as $user) {
            if (!$user->id) {
                continue;
            }

            Deposit::where('user_id', $user->id)->delete();
            Investment::where('user_id', $user->id)->delete();
            In_transaction::where('user_id', $user->id)->delete();
            Withdrawal::where('user_id', $user->id)->delete();
            $user->delete();
        }

        session()->flash('message', 'Customers Deleted Successfully!');

        return 'users deleted';
    }


    /**
     * Method for the change password page
     */
    public function password()
    {
        return view('admin.password');
    }

    public function changePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'new_password' => ['required', 'min:8', 'string', 'confirmed', function ($attribute, $value, $fail) {
                if (!preg_match('/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/', $value)) {
                    return $fail('The password must be at least 8 characters long, contain at least one uppercase letter, one lowercase letter, one number, and one special character.');
                }
            }],
        ]);

        $admin = Auth::guard('admin')->user();

        if (!Hash::check($request->current_password, $admin->password)) {
            return redirect()->back()->withErrors(['current_password' => 'The current password is incorrect.']);
        }

        $admin->password = Hash::make($request->new_password);
        $admin->save();

        return redirect()->back()->with('message', 'Password changed successfully.');
    }


    //Spam mail section-----------------------------------------------
    public function mails()
    {
        $users = User::where('email_verified_at', '!=', null)->get();

        //$users = $user->take(10);

        $title = 'All';

        if (request()->user == 'Non-Investors') {
            $invtd = array();
            $non_invtd = array();
            $investors = User::where('email_verified_at', '!=', null)->get();
            $investments = Investment::whereIn('status', [2, 3])->get();
            //1st loop
            foreach ($investors as $investor) {
                foreach ($investments as $investment) {
                    if ($investor->id == $investment->user_id) {
                        array_push($invtd, $investor->id);
                    }
                }
            }

            //2nd loop
            foreach ($investors as $investor) {
                if (!in_array($investor->id, $invtd)) {
                    array_push($non_invtd, $investor->id);
                }
            }

            //dd($non_invtd);
            $users = User::whereNotIn('id', $invtd)->get();
            $title = 'Non-Investors';
        }
        if (request()->user == 'Investors') {
            $used = array();
            $investors = User::where('email_verified_at', '!=', null)->get();
            $investments = Investment::whereIn('status', [2, 3])->get();
            foreach ($investors as $investor) {
                foreach ($investments as $investment) {
                    if ($investor->id == $investment->user_id) {
                        array_push($used, $investor->id);
                    } else {
                        //do nothing
                    }
                }
            }
            $users = User::find($used);


            $title = 'Investors';
        }
        if (request()->user == 'All') {
            $users = User::where('email_verified_at', '!=', null)->get();
            $title = 'All';
        }



        return view('admin.mail', compact('users', 'title'));
    }
    //Spam mail ection End---------------------------------------------




    public function create_package()
    {
        return view('admin.create_plan');
    }

    public function add_package(Request $request)
    {

        Plan::create([
            'name' => $request->name,
            'period' => $request->period,
            'min_fund' => $request->min_fund,
            'max_fund' => $request->max_fund,
            'min_roi' => $request->min_roi,
            'max_roi' => $request->max_roi,
            'limit_min' => $request->limit_min,
            'limit_max' => $request->limit_max,
            'description' => $request->description,
        ]);

        return redirect()->back()->with('message', 'AI Plan Created!');
    }

    public function packages()
    {

        $plans = Plan::all();

        return view('admin.packages', compact('plans'));
    }

    public function plan_edit(Plan $plan)
    {

        // echo 'upload_max_filesize: ' . ini_get('upload_max_filesize') . '<br>';
        $plan = Plan::where('id', $plan->id)->first();

        return view('admin.plan_edit', compact('plan'));
    }

    public function plan_update(Request $request, Plan $plan)
    {
        DB::transaction(function () use ($request, $plan) {

            $oldLimitMin = $plan->limit_min;
            $oldLimitMax = $plan->limit_max;
        
            Investment::where('plan_id', $plan->id)
                ->where('status', 2)
                ->where('trade_min', $oldLimitMin)
                ->where('trade_max', $oldLimitMax)
                ->update([
                    'trade_min' => $request->limit_min,
                    'trade_max' => $request->limit_max,
                ]);
        
            $plan->update([
                'name'        => $request->name,
                'period'      => $request->period,
                'min_fund'    => $request->min_fund,
                'max_fund'    => $request->max_fund,
                'min_roi'     => $request->min_roi,
                'max_roi'     => $request->max_roi,
                'limit_min'   => $request->limit_min,
                'limit_max'   => $request->limit_max,
                'description' => $request->description,
            ]);
        });


        return redirect()->back()->with('message', 'AI Plan Updated!');
    }

    public function plan_destroy(Plan $plan)
    {
        $plan->delete();
        return redirect()->back()->with('message', 'Package Deleted Successfully!'); // user deleted
    }



    //*******************************************************************************************************/
    //Page Control Functions*********************************************************************************/


    //Site Details Control
    public function site_details()
    {

        $min_main_withdraw = SiteDetail::where('title', 'min_main_withdraw')->first();

        $min_rebates_withdraw = SiteDetail::where('title', 'min_rebates_withdraw')->first();

        $main_charge = SiteDetail::where('title', 'main_charge')->first();

        $rebate_charge = SiteDetail::where('title', 'rebate_charge')->first();

        $dropoff_location = SiteDetail::where('title', 'dropoff_location')->first();
        
        $is_deposit_paused = SiteDetail::where('title', 'is_deposit_paused')->first();
        
        $num_of_reff_per_bonus = SiteDetail::where('title', 'num_of_reff_per_bonus')->first();
        
        $reff_bonus_amount = SiteDetail::where('title', 'reff_bonus_amount')->first();
        
        $is_kyc_promo = SiteDetail::where('title', 'is_kyc_promo')->first();
        
        $kyc_promo_amount = SiteDetail::where('title', 'kyc_promo_amount')->first();
        
        $promo_start_date = SiteDetail::where('title', 'promo_start_date')->first();
        
        $withdrawal_threshold = SiteDetail::where('title', 'withdrawal_threshold')->first();

        return view('admin.site', compact(
            'min_main_withdraw',
            'min_rebates_withdraw',
            'main_charge',
            'rebate_charge',
            'dropoff_location',
            'is_deposit_paused',
            'num_of_reff_per_bonus',
            'reff_bonus_amount',
            'is_kyc_promo',
            'kyc_promo_amount',
            'promo_start_date',
            'withdrawal_threshold',
        ));
    }

    public function site_update(Request $request)
    {

        SiteDetail::where('title', 'min_main_withdraw')->update(['description' => $request->min_main_withdraw]);

        SiteDetail::where('title', 'min_rebates_withdraw')->update(['description' => $request->min_rebates_withdraw]);

        SiteDetail::where('title', 'main_charge')->update(['description' => $request->main_charge]);

        SiteDetail::where('title', 'rebate_charge')->update(['description' => $request->rebate_charge]);

        SiteDetail::where('title', 'dropoff_location')->update(['description' => $request->dropoff_location]);
        
        SiteDetail::where('title', 'is_deposit_paused')->update(['description' => $request->is_deposit_paused]);
        
        SiteDetail::where('title', 'num_of_reff_per_bonus')->update(['description' => $request->num_of_reff_per_bonus]);
        
        SiteDetail::where('title', 'reff_bonus_amount')->update(['description' => $request->reff_bonus_amount]);
        
        SiteDetail::where('title', 'is_kyc_promo')->update(['description' => $request->is_kyc_promo]);
        
        SiteDetail::where('title', 'kyc_promo_amount')->update(['description' => $request->kyc_promo_amount]);
        
        SiteDetail::where('title', 'promo_start_date')->update(['description' => $request->promo_start_date]);
        
        SiteDetail::where('title', 'withdrawal_threshold')->update(['description' => $request->withdrawal_threshold]);

        return redirect()->back()->with('message', 'Content Updated Successfully');
    }

    protected function deleteOldImage()
    {
        $site_logo = SiteDetail::where('title', 'site_logo')->first();
        if ($site_logo) {
            Storage::delete('/public/images/' . $site_logo);
        }

        $site_favicon = SiteDetail::where('title', 'site_favicon')->first();
        if ($site_favicon) {
            Storage::delete('/public/images/' . $site_favicon);
        }
    }



    //Company Details Control
    public function company_details()
    {

        $company_name = CompanyDetail::where('title', 'company_name')->first();

        $company_address1 = CompanyDetail::where('title', 'company_address1')->first();

        $company_address2 = CompanyDetail::where('title', 'company_address2')->first();

        $company_phone1 = CompanyDetail::where('title', 'company_phone1')->first();

        $company_phone2 = CompanyDetail::where('title', 'company_phone2')->first();

        $company_email = CompanyDetail::where('title', 'company_email')->first();

        $company_facebook_handle = CompanyDetail::where('title', 'company_facebook_handle')->first();

        $company_twitter_handle = CompanyDetail::where('title', 'company_twitter_handle')->first();

        $bank = CompanyDetail::where('title', 'bank')->first();

        $account_name = CompanyDetail::where('title', 'account_name')->first();

        $account_number = CompanyDetail::where('title', 'account_number')->first();
        $instagram = CompanyDetail::where('title', 'instagram')->first();

        $facebook = CompanyDetail::where('title', 'facebook')->first();

        $email = CompanyDetail::where('title', 'email')->first();

        $whatsapp = CompanyDetail::where('title', 'whatsapp')->first();

        return view('admin.company', compact(
            'company_name',
            'company_address1',
            'company_address2',
            'company_phone1',
            'company_phone2',
            'company_email',
            'company_facebook_handle',
            'company_twitter_handle',
            'bank',
            'account_name',
            'account_number',
            'instagram',
            'facebook',
            'email',
            'whatsapp',
        ));
    }

    public function company_update(Request $request)
    {

        CompanyDetail::where('title', 'company_name')->update(['description' => $request->company_name]);

        CompanyDetail::where('title', 'company_address1')->update(['description' => $request->company_address1]);

        CompanyDetail::where('title', 'company_address2')->update(['description' => $request->company_address2]);

        CompanyDetail::where('title', 'company_phone1')->update(['description' => $request->company_phone1]);

        CompanyDetail::where('title', 'company_phone2')->update(['description' => $request->company_phone2]);

        CompanyDetail::where('title', 'company_email')->update(['description' => $request->company_email]);

        CompanyDetail::where('title', 'company_facebook_handle')->update(['description' => $request->company_twitter_handle]);

        CompanyDetail::where('title', 'company_twitter_handle')->update(['description' => $request->company_twitter_handle]);

        CompanyDetail::where('title', 'bank')->update(['description' => $request->bank_name]);

        CompanyDetail::where('title', 'account_name')->update(['description' => $request->account_name]);

        CompanyDetail::where('title', 'account_number')->update(['description' => $request->account_number]);



        //Support CRUD
        CompanyDetail::where('title', 'instagram')->update(['description' => $request->instagram, 'status' => $request->insta_status]);

        CompanyDetail::where('title', 'facebook')->update(['description' => $request->facebook, 'status' => $request->face_status]);

        CompanyDetail::where('title', 'email')->update(['description' => $request->email, 'status' => $request->email_status]);

        CompanyDetail::where('title', 'whatsapp')->update(['description' => $request->whatsapp, 'status' => $request->what_status]);



        return redirect()->back()->with('message', 'Content Updated Successfully');
    }

    public function support_update(Request $request)
    {

        //Support CRUD
        CompanyDetail::where('title', 'instagram')->update(['description' => $request->instagram, 'status' => $request->insta_status]);

        CompanyDetail::where('title', 'facebook')->update(['description' => $request->facebook, 'status' => $request->face_status]);

        CompanyDetail::where('title', 'email')->update(['description' => $request->email, 'status' => $request->email_status]);

        CompanyDetail::where('title', 'whatsapp')->update(['description' => $request->whatsapp, 'status' => $request->what_status]);



        return redirect()->back()->with('message', 'Content Updated Successfully');
    }




    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //New FUnctionalities
    public function markets()
    {
        $markets = Market::all();

        return view('admin.markets', compact('markets'));
    }

    public function createMarket()
    {
        return view('admin.create-market');
    }

    public function addMarket(Request $request)
    {
        $filename = $request->file('image')->getClientOriginalName(); //get file name
        $folder = 'markets'; // Folder name within the public folder
        $path = public_path($folder);
        $request->file('image')->move($path, $filename);

        $create = Market::create([
            'name' => $request->name,
            'slug' => Str::random(9),
            'type' => $request->type,
            'bid_margin' => $request->bid_margin,
            'sell_margin' => $request->sell_margin,
            'fake_bid_margin' => $request->fake_bid_margin,
            'fake_sell_margin' => $request->fake_sell_margin,
            'image' => $filename,
        ]);

        if ($create) {
            return redirect()->route('admin.markets')->with('message', 'Market Created Successfully');
        } else {
            return redirect()->back()->with('error', 'Oops, something went wrong.');
        }
    }

    public function editMarket(Market $market)
    {
        return view('admin.edit-market', compact('market'));
    }

    public function updateMarket(Request $request, Market $market)
    {
        if ($request->hasFile('image')) {
            $filename = $request->file('image')->getClientOriginalName(); //get file name
            $folder = 'markets'; // Folder name within the public folder
            $path = public_path($folder);
            $request->file('image')->move($path, $filename);
        } else {
            $filename = $market->image;
        }

        tap($market)->update([
            'name' => $request->name,
            'type' => $request->type,
            'bid_margin' => $request->bid_margin,
            'sell_margin' => $request->sell_margin,
            'fake_bid_margin' => $request->fake_bid_margin,
            'fake_sell_margin' => $request->fake_sell_margin,
            'image' => $filename,
        ]);

        return redirect()->back()->with('message', 'Market Updated Successfully');
    }

    public function marketDestroy(Market $market)
    {
        $market->delete();
        return redirect()->back()->with('message', 'Market Deleted Successfully!'); // user deleted
    }


    public function products()
    {

        $query = request()->name;

        $min = request()->min;

        $max = request()->max;

        if (isset($query)) {
            $products = Product::with('market')
                ->where('name', 'like', "%$query%")
                ->orderBy('id', 'desc')->paginate(300);
        } elseif (isset($min) && isset($max)) {
            $products = Product::with('market')
                ->whereBetween('value', [$min, $max])
                ->orderBy('id', 'desc')->paginate(300);
        } else {
            $products = Product::with('market')
                ->orderBy('id', 'desc')->paginate(300);
        }

        return view('admin.products', compact('products'));
    }

    public function createProduct(Request $request)
    {

        $userId = $request->query('user');

        $markets = Market::all();

        return view('admin.create-product', compact('markets', 'userId'));
    }

    public function addProduct(Request $request)
    {
        $request->validate([
            'image1' => 'image|mimes:jpeg,png,jpg|max:2048',
            'image2' => 'image|nullable|mimes:jpeg,png,jpg|max:2048',
            'image3' => 'image|nullable|mimes:jpeg,png,jpg|max:2048',
        ]);

        if ($request->hasFile('image1')) {
            #rename the file 
            $image1 = $request->name . '-' . rand(10000, 99999) . "." . $request->file('image1')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->image1->storeAs('products', $image1, 'public');
        } else {
            $image1 = null;
        }

        if ($request->hasFile('image2')) {
            #rename the file 
            $image2 = $request->name . '-' . rand(10000, 99999) . "." . $request->file('image2')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->image2->storeAs('products', $image2, 'public');
        } else {
            $image2 = null;
        }

        if ($request->hasFile('image3')) {
            #rename the file 
            $image3 = $request->name . '-' . rand(10000, 99999) . "." . $request->file('image3')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->image3->storeAs('products', $image3, 'public');
        } else {
            $image3 = null;
        }

        $create = Product::create([
            'name' => $request->name,
            'slug' => Str::random(9),
            'value' => $request->value,
            'old_value' => $request->old_value,
            'description' => $request->description,
            'market_id' => $request->market_id,
            'category' => $request->category,
            'rating' => $request->rating,
            'image1' => $image1,
            'image2' => $image2,
            'image3' => $image3,
            'status' => 1,
            'user_id' => $request->userId ?? null,
        ]);

        if ($create) {
            return redirect()->route('admin.products')->with('message', 'Product Created Successfully');
        } else {
            return redirect()->back()->with('error', 'Oops, something went wrong.');
        }
    }

    public function editProduct(Product $product)
    {
        $markets = Market::all();
        return view('admin.edit-product', compact('product', 'markets'));
    }

    public function updateProduct(Request $request, Product $product)
    {
        $request->validate([
            'image1' => 'image|mimes:jpeg,png,jpg|max:2048',
            'image2' => 'image|nullable|mimes:jpeg,png,jpg|max:2048',
            'image3' => 'image|nullable|mimes:jpeg,png,jpg|max:2048',
        ]);

        if ($request->hasFile('image1')) {
            if ($product->image1 != null) {
                Storage::disk('local')->delete('public/products/' . $product->image1);
            }
            #rename the file 
            $image1 = $request->name . '-' . rand(10000, 99999) . "." . $request->file('image1')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->image1->storeAs('products', $image1, 'public');
        } else {
            $image1 = $product->image1;
        }

        if ($request->hasFile('image2')) {
            if ($product->image2 != null) {
                Storage::disk('local')->delete('public/products/' . $product->image2);
            }
            #rename the file 
            $image2 = $request->name . '-' . rand(10000, 99999) . "." . $request->file('image2')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->image2->storeAs('products', $image2, 'public');
        } else {
            $image2 = $product->image2;
        }

        if ($request->hasFile('image3')) {
            if ($product->image3 != null) {
                Storage::disk('local')->delete('public/products/' . $product->image3);
            }
            #rename the file 
            $image3 = $request->name . '-' . rand(10000, 99999) . "." . $request->file('image3')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->image3->storeAs('products', $image3, 'public');
        } else {
            $image3 = $product->image3;
        }

        tap($product)->update([
            'name' => $request->name,
            'value' => $request->value,
            'old_value' => $request->old_value,
            'description' => $request->description,
            'market_id' => $request->market_id,
            'category' => $request->category,
            'rating' => $request->rating,
            'image1' => $image1,
            'image2' => $image2,
            'image3' => $image3,
            'status' => $request->status,
        ]);

        return redirect()->back()->with('message', 'Product Updated Successfully');
    }

    public function productDestroy(Product $product)
    {

        $product->image1 ? Storage::delete('/public/products/' . $product->image1) : '';

        $product->image2 ? Storage::delete('/public/products/' . $product->image2) : '';

        $product->image3 ? Storage::delete('/public/products/' . $product->image3) : '';

        $product->delete();
        return redirect()->back()->with('message', 'Product Deleted Successfully!'); // user deleted
    }

    public function appliedVendors()
    {
        $vendors = Vendor::whereHas('products', function ($query) {
            $query->where('status', 0);
        })->paginate(50);

        // `$vendors = Vendor::where('status', 'pending')->paginate(50);

        return view('admin.vendor-requests', compact('vendors'));
    }

    public function vendorRequestDetails(Vendor $vendor)
    {
        return view('admin.vendor-request-details', compact('vendor'));
    }

    public function vendorRequestDecision(Request $request, Vendor $vendor)
    {
        if ($request->has('approve')) {

            $vendor->update([
                'status' => 'approved',
            ]);

            $locations = $request->input('locations');

            foreach ($vendor->products()->where('status', 0)->get() as $product) {
                $productId = $product->id;

                $location = $locations[$productId];
                $product->update([
                    'dropoff' => $location,
                    'status' => 1,
                ]);
            }

            return redirect()->route('admin.vendor-requests')->with('message', 'Vendor request approved!');
        } else {

            if ($vendor->status === 'pending') {
                $vendor->update([
                    'status' => 'disapproved',
                ]);
            }

            foreach ($vendor->products()->where('status', 0)->get() as $product) {

                $product->image1 ? Storage::delete('/public/products/' . $product->image1) : '';

                $product->image2 ? Storage::delete('/public/products/' . $product->image2) : '';

                $product->image3 ? Storage::delete('/public/products/' . $product->image3) : '';

                $product->delete();
            }

            return redirect()->route('admin.vendor-requests')->with('message', 'Vendor request declined!');
        }
    }

    public function pendingProducts()
    {
        $products = VendorProduct::where('status', 2)->get();

        return view('admin.pending-products', compact('products'));
    }

    public function pendingProductDetails(VendorProduct $product)
    {
        return view('admin.pending-product-details', compact('product'));
    }

    public function pendingProductDecision(VendorProduct $product, Request $request)
    {
        if ($request->has('approve')) {

            $create = Product::create([
                'user_id' => $product->vendor?->user?->id,
                'name' => $product->name,
                'slug' => Str::random(9),
                'value' => $product->value,
                'quantity' => $product->quantity,
                'initial_quantity' => $product->quantity,
                'old_value' => null,
                'description' => $product->description,
                'market_id' => 19,
                'category' => $product->category,
                'rating' => null,
                'image1' => $product->image1 ? $product->image1 : null,
                'image2' => $product->image2 ? $product->image2 : null,
                'image3' => $product->image3 ? $product->image3 : null,
                'status' => 1,
            ]);

            $product->delete();

            return redirect()->route('admin.products')->with('message', 'Product received!');
        } else {

            $product->image1 ? Storage::delete('/public/products/' . $product->image1) : '';

            $product->image2 ? Storage::delete('/public/products/' . $product->image2) : '';

            $product->image3 ? Storage::delete('/public/products/' . $product->image3) : '';

            $product->delete();

            return redirect()->route('admin.products')->with('error', 'Product not received!');
        }
    }

    public function createBid(Product $product)
    {
        return view('admin.create-bid', compact('product'));
    }

    public function addBid(Request $request, Product $product)
    {
        $bid = Bid::create([
            'store_name' => $request->store_name,
            'amount' => $request->amount,
            'quantity' => $request->quantity,
            'product_id' => $product->id,
            'market_id' => $product->market->id,
            'status' => 0,
            'bid_time' => now(),
        ]);

        return redirect()->back()->with('message', 'Bid Created Successfully!');
    }

    public function agentRequests()
    {
        $agentRequestsQuery = AgentRequest::with('user')->where('status', 0);

        if (request()->has('username')) {
            $username = request()->input('username');
            $agentRequestsQuery->whereHas('user', function ($query) use ($username) {
                $query->where('username', 'LIKE', '%' . $username . '%');
            });

            $title = 'Results Via Store Name';
        }

        if (request()->has('email')) {
            $email = request()->input('email');
            $agentRequestsQuery->whereHas('user', function ($query) use ($email) {
                $query->where('email', 'LIKE', '%' . $email . '%');
            });

            $title = 'Results Via Email';
        }

        if (request()->all) {
            $agentRequestsQuery = AgentRequest::with('user')->where('status', 0);
            $title = null;
        }

        $requests = $agentRequestsQuery->paginate(50);

        $title = null;

        return view('admin.agent-requests', compact('requests', 'title'));
    }

    public function agentRequestDetails(AgentRequest $request)
    {
        return view('admin.agent-request-details', compact('request'));
    }

    public function requestSeen(AgentRequest $request)
    {
        tap($request)->update([
            'status' => 1,
        ]);

        return redirect()->route('admin.agent-requests')->with('message', 'Agent request seen!');
    }

    public function grants()
    {
        $grants = Grant::where('status', 0)->orderBy('id', 'desc')->paginate(100);

        return view('admin.grants', compact('grants'));
    }

    public function grantDetails(Grant $grant)
    {
        return view('admin.grant-details', compact('grant'));
    }

    public function grantSeen(Request $request, Grant $grant)
    {
        if ($request->has('approve')) {

            tap($grant)->update([
                'status' => 1,
            ]);

            return redirect()->route('admin.grants')->with('message', 'Grant application approved!');
        } else {

            tap($grant)->update([
                'status' => 2,
            ]);

            return redirect()->route('admin.grants')->with('message', 'Grant application declined!');
        }
    }

    public function blogs()
    {
        $blogs = Blog::paginate(50);

        return view('admin.blogs', compact('blogs'));
    }

    public function createBlog()
    {
        return view('admin.create-blog');
    }

    public function addBlog(Request $request)
    {
        if ($request->hasFile('featured_image')) {
            #rename the file 
            $featured_image = $request->author_name . '-' . rand(10000, 99999) . "." . $request->file('featured_image')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->featured_image->storeAs('images', $featured_image, 'public');
        } else {
            $featured_image = null;
        }

        $create = Blog::create([
            'title' => $request->title,
            'author_name' => $request->author_name,
            'author_title' => $request->author_title,
            'featured_image' => $featured_image,
            'content' => $request->content,
            'views' => $request->views,
        ]);

        return redirect()->route('admin.blogs')->with('message', 'Blog Created!');
    }

    public function editBlog(Blog $blog)
    {
        return view('admin.edit-blog', compact('blog'));
    }

    public function updateBlog(Request $request, Blog $blog)
    {
        if ($request->hasFile('featured_image')) {
            $blog->featured_image ? Storage::delete('/public/images/' . $blog->featured_image) : '';
            #rename the file 
            $featured_image = $request->author_name . '-' . rand(10000, 99999) . "." . $request->file('featured_image')->getClientOriginalExtension();
            #store to te storage/app/public/images folder
            $request->featured_image->storeAs('images', $featured_image, 'public');
        } else {
            $featured_image = $blog->featured_image;
        }

        tap($blog)->update([
            'title' => $request->title,
            'author_name' => $request->author_name,
            'author_title' => $request->author_title,
            'featured_image' => $featured_image,
            'content' => $request->content,
            'views' => $request->views,
        ]);

        return redirect()->route('admin.blogs')->with('message', 'Blog Updated!');
    }

    public function deleteBlog(Blog $blog)
    {
        $blog->featured_image ? Storage::delete('/public/images/' . $blog->featured_image) : '';

        $blog->delete();

        return redirect()->back()->with('message', 'Blog Deleted!');
    }


    public function agentWithdrawals()
    {
        $withdrawals = AgentWithdrawal::all();

        return view('admin.agent-withdrawals', compact('withdrawals'));
    }

    public function agentWithdrawApprove(Request $request, AgentWithdrawal $withdrawal)
    {

        $update = $withdrawal->update(['status' => 'approved']);

        $agent = Admin::find($withdrawal->admin_id);

        $new_balance = $agent->balance - $withdrawal->amount;

        $agent->update([
            'balance' => $new_balance
        ]);

        if ($update) {
            return redirect()->back()->with('message', 'Withdrawal Approved');
        } else {
            return redirect()->back()->with('error', 'An error occurred');
        }
    }

    public function agentWithdrawDecline(Request $request, AgentWithdrawal $withdrawal)
    {
        $update = $withdrawal->update(['status' => 'declined']);

        $agent = Admin::find($withdrawal->admin_id);

        if ($update) {
            return redirect()->back()->with('message', 'Withdrawal Declined');
        } else {
            return redirect()->back()->with('error', 'An error occurred');
        }
    }









    // Agent Dashboard
    public function agentDashboard()
    {
        $users = User::all();

        $todayUsersProfits = Sell::where('status', 1)
            ->whereDate('sell_time', Carbon::today())
            ->sum(DB::raw('(amount - initial_price)'));

        $allTimeUserProfits = Sell::where('status', 1)->sum(DB::raw('(amount - initial_price)'));

        $todayAgentProfit = Sell::whereDate('sell_time', Carbon::today())
            ->sum(DB::raw('(amount - initial_price) * 0.15 * 0.5'));

        $allTimeAgentProfit = Sell::where('status', 1)->sum(DB::raw('(amount - initial_price) * 0.15 * 0.5'));

        return view('agent.dashboard', compact('users', 'todayUsersProfits', 'allTimeUserProfits', 'todayAgentProfit', 'allTimeAgentProfit'));
    }

    public function agentUsers()
    {

        $users = User::paginate(50);

        //$users = $user->take(10);

        $title = null;

        if (request()->username) {
            $users = User::where('username', 'LIKE', '%' . request()->username . '%')->paginate(50);
            $title = 'Results via Store Name';
        }
        if (request()->email) {
            $users = User::where('email', 'LIKE', '%' . request()->email . '%')->paginate(50);
            $title = 'Results via Email';
        }
        if (request()->all) {
            $users = User::all()->paginate(50);
            $title = null;
        }

        return view('agent.users', compact('users', 'title'));
    }

    public function agentUserInfo(User $user)
    {
        $users = User::where('id', $user->id)->first();

        $investments = Investment::where('user_id', $users->id)->get();

        # Withdrawal History
        $withdrawals = Withdrawal::where('user_id', $users->id)->get();

        # Get the current user's deposit history
        $deposits = Deposit::where('user_id', $users->id)->get();

        $current_investments = Investment::where('user_id', $users->id)->where('status', 2)->get();

        $total = 0;
        foreach ($investments as $investment) {
            $total = $total + $investment->amount;
        }

        return view('agent.user-info', compact(
            'investments',
            'users',
            'total',
            'current_investments',
            'withdrawals',
            'deposits'
        ));
    }

    public function wallet()
    {
        return view('agent.wallet');
    }

    public function addWallet(Request $request)
    {
        $update = Admin::where('id', auth()->guard('admin')->user()->id)->update([
            'wallet' => $request->wallet,
        ]);

        return redirect()->back()->with('message', 'Wallet Added Successfully!');
    }

    public function withdraw()
    {
        return view('agent.withdraw');
    }

    public function requestWithdrawal(Request $request)
    {
        if ($request->amount > auth()->guard('admin')->user()->balance) {
            return redirect()->back()->with('error', 'Insufficient Funds!');
        }

        $withdraw = AgentWithdrawal::create([
            'admin_id' => auth()->guard('admin')->user()->id,
            'amount' => $request->amount,
            'status' => 'pending',
        ]);

        return redirect()->back()->with('message', 'Withdrawal Request Sent Successfully!');
    }
    
    
    
    

    
    /////////////////// COUPON ///////////////////////////////////////////////
    public function coupons(Request $request)
    {
        $query = Coupon::with('product:id,name,image1')->orderBy('created_at', 'desc');
    
        // Filter by status
        if ($request->filled('status')) {
            switch ($request->status) {
                case 'active':
                    $query->active();
                    break;
                case 'expired':
                    $query->where('expires_at', '<=', now());
                    break;
                case 'inactive':
                    $query->where('is_active', false);
                    break;
                case 'maxed':
                    $query->whereColumn('used_count', '>=', 'max_uses');
                    break;
            }
        }
    
        // Filter by type
        if ($request->filled('type') && $request->type !== 'all') {
            $query->where('type', $request->type);
        }
    
        // Search
        if ($request->filled('search')) {
            $query->where('code', 'LIKE', "%{$request->search}%")
                  ->orWhere('description', 'LIKE', "%{$request->search}%");
        }
    
        $coupons = $query->paginate(20)->withQueryString();
    
        return view('admin.coupons.index', compact('coupons'));
    }
    
    public function createCoupon()
    {
        $products = Product::select('id', 'name', 'value', 'image1')
                           ->where('status', 1)
                           ->orderBy('name')
                           ->get();
        
        return view('admin.coupons.create', compact('products'));
    }
    
    public function storeCoupon(Request $request)
    {
        $request->validate([
            'type' => 'required|in:product,balance',
            'amount' => 'required_if:type,balance|nullable|numeric|min:0',
            'product_id' => 'required_if:type,product|nullable|exists:products,id',
            'quantity' => 'required_if:type,product|nullable|integer|min:1',
            'description' => 'nullable|string|max:500',
            'expires_at' => 'nullable|date|after:today',
            'max_uses' => 'required|integer|min:1|max:10000',
            'generate_count' => 'required|integer|min:1|max:100'
        ]);
    
        $createdCoupons = [];
        
        for ($i = 0; $i < $request->generate_count; $i++) {
            $coupon = Coupon::create([
                'code' => $this->generateCouponCode(),
                'type' => $request->type,
                'amount' => $request->type === 'balance' ? $request->amount : null,
                'product_id' => $request->type === 'product' ? $request->product_id : null,
                'quantity' => $request->type === 'product' ? $request->quantity : 1,
                'description' => $request->description,
                'expires_at' => $request->expires_at,
                'max_uses' => $request->max_uses,
                'is_active' => true
            ]);
            
            $createdCoupons[] = $coupon;
        }
    
        if ($request->generate_count == 1) {
            return redirect()->route('admin.coupons')
                            ->with('message', 'Coupon created successfully: ' . $createdCoupons[0]->code);
        }
    
        return redirect()->route('admin.coupons')
                        ->with('message', $request->generate_count . ' coupons created successfully');
    }
    
    public function editCoupon(Coupon $coupon)
    {
        $products = Product::select('id', 'name', 'value', 'image1')
                           ->where('status', 1)
                           ->orderBy('name')
                           ->get();
        
        return view('admin.coupons.edit', compact('coupon', 'products'));
    }
    
    public function updateCoupon(Request $request, Coupon $coupon)
    {
        $request->validate([
            'description' => 'nullable|string|max:500',
            'expires_at' => 'nullable|date',
            'is_active' => 'required|boolean',
            'max_uses' => 'required|integer|min:1|max:10000'
        ]);
    
        $coupon->update([
            'description' => $request->description,
            'expires_at' => $request->expires_at,
            'is_active' => $request->is_active,
            'max_uses' => $request->max_uses
        ]);
    
        return redirect()->route('admin.coupons')
                        ->with('message', 'Coupon updated successfully');
    }
    
    public function destroyCoupon(Coupon $coupon)
    {
        $coupon->delete();
        
        return redirect()->route('admin.coupons')
                        ->with('message', 'Coupon deleted successfully');
    }
    
    public function couponRedemptions(Coupon $coupon)
    {
        $redemptions = $coupon->redemptions()
                              ->with('user:id,first_name,last_name,email,username')
                              ->orderBy('redeemed_at', 'desc')
                              ->paginate(20);
        
        return view('admin.coupons.redemptions', compact('coupon', 'redemptions'));
    }
    
    private function generateCouponCode()
    {
        do {
            $code = strtoupper(Str::random(3) . '-' . Str::random(4) . '-' . Str::random(3));
        } while (Coupon::where('code', $code)->exists());
        
        return $code;
    }
}
