<?php

namespace App\Http\Controllers\API;
use Session, File;

use App\Models\User;
use App\Models\Review;
use App\Rules\Captcha;
use Illuminate\Http\Request;
use Modules\City\Entities\City;
use Modules\FAQ\App\Models\Faq;
use Modules\Blog\App\Models\Blog;
use App\Http\Controllers\Controller;
use Modules\Page\App\Models\AboutUs;
use Illuminate\Support\Facades\Cache;
use Modules\JobPost\Entities\JobPost;
use Modules\Listing\Entities\Listing;
use Modules\Page\App\Models\Homepage;
use Modules\Page\App\Models\ContactUs;
use Modules\Category\Entities\Category;
use Modules\Page\App\Models\CustomPage;
use Modules\Blog\App\Models\BlogComment;
use Modules\JobPost\Entities\JobRequest;
use Modules\Currency\App\Models\Currency;
use Modules\Language\App\Models\Language;
use Modules\Category\Entities\SubCategory;
use Modules\Page\App\Models\PrivacyPolicy;
use Modules\Listing\Entities\ListingGallery;
use Modules\Page\App\Models\TermAndCondition;
use Modules\SeoSetting\App\Models\SeoSetting;
use Modules\Listing\App\Models\ListingPackage;
use Modules\Testimonial\App\Models\Testimonial;
use Modules\GlobalSetting\App\Models\GlobalSetting;
use Modules\Slider\Entities\Slider;

class HomeController extends Controller
{

    // public function website_setup(Request $request){

    //     $setting = null;
    //     try{
    //         $setting = Cache::rememberForever('setting', function(){
    //             $setting_data = GlobalSetting::get();

    //             $setting = array();

    //             foreach($setting_data as $data_item){
    //                 $setting[$data_item->key] = $data_item->value;
    //             }

    //             $setting = (object) $setting;

    //             return $setting;
    //         });
    //     }catch(Exception $ex){
    //         Log::info($ex->getMessage());
    //     }
        
    //     $language_list = Language::where('status', 1)->get();
    //     $currency_list = Currency::where('status', 'active')->get();


    //     $lang_code = 'en';

    //     if($request->lang_code){
    //         $lang_code = $request->lang_code;
    //     }else{
    //         $default_lang = Language::where('id', 1)->first();
    //         if($default_lang){
    //             $lang_code = $default_lang->lang_code;
    //         }else{
    //             $lang_code = 'en';
    //         }
    //     }

    //     try{

    //         $localizations = include(lang_path($lang_code.'/translate.php'));
    //     }catch(Exception $ex){
    //         return response()->json([
    //             'message' => trans('Localication unprocessable')
    //         ],403);
    //     }

    //     $splash_screens = (object)array(
    //         'splash_screen1' => $setting->splash_screen1 ?? '',
    //         'splash_screen2' => $setting->splash_screen2 ?? '',
    //         'splash_screen3' => $setting->splash_screen3 ?? '',
    //         'splash_screen1_title' => $setting->splash_screen1_title ?? '',
    //         'splash_screen2_title' => $setting->splash_screen2_title ?? '',
    //         'splash_screen3_title' => $setting->splash_screen3_title ?? '',
    //     );

    //     return response()->json([
    //         'setting' => $setting,
    //         'language_list' => $language_list,
    //         'currency_list' => $currency_list,
    //         'localizations' => $localizations,
    //         'splash_screens' => $splash_screens,
    //     ]);
    // }
    
    
    
