<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Admin;
use App\Models\Product;
use App\Models\Category;
use App\Models\Customer;
use App\Models\Attribute;
use App\Models\OrderItem;
use App\Models\LandingPage;
use App\Models\ProductVisit;
use App\Services\LogTracker;
use Illuminate\Http\Request;
use App\Models\ProductReview;
use App\Services\HomeService;
use App\Models\GeneralSetting;
use Illuminate\Support\Carbon;
use App\Models\LandingPageReview;
use App\Models\SiteConfiguration;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Traits\TypeWiseProducts;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Gloudemans\Shoppingcart\Facades\Cart;


class HomeController extends Controller
{
    protected  $site_configuration;
    protected  $homeService;
    use TypeWiseProducts;


    public function __construct(HomeService $homeService)
    {
        $this->site_configuration = SiteConfiguration::select('template_id', 'position_wise_product')->first();
        $this->homeService = $homeService;
    }
    public function index()
    {

        //------------frontend slider------------------
        $sliders                = $this->homeService->getSliders();
        //----------top section categories--------------
        $top_section_categories = $this->homeService->getTopSectionCategories();
        //----------top section categories--------------
        $top_section_brand      = $this->homeService->getTopSectionBrand();
        //-------------------- top selling product ---------------------
        $top_selling_products   = $this->homeService->getTopSellingProducts();
        // ------------------ new arrival products ---------------
        $new_arrival_products   = $this->homeService->getNewProducts();
        //-------------------- offer banner placement ---------------------
        $after_top_selling_banner = $this->homeService->getBanners([
            'after-top-selling-first-banner',
            'after-top-selling-second-banner'
        ], 5);

        $after_top_category = $this->homeService->getBanners([
            'after-category-first-banner',
            'after-category-second-banner',
        ], 5);

        $after_new_arrival      = $this->homeService->getBanners('after-new-arrival-banner', 1);
        $before_footer_section  = $this->homeService->getBanners('before-footer-section', 1);

        $cus_review = collect();
        if ($this->site_configuration->template_id == 2) {
            $cus_review = $this->homeService->getProductReviews();
        }

        $authors             = collect();
        $publishers          = collect();
        $top_author          = collect();
        $after_slider_banner = collect();
        $after_best_writer_banner = collect();
        $feature_products = collect();
        $combo_products = collect();
        $skin_concern_products = collect();
        $countries_by_products = collect();

        if ($this->site_configuration->template_id == 4) {
            $after_best_writer_banner = $this->homeService->getBanners([
                'after-best-writer-first-banner',
                'after-best-writer-second-banner',
            ], 2);
            $after_slider_banner = $this->homeService->getBanners([
                'after-slider-first-banner',
                'after-slider-second-banner',
                'after-slider-third-banner',
                'after-slider-fourth-banner',
            ], 4);

            $authors    = $this->homeService->getAuthors();
            $publishers = $this->homeService->getPublishers();
            $top_author = $this->homeService->getTopAuthors();
        }

        if ($this->site_configuration->template_id == 9) {
            $feature_products = $this->typeWiseProducts(['is_featured' => 1]);
            $combo_products = $this->typeWiseProducts(['is_combo' => 1]);
            $skin_concern_products = $this->shopByProducts('skins');
            $countries_by_products = $this->shopByProducts('countries');
        }

       

        $data = [
            'sliders'                           => $sliders,
            'after_slider_banner'               => $after_slider_banner,
            'after_best_writer_banner'          => $after_best_writer_banner,
            'top_section_categories'            => $top_section_categories,
            'top_section_brand'                 => $top_section_brand,
            'top_selling_products'              => $top_selling_products,
            'new_arrival_products'              => $new_arrival_products,
            'after_top_selling_banner'          => $after_top_selling_banner,
            'after_top_category'                => $after_top_category,
            'before_footer_section'             => $before_footer_section,
            'cus_review'                        => $cus_review,
            'after_new_arrival'                 => $after_new_arrival,
            'authors'                           => $authors,
            'publishers'                        => $publishers,
            'top_author'                        => $top_author,
            'feature_products'                  => $feature_products,
            'combo_products'                    => $combo_products,
            'skin_concern_products'             => $skin_concern_products,
            'countries_by_products'             => $countries_by_products,

        ];
        $template = 'template' . $this->site_configuration->template_id;
        return view("frontend.pages.index.$template", $data);
    }


