<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Investment;
use App\Models\Transaction;
use Illuminate\Http\Request;

class MarketerController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(){
        $this->middleware(['auth', 'verified', 'banned', 'activated']);
    }

    public function marketer()
    {
        if(auth()->user()->type != 'marketer'){
            return redirect()->route('home')->with('error', 'Sorry, you do not have access to the Marketers Dashboard.');
        }

        $team = [];
        $first = [];
        $second = [];
        $third = [];

        foreach(auth()->user()->referrals as $st_gen){
                array_push($team, $st_gen->id);
                array_push($first, $st_gen->id);
        }

        foreach(auth()->user()->referrals as $st_gen){
            foreach($st_gen->referrals as $nd_gen){
                array_push($team, $nd_gen->id);
                array_push($second, $nd_gen->id);
            }
        }

        foreach(auth()->user()->referrals as $st_gen){
            foreach($st_gen->referrals as $nd_gen){
                foreach($nd_gen->referrals as $rd_gen){
                    array_push($team, $rd_gen->id);
                    array_push($third, $rd_gen->id);
                }
            }
        }

        $rebates = Transaction::all();

        if(isset(request()->filter)){
            if(request()->filter == 'email'){
                $members = User::where('email', 'like', '%' . request()->value . '%')->get();
            }elseif(request()->filter == 'username'){
                $members = User::where('username', 'like', '%' . request()->value . '%')->get();
            }
        }else{
            $members = User::all();
        }

        return view('marketer', compact('rebates', 'members', 'team', 'first', 'second', 'third'));
    }

    public function member($username)
    {
        if(auth()->user()->type != 'marketer'){
            return redirect()->route('home')->with('error', 'Sorry, you do not have access to the Marketers Dashboard.');
        }

        $user = User::where('username', $username)->firstOrFail();
        $first = [];
        $second = [];
        $third = [];
        
        foreach($user->referrals as $st_gen){
                array_push($first, $st_gen->id);
        }

        foreach($user->referrals as $st_gen){
            foreach($st_gen->referrals as $nd_gen){
                array_push($second, $nd_gen->id);
            }
        }

        foreach($user->referrals as $st_gen){
            foreach($st_gen->referrals as $nd_gen){
                foreach($nd_gen->referrals as $rd_gen){
                    array_push($third, $rd_gen->id);
                }
            }
        }

        return view('member', compact('user', 'first', 'second', 'third'));
    }
}