     public function website_setup(Request $request){

        $setting = null;
        try{
            $setting = Cache::rememberForever('setting', function(){
                $setting_data = GlobalSetting::get();

                $setting = array();

                foreach($setting_data as $data_item){
                    $setting[$data_item->key] = $data_item->value;
                }

                $setting = (object) $setting;

                return $setting;
            });
        }catch(Exception $ex){
            Log::info($ex->getMessage());
        }
        
        $language_list = Language::where('status', 1)->get();
        $currency_list = Currency::where('status', 'active')->get();


        $lang_code = 'en';

        if($request->lang_code){
            $lang_code = $request->lang_code;
        }else{
            $default_lang = Language::where('id', 1)->first();
            if($default_lang){
                $lang_code = $default_lang->lang_code;
            }else{
                $lang_code = 'en';
            }
        }

        try{

            $localizations = include(lang_path($lang_code.'/translate.php'));
        }catch(Exception $ex){
            return response()->json([
                'message' => trans('Localication unprocessable')
            ],403);
        }

        $splash_screens = (object)array(
            'splash_screen1' => $setting->splash_screen1 ?? '',
            'splash_screen2' => $setting->splash_screen2 ?? '',
            'splash_screen3' => $setting->splash_screen3 ?? '',
            'splash_screen1_title' => $setting->splash_screen1_title ?? '',
            'splash_screen2_title' => $setting->splash_screen2_title ?? '',
            'splash_screen3_title' => $setting->splash_screen3_title ?? '',
        );

        $addons = [];

        if (checkModule('Wallet')) {
            $addons['wallet'] = true;
        } else {
            $addons['wallet'] = false;
        }
        
        if (checkModule('Subscription')) {
            $addons['subscription'] = true;
        } else {
            $addons['subscription'] = false;
        }
        
        if (checkModule('Refund')) {
            $addons['refund'] = true;
        } else {
            $addons['refund'] = false;
        }

        if (checkModule('LiveChat')) {
            $addons['LiveChat'] = true;
        } else {
            $addons['LiveChat'] = false;
        }
        
        return response()->json([
            'setting' => $setting,
            'language_list' => $language_list,
            'currency_list' => $currency_list,
            'localizations' => $localizations,
            'splash_screens' => $splash_screens,
            'addons' => $addons,
  
        ]);
    }



      public function index(Request $request)
    {
        $theme_setting = GlobalSetting::where('key', 'selected_theme')->first();

        if($theme_setting->value == 'all_theme'){
            if($request->has('theme')){
                $theme = $request->theme;
                if($theme == 'one'){
                    Session::put('selected_theme', 'theme_one');
                }elseif($theme == 'two'){
                    Session::put('selected_theme', 'theme_two');
                }else{
                    if(!Session::has('selected_theme')){
                        Session::put('selected_theme', 'theme_one');
                    }
                }
            }else{
                Session::put('selected_theme', 'theme_one');
            }
        }else{
            if($theme_setting->value == 'theme_one'){
                Session::put('selected_theme', 'theme_one');
            }elseif($theme_setting->value == 'theme_two'){
                Session::put('selected_theme', 'theme_two');
            }
        }

        $homepage = Homepage::first();

        $featured_services = Listing::with('seller')->where(['status' => 'enable', 'approved_by_admin' => 'approved', 'is_featured' => 'enable'])->latest()->take(10)->get();


        $job_posts = JobPost::where(['status' => 'enable', 'approved_by_admin' => 'approved'])->latest()->take(10)->get();

        $top_sellers = User::where(['status' => 'enable' , 'is_banned' => 'no', 'is_seller' => 1, 'is_top_seller' => 'enable'])->where('email_verified_at', '!=', null)->select('id', 'username', 'name', 'image', 'status', 'is_banned', 'is_seller', 'is_top_seller', 'designation', 'hourly_payment','kyc_status','online_status','online')->orderBy('id','desc')->take(5)->get();

        $testimonials = Testimonial::where('status', 'active')->latest()->get();

        $latest_testimonials = Testimonial::where('status', 'active')->get();

        $latest_services = Listing::with('seller')->where(['status' => 'enable', 'approved_by_admin' => 'approved'])->latest()->take(5)->get();

        $seo_setting = SeoSetting::where('id', 1)->first();

        $categories = Category::where('status', 'enable')->latest()->take(4)->get();

        $slider = Slider::where('status', 'active')->latest()->get();

        $filter_array = array();
        foreach($categories as $category){
            $filter_array[] = $category->id;
        }

        $home2_filter_service = Listing::with('seller')->where(['status' => 'enable', 'approved_by_admin' => 'approved'])->whereIn('category_id', $filter_array)->latest()->take(8)->get();

        $categories = Category::where('status', 'enable')->latest()->get();

        $selected_theme = Session::get('selected_theme');
      return response()->json([
            'seo_setting' => $seo_setting,
                'homepage' => $homepage,
                'categories' => $categories,
                'featured_services' => $featured_services,
                'job_posts' => $job_posts,
                'top_sellers' => $top_sellers,
                'testimonials' => $testimonials,
                'latest_testimonials' => $latest_testimonials,
                'latest_services' => $latest_services,
                'home2_filter_service' => $home2_filter_service,
                'slider' => $slider,
        ]);
        
    }
    