    public function landingPage($slug)
    {

        $page               = LandingPage::where('status', 1)->where('page_slug', $slug)->firstOrFail();
        $products           = Product::where('landing_page_id', $page->id)
                                ->where('status', 1)
                                ->orderBy('id', 'desc')
                                ->select('id', 'name', 'thumbnail_img', 'slug', 'sale_price', 'price','is_free_delivery', 'status')
                                ->get();
        $has_free_delivery = $products->contains(function ($item) {
            return $item->is_free_delivery == 1;
        });  

        $general_setting    = GeneralSetting::latest()->select('logo')->first();
        $reviews            = LandingPageReview::where('landing_page_id',$page->id)->select('thumbnail_img')->get();
        $delivery_charges   = DB::table('delivery_charges')->where('status',1)->get();
        $descriptions       = DB::table('descriptions')->where('landing_page_id', $page->id)->where('status', 1)->select('title')->get();

        if (Cart::total() == 0) {
            Product::where('is_auto_cart', 1)->where('landing_page_id', $page->id)->where('status', 1)->orderBy('id', 'desc')->get()->each(function ($product) {
                Cart::add([
                    'id'      => $product->id,
                    'name'    => $product->name,
                    'slug'    => $product->slug,
                    'qty'     => 1,
                    'price'   => $product->sale_price,
                    'weight'  => 0,
                    'tax'     => 0,
                    'options' => [
                        'original_price' => $product->price,
                        'image'          => $product->thumbnail_img,
                    ],
                ]);
            });
        }

        $cartItems = Cart::content()->pluck('id')->toArray();

        $data = [
            'page'             => $page,
            'general_setting'  => $general_setting,
            'reviews'          => $reviews,
            'products'         => $products,
            'has_free_delivery' => $has_free_delivery ?? 0,
            'delivery_charges' => $delivery_charges,
            'descriptions'     => $descriptions,
            'cartItems'        => $cartItems,
        ];

        return view('frontend.components.landing_page', $data);

    }

    public function getDeliveryCharge(Request $request)
    {
        $deliveryChargeId   = $request->query('delivery_charge_id');
        $deliveryCharge     = DB::table('delivery_charges')->where('id', $deliveryChargeId)->value('delivery_charge');

        if ($deliveryCharge !== null) {
            return response()->json([
                'success'           => true,
                'delivery_charge'   => $deliveryCharge,
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Delivery charge not found',
            ]);
        }
    }

    //-----------------loadMoreCategoryProduct----------------
    public function loadMoreCategoryProduct(Request $request)
    {

        $page  = $request->page;
        $limit = $request->limit;
        $start = ($page - 1) * $limit;
        //---------------category wise product---------
        $categories = Category::skip($start)->orderBy('position', 'asc')->where('status', 1)->select('id', 'name', 'slug')->with(['subCategory:id,category_id,name,slug'])->paginate($limit);
        foreach ($categories as $category) {
            $category->{'products'} = $this->homeService->getProducts('category_id', $category->id, 12, $this->site_configuration->position_wise_product);
        }
        // return $categories;
        $data = "";
        foreach ($categories as $category) {
            $data .= view('frontend.components.load_more_category_product', compact('category'))->render();
        }

        

        return response()->json([
            'status'          => true,
            'data'            => $data,
            'category_length' => $categories->count(),
            'message'         => 'load Data with category product',
        ]);
    }

    //-----------------loadMoreCategoryProduct----------------
    public function loadMoreBrandProduct(Request $request)
    {

        $page   = $request->page;
        $limit  = $request->limit;
        $start  = ($page - 1) * $limit;
        //---------------category wise product---------
        $brands = Brand::skip($start)->orderBy('position', 'asc')->where('status', 1)->select('id', 'name', 'slug')->paginate($limit);

        foreach ($brands as $brand) {
            $brand->{'products'} = $this->homeService->getProducts('brand_id', $brand->id, 12, $this->site_configuration->position_wise_product);
        }

        // return $categories;
        $data = "";

        
        foreach ($brands as $brand) {
            $data .= view('frontend.components.load_more_category_product', compact('brand'))->render();
        }

        

        return response()->json([
            'status'          => true,
            'data'            => $data,
            'category_length' => $brands->count(),
            'message'         => 'load Data with category product',
        ]);
    }


