<?php
    namespace App\Http\Controllers;

    use App\Models\Banner;
    use App\Models\Product;
    use App\Models\Category;
    use App\Models\PostTag;
    use App\Models\PostCategory;
    use App\Models\Post;
    use App\Models\Cart;
    use App\Models\Brand;
    use App\User;
    use Auth;
    use Session;
    use Newsletter;
    use DB;
    use Hash;
    use Illuminate\Support\Str;
    use Illuminate\Http\Request;
    use App\Mail\SendOtpMail;
    use Illuminate\Support\Facades\Mail;
    use Carbon\Carbon;

    class FrontendController extends Controller
    {

    
        public function index(Request $request)
        {
            return redirect()->route($request->user()->role);
        }

        public function home()
        {
            $featured = Product::where('status', 'active')->where('is_featured', 1)->orderBy('price', 'DESC')->limit(2)->get();
            $posts = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            $banners = Banner::where('status', 'active')->limit(3)->orderBy('id', 'DESC')->get();
            // return $banner;
            $products = Product::where('status', 'active')->orderBy('id', 'DESC')->limit(8)->get();
            $category = Category::where('status', 'active')->where('is_parent', 1)->orderBy('title', 'ASC')->get();
            // return $category;
            return view('frontend.index')
                ->with('featured', $featured)
                ->with('posts', $posts)
                ->with('banners', $banners)
                ->with('product_lists', $products)
                ->with('category_lists', $category);
        }

        public function aboutUs()
        {
            return view('frontend.pages.about-us');
        }
        

        public function contact()
        {
            return view('frontend.pages.contact');
        }

        public function productDetail($slug)
        {
            $product_detail = Product::getProductBySlug($slug);
            // dd($product_detail);
            return view('frontend.pages.product_detail')->with('product_detail', $product_detail);
        }

        public function productGrids()
        {
            $products = Product::query();

            if (!empty($_GET['category'])) {
                $slug = explode(',', $_GET['category']);
                // dd($slug);
                $cat_ids = Category::select('id')->whereIn('slug', $slug)->pluck('id')->toArray();
                // dd($cat_ids);
                $products->whereIn('cat_id', $cat_ids);
                // return $products;
            }
            if (!empty($_GET['brand'])) {
                $slugs = explode(',', $_GET['brand']);
                $brand_ids = Brand::select('id')->whereIn('slug', $slugs)->pluck('id')->toArray();
                return $brand_ids;
                $products->whereIn('brand_id', $brand_ids);
            }
            if (!empty($_GET['sortBy'])) {
                if ($_GET['sortBy'] == 'title') {
                    $products = $products->where('status', 'active')->orderBy('title', 'ASC');
                }
                if ($_GET['sortBy'] == 'price') {
                    $products = $products->orderBy('price', 'ASC');
                }
            }

            if (!empty($_GET['price'])) {
                $price = explode('-', $_GET['price']);
                // return $price;
                // if(isset($price[0]) && is_numeric($price[0])) $price[0]=floor(Helper::base_amount($price[0]));
                // if(isset($price[1]) && is_numeric($price[1])) $price[1]=ceil(Helper::base_amount($price[1]));

                $products->whereBetween('price', $price);
            }

            $recent_products = Product::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            // Sort by number
            if (!empty($_GET['show'])) {
                $products = $products->where('status', 'active')->paginate($_GET['show']);
            } else {
                $products = $products->where('status', 'active')->paginate(9);
            }
            // Sort by name , price, category


            return view('frontend.pages.product-grids')->with('products', $products)->with('recent_products', $recent_products);
        }
        public function productLists()
        {
            $products = Product::query();

            if (!empty($_GET['category'])) {
                $slug = explode(',', $_GET['category']);
                // dd($slug);
                $cat_ids = Category::select('id')->whereIn('slug', $slug)->pluck('id')->toArray();
                // dd($cat_ids);
                $products->whereIn('cat_id', $cat_ids)->paginate;
                // return $products;
            }
            if (!empty($_GET['brand'])) {
                $slugs = explode(',', $_GET['brand']);
                $brand_ids = Brand::select('id')->whereIn('slug', $slugs)->pluck('id')->toArray();
                return $brand_ids;
                $products->whereIn('brand_id', $brand_ids);
            }
            if (!empty($_GET['sortBy'])) {
                if ($_GET['sortBy'] == 'title') {
                    $products = $products->where('status', 'active')->orderBy('title', 'ASC');
                }
                if ($_GET['sortBy'] == 'price') {
                    $products = $products->orderBy('price', 'ASC');
                }
            }

            if (!empty($_GET['price'])) {
                $price = explode('-', $_GET['price']);
                // return $price;
                // if(isset($price[0]) && is_numeric($price[0])) $price[0]=floor(Helper::base_amount($price[0]));
                // if(isset($price[1]) && is_numeric($price[1])) $price[1]=ceil(Helper::base_amount($price[1]));

                $products->whereBetween('price', $price);
            }

            $recent_products = Product::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            // Sort by number
            if (!empty($_GET['show'])) {
                $products = $products->where('status', 'active')->paginate($_GET['show']);
            } else {
                $products = $products->where('status', 'active')->paginate(6);
            }
            // Sort by name , price, category


            return view('frontend.pages.product-lists')->with('products', $products)->with('recent_products', $recent_products);
        }
        public function productFilter(Request $request)
        {
            $data = $request->all();
            // return $data;
            $showURL = "";
            if (!empty($data['show'])) {
                $showURL .= '&show=' . $data['show'];
            }

            $sortByURL = '';
            if (!empty($data['sortBy'])) {
                $sortByURL .= '&sortBy=' . $data['sortBy'];
            }

            $catURL = "";
            if (!empty($data['category'])) {
                foreach ($data['category'] as $category) {
                    if (empty($catURL)) {
                        $catURL .= '&category=' . $category;
                    } else {
                        $catURL .= ',' . $category;
                    }
                }
            }

            $brandURL = "";
            if (!empty($data['brand'])) {
                foreach ($data['brand'] as $brand) {
                    if (empty($brandURL)) {
                        $brandURL .= '&brand=' . $brand;
                    } else {
                        $brandURL .= ',' . $brand;
                    }
                }
            }
            // return $brandURL;

            $priceRangeURL = "";
            if (!empty($data['price_range'])) {
                $priceRangeURL .= '&price=' . $data['price_range'];
            }
            if (request()->is('e-shop.loc/product-grids')) {
                return redirect()->route('product-grids', $catURL . $brandURL . $priceRangeURL . $showURL . $sortByURL);
            } else {
                return redirect()->route('product-lists', $catURL . $brandURL . $priceRangeURL . $showURL . $sortByURL);
            }
        }
        public function productSearch(Request $request)
        {
            $recent_products = Product::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            $products = Product::orwhere('title', 'like', '%' . $request->search . '%')
                ->orwhere('slug', 'like', '%' . $request->search . '%')
                ->orwhere('description', 'like', '%' . $request->search . '%')
                ->orwhere('summary', 'like', '%' . $request->search . '%')
                ->orwhere('price', 'like', '%' . $request->search . '%')
                ->orderBy('id', 'DESC')
                ->paginate('9');
            return view('frontend.pages.product-grids')->with('products', $products)->with('recent_products', $recent_products);
        }

        public function productBrand(Request $request)
        {
            $products = Brand::getProductByBrand($request->slug);
            $recent_products = Product::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            if (request()->is('e-shop.loc/product-grids')) {
                return view('frontend.pages.product-grids')->with('products', $products->products)->with('recent_products', $recent_products);
            } else {
                return view('frontend.pages.product-lists')->with('products', $products->products)->with('recent_products', $recent_products);
            }
        }
        public function productCat(Request $request)
        {
            $products = Category::getProductByCat($request->slug);
            // return $request->slug;
            $recent_products = Product::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();

            if (request()->is('e-shop.loc/product-grids')) {
                return view('frontend.pages.product-grids')->with('products', $products->products)->with('recent_products', $recent_products);
            } else {
                return view('frontend.pages.product-lists')->with('products', $products->products)->with('recent_products', $recent_products);
            }
        }
        public function productSubCat(Request $request)
        {
            $products = Category::getProductBySubCat($request->sub_slug);
            // return $products;
            $recent_products = Product::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();

            if (request()->is('e-shop.loc/product-grids')) {
                return view('frontend.pages.product-grids')->with('products', $products->sub_products)->with('recent_products', $recent_products);
            } else {
                return view('frontend.pages.product-lists')->with('products', $products->sub_products)->with('recent_products', $recent_products);
            }
        }

        public function blog()
        {
            $post = Post::query();

            if (!empty($_GET['category'])) {
                $slug = explode(',', $_GET['category']);
                // dd($slug);
                $cat_ids = PostCategory::select('id')->whereIn('slug', $slug)->pluck('id')->toArray();
                return $cat_ids;
                $post->whereIn('post_cat_id', $cat_ids);
                // return $post;
            }
            if (!empty($_GET['tag'])) {
                $slug = explode(',', $_GET['tag']);
                // dd($slug);
                $tag_ids = PostTag::select('id')->whereIn('slug', $slug)->pluck('id')->toArray();
                // return $tag_ids;
                $post->where('post_tag_id', $tag_ids);
                // return $post;
            }

            if (!empty($_GET['show'])) {
                $post = $post->where('status', 'active')->orderBy('id', 'DESC')->paginate($_GET['show']);
            } else {
                $post = $post->where('status', 'active')->orderBy('id', 'DESC')->paginate(9);
            }
            // $post=Post::where('status','active')->paginate(8);
            $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            return view('frontend.pages.blog')->with('posts', $post)->with('recent_posts', $rcnt_post);
        }

        public function blogDetail($slug)
        {
            $post = Post::getPostBySlug($slug);
            $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            // return $post;
            return view('frontend.pages.blog-detail')->with('post', $post)->with('recent_posts', $rcnt_post);
        }

        public function blogSearch(Request $request)
        {
            // return $request->all();
            $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            $posts = Post::orwhere('title', 'like', '%' . $request->search . '%')
                ->orwhere('quote', 'like', '%' . $request->search . '%')
                ->orwhere('summary', 'like', '%' . $request->search . '%')
                ->orwhere('description', 'like', '%' . $request->search . '%')
                ->orwhere('slug', 'like', '%' . $request->search . '%')
                ->orderBy('id', 'DESC')
                ->paginate(8);
            return view('frontend.pages.blog')->with('posts', $posts)->with('recent_posts', $rcnt_post);
        }

        public function blogFilter(Request $request)
        {
            $data = $request->all();
            // return $data;
            $catURL = "";
            if (!empty($data['category'])) {
                foreach ($data['category'] as $category) {
                    if (empty($catURL)) {
                        $catURL .= '&category=' . $category;
                    } else {
                        $catURL .= ',' . $category;
                    }
                }
            }

            $tagURL = "";
            if (!empty($data['tag'])) {
                foreach ($data['tag'] as $tag) {
                    if (empty($tagURL)) {
                        $tagURL .= '&tag=' . $tag;
                    } else {
                        $tagURL .= ',' . $tag;
                    }
                }
            }
            // return $tagURL;
            // return $catURL;
            return redirect()->route('blog', $catURL . $tagURL);
        }

        public function blogByCategory(Request $request)
        {
            $post = PostCategory::getBlogByCategory($request->slug);
            $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            return view('frontend.pages.blog')->with('posts', $post->post)->with('recent_posts', $rcnt_post);
        }

        public function blogByTag(Request $request)
        {
            // dd($request->slug);
            $post = Post::getBlogByTag($request->slug);
            // return $post;
            $rcnt_post = Post::where('status', 'active')->orderBy('id', 'DESC')->limit(3)->get();
            return view('frontend.pages.blog')->with('posts', $post)->with('recent_posts', $rcnt_post);
        }

        // Login
        public function login()
        {
            return view('frontend.pages.login');
        }
        /*public function loginSubmit(Request $request)
        {
            $data = $request->all();
            if (Auth::attempt(['email' => $data['email'], 'password' => $data['password'], 'status' => 'active'])) {
                Session::put('user', $data['email']);
                request()->session()->flash('success', 'Successfully login');
                return redirect()->route('home');
            } else {
                request()->session()->flash('error', 'Invalid email and password pleas try again!');
                return redirect()->back();
            }
        }*/


public function loginSubmit(Request $request)
{
    $user = User::where('email', $request->email)->first();

    if (!$user) {
        return response()->json([
            'status' => 'error',
            'message' => 'User not found'
        ]);
    }

    if (!Hash::check($request->password, $user->password)) {
        return response()->json([
            'status' => 'error',
            'message' => 'Invalid email or password'
        ]);
    }

    //  ADMIN LOGIN — BYPASS EMAIL VERIFICATION & OTP
    if ($user->role === 'admin') {

        if ($user->status !== 'active') {
            return response()->json([
                'status' => 'error',
                'message' => 'Admin account is inactive'
            ]);
        }

        Auth::login($user);

        return response()->json([
            'status' => 'success',
            'redirect' => route('admin') // or admin.dashboard
        ]);
    }

    //  NORMAL USER MUST BE VERIFIED
    if (!$user->is_verified) {
        return response()->json([
            'status' => 'error',
            'message' => 'Please verify your email first.'
        ]);
    }

    //  OTP FLOW FOR NORMAL USERS ONLY
    $otp = rand(100000, 999999);

    $user->update([
        'otp' => Hash::make($otp),
        'otp_expires_at' => Carbon::now()->addMinutes(5),
        'otp_last_sent_at' => Carbon::now(),
    ]);

    Mail::to($user->email)->send(new SendOtpMail($otp));

    session(['login_otp_user_id' => $user->id]);

    return response()->json([
        'status' => 'otp_sent'
    ]);
}




        public function showLoginOtpForm()
        {
            return view('frontend.pages.login-otp');
        }

        public function verifyLoginOtp(Request $request)
        {
            $userId = session('login_otp_user_id');

            if (!$userId) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Session expired. Please login again.'
                ]);
            }

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

            if (!$user) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'User not found.'
                ]);
            }

            if (!Hash::check($request->otp, $user->otp)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Invalid OTP'
                ]);
            }

            if (now()->gt($user->otp_expires_at)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'OTP expired'
                ]);
            }

            $user->update([
                'otp' => null,
                'otp_expires_at' => null,
                'otp_last_sent_at' => null
            ]);

            Auth::login($user);

            // Flash success message for next page
            session()->flash('success', 'Logged in successfully');

            // Clear session
            session()->forget('login_otp_user_id');

            return response()->json([
                'status' => 'success',
                'redirect' => route('home')
            ]);
        }


        public function resendLoginOtp()
        {
            $userId = session('login_otp_user_id');

            if (!$userId) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Session expired. Please login again.'
                ]);
            }

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

            if (!$user) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'User not found.'
                ]);
            }

            if (
                $user->otp_last_sent_at &&
                Carbon::now()->diffInSeconds($user->otp_last_sent_at) < 60
            ) {
                return response()->json([
                    'status' => 'cooldown',
                    'message' => 'Please wait before requesting a new OTP.'
                ]);
            }

            $otp = rand(100000, 999999);

            $user->update([
                'otp' => Hash::make($otp),
                'otp_expires_at' => Carbon::now()->addMinutes(5),
                'otp_last_sent_at' => Carbon::now(),
            ]);

            Mail::to($user->email)->send(new SendOtpMail($otp));

            return response()->json([
                'status' => 'resent',
                'message' => 'New OTP sent successfully.'
            ]);
        }



        public function logout()
        {
            //Session::forget('user');
            //Auth::logout();
            Auth::logout();
            Session::invalidate();
            Session::regenerateToken();

            request()->session()->flash('success', 'Logout successfully');
            return back();
        }

        public function register()
        {
            return view('frontend.pages.register');
        }


        public function showOtpForm()
        {
            return view('frontend.pages.verify-otp');
        }

        /*public function verifyOtp(Request $request)
        {




            $userId = session('otp_user_id');

            if (!$userId) {
                return redirect()->route('login.form');
            }

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

            if (!$user) {
                return redirect()->route('login.form');
            }



            if (!Hash::check($request->otp, $user->otp)) {
                return back()->with('error', 'Invalid OTP');
            }

            if (now()->gt($user->otp_expires_at)) {
                return back()->with('error', 'OTP expired');
            }

            $user->update([
                'is_verified' => 1,
                'status' => 'active',
                'otp' => null,
                'otp_expires_at' => null
            ]);

            Auth::login($user);

            return redirect()->route('home')
                ->with('success', 'Email verified successfully');
        }*/

        public function verifyOtp(Request $request)
        {
            $userId = session('otp_user_id');

            if (!$userId) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Session expired. Please register again.'
                ]);
            }

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

            if (!$user) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'User not found.'
                ]);
            }

            if (!Hash::check($request->otp, $user->otp)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Invalid OTP'
                ]);
            }

            if (now()->gt($user->otp_expires_at)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'OTP expired'
                ]);
            }

            $user->update([
                'is_verified' => 1,
                'status' => 'active',
                'otp' => null,
                'otp_expires_at' => null
            ]);

            session()->forget('otp_user_id');

            Auth::login($user);

            session()->flash('success', 'Registration successful. Welcome!');

            return response()->json([
                'status' => 'success',
                'redirect' => route('home')
            ]);
        }


        /*public function registerSubmit(Request $request)
        {
            // return $request->all();
            $this->validate($request, [
                'name' => 'string|required|min:2',
                'email' => 'string|required|unique:users,email',
                'password' => 'required|min:6|confirmed',
            ]);
            $data = $request->all();
            // dd($data);
            $check = $this->create($data);
            Session::put('user', $data['email']);
            if ($check) {
                request()->session()->flash('success', 'Successfully registered');
                return redirect()->route('home');
            } else {
                request()->session()->flash('error', 'Please try again!');
                return back();
            }
        }*/


        public function registerSubmit(Request $request)
        {
            $validator = \Validator::make($request->all(), [
                'name' => 'string|required|min:2',
                'email' => 'string|required|unique:users,email',
                'password' => 'required|min:6|confirmed',
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => $validator->errors()->first()
                ]);
            }
            $user = $this->create($request->all());

            if ($user) {
                // Generate OTP
                $otp = rand(100000, 999999);

                $user->update([
                    'otp' => Hash::make($otp),
                    'otp_expires_at' => Carbon::now()->addMinutes(5),
                    'otp_last_sent_at' => Carbon::now(),
                ]);



                // Send Email
                Mail::to($user->email)->send(new SendOtpMail($otp));

                // Store user id in session for verification
                session(['otp_user_id' => $user->id]);

                return response()->json([
                    'status' => 'otp_sent'
                ]);
            } else {
                return back()->with('error', 'Please try again!');
            }
        }

        public function resendRegisterOtp()
        {
            $userId = session('otp_user_id');

            if (!$userId) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Session expired. Please register again.'
                ]);
            }

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

            if (!$user) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'User not found.'
                ]);
            }

            if (
                $user->otp_last_sent_at &&
                Carbon::now()->diffInSeconds($user->otp_last_sent_at) < 60
            ) {
                return response()->json([
                    'status' => 'cooldown',
                    'message' => 'Please wait before requesting a new OTP.'
                ]);
            }

            $otp = rand(100000, 999999);

            $user->update([
                'otp' => Hash::make($otp),
                'otp_expires_at' => Carbon::now()->addMinutes(5),
                'otp_last_sent_at' => Carbon::now(),
            ]);

            Mail::to($user->email)->send(new SendOtpMail($otp));

            return response()->json([
                'status' => 'resent'
            ]);
        }


        public function create(array $data)
        {
            return User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
                //Changed by Dhaval
                //'status'=>'active'
                'status' => 'inactive',
                'is_verified' => 0,


            ]);
        }
        // Reset password
        public function showResetForm()
        {
            return view('auth.passwords.old-reset');
        }

        public function subscribe(Request $request)
        {
            if (! Newsletter::isSubscribed($request->email)) {
                Newsletter::subscribePending($request->email);
                if (Newsletter::lastActionSucceeded()) {
                    request()->session()->flash('success', 'Subscribed! Please check your email');
                    return redirect()->route('home');
                } else {
                    Newsletter::getLastError();
                    return back()->with('error', 'Something went wrong! please try again');
                }
            } else {
                request()->session()->flash('error', 'Already Subscribed');
                return back();
            }
        }
    }