    public function all_categories(Request $request){

        $categories = Category::where('status', 'enable')->latest()->get();

        return response()->json([
            'categories' => $categories
        ]);
    }

    public function freelancers(Request $request)
    {
        $sellers = User::where(['status' => 'enable' , 'is_banned' => 'no', 'is_seller' => 1])->where('email_verified_at', '!=', null)->select('id', 'username', 'name', 'image', 'status', 'is_banned', 'is_seller', 'is_top_seller', 'designation', 'hourly_payment','kyc_status','online_status','online');

        if($request->is_toprated){
            if($request->is_toprated == 'toprated'){
                $sellers = $sellers->where('is_top_seller', 'enable');
            }
        }

        if($request->category){
            $category = Category::where('id', $request->category)->first();
            if($category){
                $sellers = $sellers->whereHas('listings', function ($query) use ($request, $category) {
                    $query->where('category_id', $category->id);
                });

            }
        }

        if($request->sort_by){
            if($request->sort_by == 'a_to_z'){
                $sellers = $sellers->orderBy('name', 'asc');
            }elseif($request->sort_by == 'z_to_a'){
                $sellers = $sellers->orderBy('name', 'desc');
            }
        }else{
            $sellers = $sellers->latest();
        }

        if($request->price_filter){
            if($request->price_filter == 'low_to_high'){
                $sellers = $sellers->orderBy('hourly_payment', 'asc');
            }elseif($request->price_filter == 'high_to_low'){
                $sellers = $sellers->orderBy('hourly_payment', 'desc');
            }
        }


        if($request->search){
            $sellers = $sellers->where('name', 'like', '%' . $request->search . '%');
        }


        $sellers = $sellers->paginate(15);
        
        return response()->json([
            'sellers' => $sellers
        ]);
    }

    public function freelancers_filter_elements(Request $request){

        $categories = Category::where('status', 'enable')->latest()->get();

        $sort_by = (object) array(
            'a_to_z' => 'a_to_z',
            'z_to_a' => 'z_to_a',
        );

        $price_filter = (object) array(
            'low_to_high' => 'low_to_high',
            'high_to_low' => 'high_to_low',
        );

        return response()->json([
            'sort_by' => $sort_by,
            'price_filter' => $price_filter,
            'is_toprated' => 'toprated',
            'categories' => $categories,
        ]);

    }

    

