<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\PasswordReset;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Classes\GeniusMailer;
use Session;

class AdminController extends Controller
{
    function adminLoginView()
    {
        return view('admin.auth.login');
    }

    function adminDashboard()
    {
        $orderCount = Order::count();
        $completedOrderCount = Order::where('order_status', 'completed')->count();
        $pendingOrderCount = Order::where('order_status', 'pending')->count();
        $todayOrderCount = Order::whereDate('created_at', Carbon::today())->count();
        $userCount = User::count();
        $verifiedUserCount = User::where('email_verified', 1)->count();

        return view('admin.pages.dashboard', compact('orderCount','userCount','verifiedUserCount','completedOrderCount', 'todayOrderCount','pendingOrderCount'));
    }

    function profile()
    {
        return view('admin.pages.profile');
    }


    function adminChangePasswordView()
    {
        return view('admin.auth.change-password');
    }

    public function showResetLinkView()
    {
        return view('admin.email.reset-ps-link-sent-form');
    }


    function adminLogin(Request $request)
    {

        $input = $request->all();
        $this->validate($request, [
            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:5|max:30'
        ], [
            'email.exists' => 'Account does not exist.'
        ]);

        //        $creds = $request->only('email', 'password');
//        if (Auth::guard('admin')->attempt($creds)) {
//            return redirect()->route('admin.dashboard');
//        } else {
//            return redirect()->route('admin.login')->with('error', 'Incorrect credentials');
//        }
        if (auth()->attempt(array('email' => $input['email'], 'password' => $input['password']))) {

            if (auth()->user()->hasRole('admin')) {
                return redirect()->route('admin.dashboard')->with('success', 'Login Successful');
            } else {
                return redirect()->back()->with('error', 'Role not authorized');
            }
        } else {
            return redirect()->back()->with('error', 'Incorrect Password');
        }
    }


    public function adminUpdatePassword(Request $request)
    {

        $request->validate([
            'new_password' => ['required', 'min:8'],
            'confirm_password' => ['required', 'min:8', 'same:new_password'],
        ]);


        User::where(['email' => $request->email])
            ->update(['password' => Hash::make($request->new_password),]);

        return redirect()->back()->with('success', 'Your password has been changed!');

    }


    public function adminProfileUpdate(Request $request)
    {

        $request->validate([
            'admin_profile' => 'required|image'
        ]);

        $admin_id = $request->admin_id;


        $admin_profile_update = User::find($admin_id);
        $admin_profile_update->first_name = $request->first_name;
        $admin_profile_update->last_name = $request->last_name;
        $admin_profile_update->address = $request->address;
        $admin_profile_update->phone_number = $request->phone_number;

        if ($request->hasFile('admin_profile')) {
            $admin_profile_update->clearMediaCollection('admin_profile');
            $admin_profile_update->addMediaFromRequest('admin_profile')->toMediaCollection('admin_profile');
        }

        $admin_profile_update->update();
        return redirect()->back()->with('success', 'admin Profile is Updated');


    }


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

    // Befor login functionality


    public function sentPasswordResetLink(Request $request)
    {

        if ($request->email == '') {
            return redirect()->back()->with('error', 'Please Required Your Email');

        }
        $check_email_not_exists = User::where('email', $request->email)->get();

        if (isset($check_email_not_exists[0])) {


            $token = \Str::random(64);
            $resetpassword = new PasswordReset;
            $resetpassword->email = $request->email;
            $resetpassword->token = $token;
            //  $resetpassword->created_at = Carbon::now();
            $resetpassword->save();

            $actionLink = route('admin.show-reset-update-view', ['token' => $token, 'email' => $request->email]);
            $body = "We are received a request to reset the password for <b>Your app Name </b> account associated with " . $request->email . ". You can reset your password by clicking the link below";


            //            $view = view('email.contact', compact(['first_name', 'email', 'message']))->render();

            $view = view('admin.email.sent-to-reset-template', compact(['actionLink', 'body']))->render();


            $data = [
                'from' => 'Support@Theclubhouse.Com',
                'to' => $request->email,
                'subject' => "Thanks for submit!!",
                'body' => $view,
            ];

            $mailer = new GeniusMailer();
            $mailer->sendCustomMail($data);


            //            \Mail::send('email-admin-template.sent-to-reset-template', ['actionLink' => $actionLink, 'body' => $body], function ($message) use ($request) {
//                $message->to($request->email)
//                    ->from('Kshahzaib046@gmail.com')
//                    ->subject('Reset Password');
//
//
//            });
            return redirect()->back()->with('success', 'We have e-mailed your password reset link!.');


        } else {
            return redirect()->back()->with('error', 'Your Email not registered');

        }

    }


    public function showResetUpdateView(Request $request, $token = null)
    {
        return view('admin.email.password-update-form')->with(['token' => $token, 'email' => $request->email]);
    }

    public function resetPasswordUpdate(Request $request)
    {

        $request->validate([

            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:8',
            'confirm_password' => 'required|min:8|same:password',
        ]);

        $check_token = PasswordReset::where([
            'email' => $request->email,
            'token' => $request->token,
        ])->first();


        if (!$check_token) {
            return back()->with('error', 'Invalid token');
        } else {


            User::where(['email' => $request->email])
                ->update(['password' => \Hash::make($request->password),]);

            PasswordReset::where(['email' => $request->email])->delete();


            return redirect()->back()->with('success', 'Your password has been changed! You can login with new password')->with('verifiedEmail', $request->email);

        }


    }


}