    public function newArrivalProduct()
    {
        $products = Product::where('status', 1)
            ->with('author:id,name', 'publisher:id,name')
            ->withAvg('productReviews', 'rating_stars')
            ->select('id', 'name', 'price', 'sale_price', 'reselling_price', 'slug', 'discount', 'thumbnail_img', 'stock', 'is_free_delivery', 'review_ratings', 'avg_review', 'author_id', 'publisher_id')
            ->orderBy('id', 'desc')
            ->take(30)
            ->get();

        return view('frontend.pages.new_arrival_product', compact('products'));
    }

    public function topSellProduct()
    {
        $top_selling_product_id = OrderItem::where('created_at', '>=', Carbon::today()->subDays('7'))
            ->select('product_id', DB::raw('count(*) as total'))
            ->groupBy('product_id')
            ->orderBy('total', 'desc')
            ->take(12)
            ->pluck('product_id');

        $products = Product::WhereIn('id', $top_selling_product_id)
            ->with('author:id,name', 'publisher:id,name')
            ->select('id', 'name', 'price', 'sale_price', 'reselling_price', 'slug', 'discount', 'thumbnail_img', 'stock', 'is_free_delivery', 'review_ratings', 'avg_review', 'author_id', 'publisher_id')
            ->where('status', 1)
            ->take(30)
            ->get();

        return view('frontend.pages.top_sell_product', compact('products'));
    }

    public function setAffiliateUsername($username)
    {
        session::put('username', $username);
        return redirect('/');
    }



    public function affiliateWithdrawal(Request $request)
    {
        // return $request->all();
        $request->validate([
            'payment_method' => 'required',
            'note'           => 'nullable'
        ]);

        DB::beginTransaction();
        try {

            /****** find customer ******/
            $customer = Customer::where('username', $request->username)->first();

            if ($customer->amount <= 0) {
                return back()->with('message', 'Sorry, you do not have enough balance');
            }

            /************ save customer withdrawal request ***********/
            $this->homeService->saveCustomerWithdrawRequest($customer, $request, 'affiliate', $customer->amount);

            /********* customer withdrawal request transaction ********/
            $this->homeService->saveCustomerPaymentTransaction($customer, $request, 'affiliate', $customer->amount);


            /********* customer table amount update ********/
            $customer->amount = 0;
            $customer->save();

            DB::commit();
            return back()->with('message', 'Request Sent');
        } catch (\Throwable $e) {
            LogTracker::failLog($e, $customer);
            DB::rollBack();
        }
    }
    public function couponIncomeWithdrawal(Request $request)
    {
        // return $request->all();
        $request->validate([
            'payment_method' => 'required',
            'note'           => 'nullable'
        ]);

        DB::beginTransaction();
        try {

            /****** find influencer ******/
            $influencer = Customer::where('username', $request->username)->first();

            if ($influencer->coupon_income_amount <= 0) {
                return back()->with('message', 'Sorry, you do not have enough balance');
            }

            /************ save influencer withdrawal request ***********/
            $this->homeService->saveCustomerWithdrawRequest($influencer, $request, 'coupon', $influencer->coupon_income_amount);
            /********* influencer withdrawal request transaction ********/
            $this->homeService->saveCustomerPaymentTransaction($influencer, $request, 'coupon', $influencer->coupon_income_amount);

            /********* influencer table amount update ********/
            $influencer->coupon_income_amount = 0;
            $influencer->save();

            DB::commit();
            return back()->with('message', 'Request Sent');
        } catch (\Throwable $e) {
            LogTracker::failLog($e, $influencer);
            DB::rollBack();
        }
    }


      public function brand()
    {
        $brandsByLetter = [];

        foreach (range('A', 'Z') as $letter) {
            $brandsByLetter[$letter] = DB::table('brands')
                ->where('name', 'like', $letter . '%')
                ->get();
        }

        return view('frontend.pages.brand', ['brandsByLetter' => $brandsByLetter]);
    }


    
}