    public function freelancer($username)
    {
        $seller = User::where(['status' => 'enable' , 'is_banned' => 'no', 'is_seller' => 1, 'username' => $username])->where('email_verified_at', '!=', null)->first();

        if(!$seller){
            return response()->json([
                'message' => trans('Not Found')
            ], 403);
        }

        $total_job_done = JobRequest::where('seller_id', $seller->id)->where('status', 'approved')->count();

        $total_service = Listing::where(['status' => 'enable', 'approved_by_admin' => 'approved', 'seller_id' => $seller->id ])->count();

        $services = Listing::where(['status' => 'enable', 'approved_by_admin' => 'approved', 'seller_id' => $seller->id ])->latest()->get();

        $review_list = Review::with('buyer')->where('seller_id', $seller->id)->where('status', 'enable')->latest()->get();

        $total_ratings = $review_list->count();
        $avg_ratings = $review_list->avg('rating');


        // Initialize an array to hold the counts of each rating
        $ratingCounts = [];
        foreach ($review_list as $review) {
            $rating = $review->rating;
            if (!isset($ratingCounts[$rating])) {
                $ratingCounts[$rating] = 0;
            }
            $ratingCounts[$rating]++;
        }

        // Calculate the percentage for each rating (1 to 5)
        $ratingData = [];
        for ($i = 1; $i <= 5; $i++) {
            $count = isset($ratingCounts[$i]) ? $ratingCounts[$i] : 0;
            $percentage = $total_ratings ? ($count / $total_ratings) * 100 : 0;
            $ratingData[$i] = [
                'count' => $count,
                'percentage' => $percentage
            ];
        }

        $able_to_live_chat = false;

        if(checkModule('LiveChat')){
            $able_to_live_chat = true;
        }


        return response()->json([
            'seller' => $seller,
            'total_job_done' => $total_job_done,
            'total_service' => $total_service,
            'services' => $services,
            'review_list' => $review_list,
            'total_ratings' => $total_ratings,
            'avg_ratings' => $avg_ratings,
            'rating_data' => $ratingData,
            'able_to_live_chat' => $able_to_live_chat,
        ]);
    }


    public function job_posts(Request $request)
    {
        $job_posts = JobPost::where(['status' => 'enable', 'approved_by_admin' => 'approved']);

        if($request->city_id){
            $job_posts = $job_posts->where('city_id', $request->city_id);
        }

        if($request->category_id){
            $job_posts = $job_posts->where('category_id', $request->category_id);
        }

        if($request->search){
            $job_posts = $job_posts->whereHas('front_translate', function ($query) use ($request) {
                            $query->where('title', 'like', '%' . $request->search . '%')
                                ->orWhere('description', 'like', '%' . $request->search . '%');
                        });
        }

        $job_posts = $job_posts->latest()->paginate(10);
        $job_posts = $job_posts->appends($request->all());

        return response()->json([
            'job_posts' => $job_posts
        ]);
    }

    public function job_posts_filter_elements(Request $request){
        $categories = Category::where('status', 'enable')->latest()->get();

        $cities = City::latest()->get();

        return response()->json([
            'categories' => $categories,
            'cities' => $cities,
        ]);

    }

    

    public function job_post(Request $request, $slug)
    {
        $job_post = JobPost::with('category', 'city')->where(['status' => 'enable', 'approved_by_admin' => 'approved'])->where('slug', $slug)->first();

        if(!$job_post){
            return response()->json([
                'message' => trans('Not Found')
            ], 403);
        }

        $total_job_by_author = JobRequest::where(['status' => 'enable', 'status' => 'approved'])->where('user_id', $job_post->user_id)->count();


        $author = User::select('id', 'name', 'email', 'image', 'username', 'address', 'created_at')->where('id', $job_post->user_id)->first();

        return response()->json([
            'job_post' => $job_post, 
            'author' => $author, 
            'total_job_by_author' => $total_job_by_author
        ]);
    }


    public function privacy_policy()
    {
        $privacy_policy = PrivacyPolicy::first();

        return response()->json([
            'privacy_policy' => $privacy_policy
        ]);
    }


    public function terms_conditions()
    {
        $terms_conditions = TermAndCondition::first();

        $seo_setting = SeoSetting::where('id', 6)->first();

        return response()->json([
            'terms_conditions' => $terms_conditions
        ]);
    }

