<?php

namespace App\Http\Controllers\Admin;

use App\Deposit;
use App\GeneralSetting;
use App\Plan;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use App\User;
use App\UserLogin;
use App\Withdrawal;

class AdminController extends Controller
{

    public function dashboard(Request $request)
    {
        $page_title = 'Dashboard';
        $user_login_data = UserLogin::whereYear('created_at', '>=', \Carbon\Carbon::now()->subYear())->get(['browser', 'os', 'country']);
        $chart['user_browser_counter'] = $user_login_data->groupBy('browser')->map(function ($item, $key) {
            return collect($item)->count();
        });

        $chart['user_os_counter'] = $user_login_data->groupBy('os')->map(function ($item, $key) {
            return collect($item)->count();
        });

        $chart['user_country_counter'] = $user_login_data->groupBy('country')->map(function ($item, $key) {
            return collect($item)->count();
        })->sort()->reverse()->take(5);

        $widget['total_users'] = User::all('sv', 'ev', 'status', 'balance');
        $widget['deposits'] = Deposit::where('status', 1)->selectRaw('COUNT(*) as total, SUM(rate * charge) as total_charge')->selectRaw('SUM(rate * amount) as total_amount')->first();
        $widget['withdrawals'] = Withdrawal::where('status', 1)->selectRaw('COUNT(*) as total, SUM(rate * charge) as total_charge')->selectRaw('SUM(rate * amount) as total_amount')->first();

        return view('admin.dashboard', compact('page_title', 'chart', 'widget'));
    }

    public function profile()
    {
        $page_title = 'Profile';
        $admin = Auth::guard('admin')->user();
        return view('admin.profile', compact('page_title', 'admin'));
    }

    public function profileUpdate(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'image' => 'nullable|image|mimes:jpg,jpeg,png'
        ]);

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

        if ($request->hasFile('image')) {
            try {
                $old = $user->image ?: null;
                $user->image = upload_image($request->image, config('constants.admin.profile.path'), config('contants.admin.profile.size'), $old);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Image could not be uploaded.'];
                return back()->withNotify($notify);
            }
        }

        $user->name = $request->name;
        $user->email = $request->email;
        $user->save();
        $notify[] = ['success', 'Your profile has been updated.'];
        return redirect()->route('admin.profile')->withNotify($notify);
    }

    public function passwordUpdate(Request $request)
    {
        $this->validate($request, [
            'old_password' => 'required',
            'password' => 'required|min:6|confirmed',
        ]);

        $user = Auth::guard('admin')->user();
        if (!Hash::check($request->old_password, $user->password)) {
            $notify[] = ['error', 'Password Do not match !!'];
            return back()->withErrors(['Invalid old password.']);
        }
        $user->update([
            'password' => bcrypt($request->password)
        ]);
        return redirect()->route('admin.profile')->withSuccess('Password Changed Successfully');
    }


    public function plan()
    {
        $page_title = 'MLM Plans';
        $empty_message = 'No Plan found';
        $plans = Plan::paginate(config('constants.table.default'));
        return view('admin.mlm_plan', compact('page_title', 'plans', 'empty_message'));
    }

    public function planCreate(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'amount' => 'required|min:0',
            'bv' => 'required|min:0|integer',
            'ref_com' => 'required|min:0',
            'com_to_tree' => 'required|min:0',
        ]);


        $plan = new Plan();
        $plan->name = $request->name;
        $plan->amount = $request->amount;
        $plan->bv = $request->bv;
        $plan->ref_com = $request->ref_com;
        $plan->com_to_tree = $request->com_to_tree;
        $plan->status = $request->status;
        $plan->save();

        $notify[] = ['success', 'New MLM Plan create successfully'];
        return back()->withNotify($notify);
    }


    public function planUpdate(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
            'name' => 'required',
            'amount' => 'required|min:0',
            'bv' => 'required|min:0|integer',
            'ref_com' => 'required|min:0',
            'com_to_tree' => 'required|min:0',
        ]);


        $plan = Plan::find($request->id);
        $plan->name = $request->name;
        $plan->amount = $request->amount;
        $plan->bv = $request->bv;
        $plan->ref_com = $request->ref_com;
        $plan->com_to_tree = $request->com_to_tree;
        $plan->status = $request->status;
        $plan->save();

        $notify[] = ['success', 'MLM Plan has been updated.'];
        return back()->withNotify($notify);
    }


    public function matchingIndex()
    {
        $page_title = 'Matching Bonus';

        return view('admin.matching_bonus', compact('page_title'));
    }

    public function matchingUpdate(Request $request)
    {
        $this->validate($request, [
            'bv_price' => 'required|min:0',
            'total_bv' => 'required|min:0|integer',
            'max_bv' => 'required|min:0|integer',


        ]);




        $setting = GeneralSetting::first();

        if ($request->matching_bonus_time == 'daily') {
          $when = $request->daily_time;
        } elseif ($request->matching_bonus_time == 'weekly') {
            $when = $request->weekly_time;
        } elseif ($request->matching_bonus_time == 'monthly') {
            $when = $request->monthly_time;
        }


        $setting->bv_price = $request->bv_price;
        $setting->total_bv = $request->total_bv;
        $setting->max_bv = $request->max_bv;
        $setting->cary_flash = $request->cary_flash;
        $setting->matching_bonus_time = $request->matching_bonus_time;
    
        $setting->matching_when = $when;
        $setting->save();

        $notify[] = ['success', 'Matching bonus has been updated.'];
        return back()->withNotify($notify);

    }
}