    public function services(Request $request)
    {
        $services = Listing::with('seller')->where(['status' => 'enable', 'approved_by_admin' => 'approved' ]);

        if($request->is_featured){
            if($request->is_featured == 'featured'){
                $services = $services->where('is_featured', 'enable');
            }
        }


        $subCategory = collect();

        if($request->category){
            $category = Category::where('id', $request->category)->first();
            if($category){
                $services = $services->where('category_id', $category->id);

                $subCategory = SubCategory::where('category_id', $category->id)->get();
            }
        }

        if($request->sub_category){
            $sub_category = SubCategory::where('id', $request->sub_category)->first();
            if($sub_category){
                $services = $services->where('sub_category_id', $sub_category->id);
            }
        }

        if($request->price_filter){
            if($request->price_filter == 'low_to_high'){
                $services = $services->whereHas('listing_package', function ($query) use ($request) {
                    $query->orderBy('basic_price', 'asc');
                });
            }elseif($request->price_filter == 'high_to_low'){
                $services = $services->whereHas('listing_package', function ($query) use ($request) {
                    $query->orderBy('basic_price', 'desc');
                });
            }

        }

        if($request->search){
            $services = $services->whereHas('front_translate', function ($query) use ($request) {
                            $query->where('title', 'like', '%' . $request->search . '%')
                                ->orWhere('description', 'like', '%' . $request->search . '%');
                        });
        }


        if($request->sort_by){
            if($request->sort_by == 'a_to_z'){
                $services = $services->whereHas('front_translate', function ($query) use ($request) {
                    $query->orderBy('title', 'asc');
                });
            }elseif($request->sort_by == 'z_to_a'){
                $services = $services->whereHas('front_translate', function ($query) use ($request) {
                    $query->orderBy('title', 'desc');
                });
            }
        }else{
            $services = $services->latest();
        }

        $services = $services->paginate(10);

        return response()->json([
            'services' => $services
        ]);
    }

    public function service_filter_elements(Request $request){
        $categories = Category::where('status', 'enable')->latest()->get();

        $sub_categories = SubCategory::where('status', 'enable')->latest()->get();

        $sort_by = (object) array(
            'a_to_z' => 'a_to_z',
            'z_to_a' => 'z_to_a',
        );

        return response()->json([
            'sort_by' => $sort_by,
            'categories' => $categories,
            'sub_categories' => $sub_categories,
            'is_featured' => 'featured',
        ]);

    }

    public function service(Request $request, $slug)
    {
        $service = Listing::with('seller','listing_package')->where(['status' => 'enable', 'approved_by_admin' => 'approved', 'slug' => $slug])->firstOrFail();

        if(!$service){
            return response()->json([
                'message' => trans('Not Found')
            ], 403);
        }

        $galleries = ListingGallery::where('listing_id', $service->id)->latest()->get();

        $seller = User::where(['status' => 'enable' , 'is_banned' => 'no', 'is_seller' => 1, 'id' => $service->seller_id])->where('email_verified_at', '!=', null)->select('id', 'username', 'name', 'image', 'status', 'is_banned', 'is_seller', 'is_top_seller', 'designation', 'hourly_payment','kyc_status','online_status','online')->orderBy('id','desc')->firstOrFail();

        $total_job_done = JobRequest::where('seller_id', $seller->id)->where('status', 'approved')->count();

        $total_service = Listing::where(['status' => 'enable', 'approved_by_admin' => 'approved', 'seller_id' => $seller->id ])->count();

        $service_package = ListingPackage::where('listing_id', $service->id)->first();

        $review_list = Review::with('buyer')->where('listing_id', $service->id)->where('status', 'enable')->latest()->get();

        $total_ratings = $review_list->count();
        $avg_ratings = $review_list->avg('rating');


        // Initialize an array to hold the counts of each rating
        $ratingCounts = [];
        foreach ($review_list as $review) {
            $rating = $review->rating;
            if (!isset($ratingCounts[$rating])) {
                $ratingCounts[$rating] = 0;
            }
            $ratingCounts[$rating]++;
        }

        // Calculate the percentage for each rating (1 to 5)
        $ratingData = [];
        for ($i = 1; $i <= 5; $i++) {
            $count = isset($ratingCounts[$i]) ? $ratingCounts[$i] : 0;
            $percentage = $total_ratings ? ($count / $total_ratings) * 100 : 0;
            $ratingData[$i] = [
                'count' => $count,
                'percentage' => $percentage
            ];
        }

        $able_to_live_chat = false;

        if(checkModule('LiveChat')){
            $able_to_live_chat = true;
        }

        return response()->json([
            'service' => $service,
            'service_package' => $service_package,
            'galleries' => $galleries,
            'review_list' => $review_list,
            'seller' => $seller,
            'total_job_done' => $total_job_done,
            'total_service' => $total_service,
            'total_ratings' => $total_ratings,
            'avg_ratings' => $avg_ratings,
            'rating_data' => $ratingData,
            'able_to_live_chat' => $able_to_live_chat,
        ]);
    }



    public function language_switcher(Request $request){


        $request_lang = Language::where('lang_code', $request->lang_code)->first();

        Session::put('front_lang', $request->lang_code);
        Session::put('front_lang_name', $request_lang->lang_name);
        Session::put('lang_dir', $request_lang->lang_direction);

        app()->setLocale($request->lang_code);



        $notify_message= trans('translate.Language switched successful');
        if(env('APP_MODE') == 'DEMO'){
            $notify_message=array('message'=>$notify_message,'alert-type'=>'success', 'demo_mode' => 'Demo mode not tranlsate all language');
        }else{
            $notify_message=array('message'=>$notify_message,'alert-type'=>'success');
        }


        return redirect()->back()->with($notify_message);

    }


    public function currency_switcher(Request $request){

        $request_currency = Currency::where('currency_code', $request->currency_code)->first();

        Session::put('currency_name', $request_currency->currency_name);
        Session::put('currency_code', $request_currency->currency_code);
        Session::put('currency_icon', $request_currency->currency_icon);
        Session::put('currency_rate', $request_currency->currency_rate);
        Session::put('currency_position', $request_currency->currency_position);

        $notify_message= trans('translate.Currency switched successful');
        $notify_message=array('message'=>$notify_message,'alert-type'=>'success');
        return redirect()->back()->with($notify_message);

    }




    public function download_submission_file($file){
       
        $filepath = public_path("uploads/custom-images/{$file}");

        $extension = pathinfo($file, PATHINFO_EXTENSION);

        $downloadName = 'Submission File.' . $extension;

        return response()->download($filepath, $downloadName);

    }


    public function slider()
    {

        $sliders = Slider::get();

        return response()->json([
            'sliders' => $sliders
        ]);
    }


    public function about_us()
    {
        $about_us = AboutUs::first();

        $homepage = Homepage::first();

        $testimonials = Testimonial::where('status', 'active')->latest()->get();

        $latest_testimonials = Testimonial::where('status', 'active')->get();

        $faqs = Faq::latest()->get();

        $seo_setting = SeoSetting::where('id', 3)->first();

        return response()->json([
            'seo_setting' => $seo_setting,
            'about_us' => $about_us,
            'homepage' => $homepage,
            'testimonials' => $testimonials,
            'latest_testimonials' => $latest_testimonials,
            'faqs' => $faqs,
        ]);
    }

    public function contact_us()
    {
        $contact_us = ContactUs::first();

        $seo_setting = SeoSetting::where('id', 4)->first();

        return response()->json([
           'contact_us' => $contact_us,
           'seo_setting' => $seo_setting,
        ]);
    }

    public function faq()
    {
        $faqs = Faq::latest()->get();

        $seo_setting = SeoSetting::where('id', 5)->first();

        return response()->json([
            'faqs' => $faqs,
            'seo_setting' => $seo_setting,
        ]);
    }


}
