<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\BlogSavedByUser;
use App\Models\Comment;
use App\Models\CommentLikeByUser;
use App\Models\GoldRate;
use App\Models\Reply;
use App\Models\ReplyLikeByUser;
use App\Models\SubCategory;
use Illuminate\Http\Request;
use App\Helpers\myfunctions;
use App\Models\QuerySetting;
use App\Models\SiteContent;
use App\Models\Category;
use App\Models\Banner;
use App\Models\Coupon;
use App\Models\Store;
use App\Models\Blog;
use App\Models\Page;
use Remls\HijriDate\HijriDate;

class HomeController extends Controller
{
    //

    public function Index()
    {
        $blogs = Blog::with(['category:id,name', 'sub_category:id,name'])->where(['blogs.status' =>'publish'])->limit(4)
            ->orderby('id','desc')
            ->get();
        $latestblogs = Blog::with(['category:id,name', 'sub_category:id,name'])->orderby('id','desc')->limit(4)->where(['blogs.type'  =>'latest', 'blogs.status' =>'publish'])->get();
        $popularblogs = Blog::with(['category:id,name', 'sub_category:id,name'])->orderby('id','desc')->limit(4)->where(['blogs.type'  =>'popular', 'blogs.status' =>'publish'])->get();
        $featuredblogs = Blog::with(['category:id,name', 'sub_category:id,name'])->orderby('id','desc')->limit(6)->where(['blogs.type'  =>'featured', 'blogs.status' =>'publish'])->get();
        $topblogs = Blog::with(['category:id,name', 'sub_category:id,name'])->inRandomOrder()->limit(5)->where(['blogs.type'  =>'featured', 'blogs.status' =>'publish'])->get();
        $popblogs = Blog::with(['category:id,name', 'sub_category:id,name'])->inRandomOrder()->limit(4)->where(['blogs.type'  =>'popular', 'blogs.status' =>'publish'])->get();
        $category_blogs = Category::limit(5)->get();
        $categories = Category::orderby('id','asc')->limit(5)->get(); 

        $content = SiteContent::orderby('id', 'desc')->first();

        // $data = json_encode(array('currency' => 'USD', 'sort' => 'rank', 'order' => 'ascending', 'offset' => 0, 'limit' => 10, 'meta' => true));
        // $context_options = array(
        //     'http' => array(
        //         'method' => 'POST',
        //         'header' => "Content-type: application/json\r\n"
        //             . "x-api-key: 9615a53f-f047-4579-bb50-94718ff5ceaa" . "\r\n",
        //         'content' => $data
        //     )
        // );
        // $context = stream_context_create($context_options);
        // $fp = fopen('https://api.livecoinwatch.com/coins/list', 'r', false, $context);
        // $jsonData = json_decode(stream_get_contents($fp));
        // dd($jsonData);
        return view('user.pages.index', get_defined_vars());
    }

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

    public function Stores()
    {
        $query = QuerySetting::find(1);
        if ($query->storepage_stores == 'limit()') {
            $stores = Store::limit($query->storepage_stores_limit)->get();
        } else if ($query->storepage_stores == 'paginate()') {
            $stores = Store::inRandomOrder()->paginate($query->storepage_stores_limit);
        } else if ($query->storepage_stores == 'inRandomOrder()') {
            $stores = Store::inRandomOrder()->get();
        } else if ($query->storepage_stores == 'inRandomOrder()->limit()') {
            $stores = Store::inRandomOrder()->limit($query->storepage_stores_limit)->get();
        } else if ($query->storepage_stores == 'Orderby()') {
            $stores = Store::orderby($query->storepage_stores_orderby_key1, $query->storepage_stores_orderby_key2)->get();
        } else if ($query->storepage_stores == 'Orderby()->limit()') {
            $stores = Store::orderby($query->storepage_stores_orderby_key1, $query->storepage_stores_orderby_key2)->limit($query->storepage_stores_limit)->get();
        } else {
            $stores = Store::orderby('name', 'asc')->paginate(48);
        }
        // $stores = Store::orderBy('name', 'asc')->get();
        // $storesgroup = $stores->reduce(function ($carry, $store) {

        //     // get first letter
        //     $first_letter = $store['name'][0];

        //     if ( !isset($carry[$first_letter]) ) {
        //         $carry[$first_letter] = [];
        //     }

        //     $carry[$first_letter][] = $store;

        //     return $carry;

        // }, []);


        // return view('user.pages.stores',compact('stores'))->with('storesgroup',$storesgroup);
        return view('user.pages.stores', get_defined_vars());
    }

    public function StoreProfile($slug)
{
    $store = Store::select('stores.*', 'categories.name as category')
        ->leftJoin('categories', 'categories.id', '=', 'stores.category_id')
        ->where('stores.slug', $slug)
        ->first();

    $query = QuerySetting::find(1);

    // Null check
    if (!$query) {
        // Set some default fallback data if QuerySetting not found
        $stores = Store::limit(15)->get();
        $categories = Category::limit(5)->get();
        $coupons = Coupon::select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
            ->leftJoin('categories', 'coupons.category_id', 'categories.id')
            ->leftJoin('stores', 'coupons.store_id', 'stores.id')
            ->where('coupons.store_id', $store->id)
            ->get();
        return view('user.pages.store-profile', compact('store', 'stores', 'categories', 'coupons'));
    }

    // STORES section
    if ($query->storeprofilepage_stores == 'limit()') {
        $stores = Store::limit($query->storeprofilepage_stores_limit)->get();
    } elseif ($query->storeprofilepage_stores == 'inRandomOrder()') {
        $stores = Store::inRandomOrder()->get();
    } elseif ($query->storeprofilepage_stores == 'inRandomOrder()->limit()') {
        $stores = Store::inRandomOrder()->limit($query->storeprofilepage_stores_limit)->get();
    } elseif ($query->storeprofilepage_stores == 'Orderby()') {
        $stores = Store::orderBy($query->storeprofilepage_stores_orderby_key1, $query->storeprofilepage_stores_orderby_key2)->get();
    } elseif ($query->storeprofilepage_stores == 'Orderby()->limit()') {
        $stores = Store::orderBy($query->storeprofilepage_stores_orderby_key1, $query->storeprofilepage_stores_orderby_key2)
            ->limit($query->storeprofilepage_stores_limit)->get();
    } else {
        $stores = Store::limit(15)->get();
    }

    // CATEGORIES section
    if ($query->storeprofilepage_categories == 'limit()') {
        $categories = Category::limit($query->storeprofilepage_categories_limit)->get();
    } elseif ($query->storeprofilepage_categories == 'inRandomOrder()') {
        $categories = Category::inRandomOrder()->get();
    } elseif ($query->storeprofilepage_categories == 'inRandomOrder()->limit()') {
        $categories = Category::inRandomOrder()->limit($query->storeprofilepage_categories_limit)->get();
    } elseif ($query->storeprofilepage_categories == 'Orderby()') {
        $categories = Category::orderBy($query->storeprofilepage_categories_orderby_key1, $query->storeprofilepage_categories_orderby_key2)->get();
    } elseif ($query->storeprofilepage_categories == 'Orderby()->limit()') {
        $categories = Category::orderBy($query->storeprofilepage_categories_orderby_key1, $query->storeprofilepage_categories_orderby_key2)
            ->limit($query->storeprofilepage_categories_limit)->get();
    } else {
        $categories = Category::limit(5)->get();
    }

    // COUPONS section
    if ($query->storeprofilepage_coupons == 'limit()') {
        $coupons = Coupon::select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
            ->leftJoin('categories', 'coupons.category_id', 'categories.id')
            ->leftJoin('stores', 'coupons.store_id', 'stores.id')
            ->where('coupons.store_id', $store->id)
            ->limit($query->storeprofilepage_coupons_limit)->get();
    } elseif ($query->storeprofilepage_coupons == 'inRandomOrder()') {
        $coupons = Coupon::select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
            ->leftJoin('categories', 'coupons.category_id', 'categories.id')
            ->leftJoin('stores', 'coupons.store_id', 'stores.id')
            ->where('coupons.store_id', $store->id)
            ->inRandomOrder()->get();
    } elseif ($query->storeprofilepage_coupons == 'inRandomOrder()->limit()') {
        $coupons = Coupon::select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
            ->leftJoin('categories', 'coupons.category_id', 'categories.id')
            ->leftJoin('stores', 'coupons.store_id', 'stores.id')
            ->where('coupons.store_id', $store->id)
            ->inRandomOrder()->limit($query->storeprofilepage_coupons_limit)->get();
    } elseif ($query->storeprofilepage_coupons == 'Orderby()') {
        $coupons = Coupon::select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
            ->leftJoin('categories', 'coupons.category_id', 'categories.id')
            ->leftJoin('stores', 'coupons.store_id', 'stores.id')
            ->where('coupons.store_id', $store->id)
            ->orderByRaw("CAST($query->storeprofilepage_coupons_orderby_key1 AS UNSIGNED) $query->storeprofilepage_coupons_orderby_key2")->get();
    } elseif ($query->storeprofilepage_coupons == 'Orderby()->limit()') {
        $coupons = Coupon::select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
            ->leftJoin('categories', 'coupons.category_id', 'categories.id')
            ->leftJoin('stores', 'coupons.store_id', 'stores.id')
            ->where('coupons.store_id', $store->id)
            ->orderBy($query->storeprofilepage_coupons_orderby_key1, $query->storeprofilepage_coupons_orderby_key2)
            ->limit($query->categorypage_coupons_limit)->get();
    } else {
        $coupons = Coupon::select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
            ->leftJoin('categories', 'coupons.category_id', 'categories.id')
            ->leftJoin('stores', 'coupons.store_id', 'stores.id')
            ->where('coupons.store_id', $store->id)->get();
    }

    return view('user.pages.store-profile', compact('store', 'stores', 'categories', 'coupons'));
}


    public function Categories()
    {
        $query = QuerySetting::find(1);

        if ($query->categorypage_categories == 'limit()') {

            $categories = Category::limit($query->categorypage_categories_limit)->get();
        } else if ($query->categorypage_categories == 'paginate()') {
            $categories = Category::paginate($query->categorypage_categories_limit);
        } else if ($query->categorypage_categories == 'inRandomOrder()') {
            $categories = Category::inRandomOrder()->get();
        } else if ($query->categorypage_categories == 'inRandomOrder()->limit()') {
            $categories = Category::inRandomOrder()->limit($query->categorypage_categories_limit)->get();
        } else if ($query->categorypage_categories == 'Orderby()') {
            $categories = Category::orderby($query->categorypage_categories_orderby_key1, $query->categorypage_categories_orderby_key2)->get();
        } else if ($query->categorypage_categories == 'Orderby()->limit()') {
            $categories = Category::orderby($query->categorypage_categories_orderby_key1, $query->categorypage_categories_orderby_key2)->limit($query->categorypage_categories_limit)->get();
        } else {
            $categories = Category::get();
        }
        return view('user.pages.categories', compact('categories'));
    }

    public function CategoryProfile($slug)
    {
        $category = Category::where('slug', $slug)
            ->first();
        $query = QuerySetting::find(1);
        if ($query->categoryprofilepage_stores == 'limit()') {
            $stores = Store::limit($$query->categoryprofilepage_stores_limit)->get();
        } else if ($query->categoryprofilepage_stores == 'inRandomOrder()') {
            $stores = Store::inRandomOrder()->get();
        } else if ($query->categoryprofilepage_stores == 'inRandomOrder()->limit()') {
            $stores = Store::inRandomOrder()->limit($query->categoryprofilepage_stores_limit)->get();
        } else if ($query->categoryprofilepage_stores == 'Orderby()') {
            $stores = Store::orderby($query->categoryprofilepage_stores_orderby_key1, $query->categoryprofilepage_stores_orderby_key2)->get();
        } else if ($query->categoryprofilepage_stores == 'Orderby()->limit()') {
            $stores = Store::orderby($query->categoryprofilepage_stores_orderby_key1, $query->categoryprofilepage_stores_orderby_key2)->limit($query->categoryprofilepage_stores_limit)->get();
        } else {
            $stores = Store::limit(15)->get();
        }

        if ($query->categoryprofilepage_categories == 'limit()') {

            $categories = Category::limit($query->categoryprofilepage_categories_limit)->get();
        } else if ($query->categoryprofilepage_categories == 'inRandomOrder()') {
            $categories = Category::inRandomOrder()->get();
        } else if ($query->categoryprofilepage_categories == 'inRandomOrder()->limit()') {
            $categories = Category::inRandomOrder()->limit($query->categoryprofilepage_categories_limit)->get();
        } else if ($query->categoryprofilepage_categories == 'Orderby()') {
            $categories = Category::orderby($query->categoryprofilepage_categories_orderby_key1, $query->categoryprofilepage_categories_orderby_key2)->get();
        } else if ($query->categoryprofilepage_categories == 'Orderby()->limit()') {
            $categories = Category::orderby($query->categoryprofilepage_categories_orderby_key1, $query->categoryprofilepage_categories_orderby_key2)->limit($query->categoryprofilepage_categories_limit)->get();
        } else {
            $categories = Category::limit(5)->get();
        }

        if ($query->categoryprofilepage_coupons == 'limit()') {

            $coupons = Coupon::Select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
                ->leftjoin('categories', 'categories.id', 'coupons.category_id')
                ->leftjoin('stores', 'stores.id', 'coupons.store_id')->where('coupons.category_id', $category->id)->limit($query->categoryprofilepage_coupons_limit)->get();
        } else if ($query->categoryprofilepage_coupons == 'inRandomOrder()') {
            $coupons = Coupon::Select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
                ->leftjoin('categories', 'categories.id', 'coupons.category_id')
                ->leftjoin('stores', 'stores.id', 'coupons.store_id')->where('coupons.category_id', $category->id)->inRandomOrder()->get();
        } else if ($query->categoryprofilepage_coupons == 'inRandomOrder()->limit()') {
            $coupons = Coupon::Select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
                ->leftjoin('categories', 'categories.id', 'coupons.category_id')
                ->leftjoin('stores', 'stores.id', 'coupons.store_id')->where('coupons.category_id', $category->id)->inRandomOrder()->limit($query->categoryprofilepage_coupons_limit)->get();
        } else if ($query->categoryprofilepage_coupons == 'Orderby()') {
            $coupons = Coupon::Select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
                ->leftjoin('categories', 'categories.id', 'coupons.category_id')
                ->leftjoin('stores', 'stores.id', 'coupons.store_id')->where('coupons.category_id', $category->id)->orderby($query->categoryprofilepage_coupons_orderby_key1, $query->categoryprofilepage_coupons_orderby_key2)->get();
        } else if ($query->categoryprofilepage_coupons == 'Orderby()->limit()') {
            $coupons = Coupon::Select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
                ->leftjoin('categories', 'categories.id', 'coupons.category_id')
                ->leftjoin('stores', 'stores.id', 'coupons.store_id')->where('coupons.category_id', $category->id)->orderby($query->categoryprofilepage_coupons_orderby_key1, $query->categoryprofilepage_coupons_orderby_key2)->limit($query->categoryprofilepage_coupons_limit)->get();
        } else {
            $coupons = Coupon::Select('coupons.*', 'categories.feature_image as category_image', 'stores.feature_image as store_image')
                ->leftjoin('categories', 'categories.id', 'coupons.category_id')
                ->leftjoin('stores', 'stores.id', 'coupons.store_id')->where('coupons.category_id', $category->id)->get();
        }
        // dd($coupons);
        return view('user.pages.category-profile', compact('category', 'stores', 'categories', 'coupons'));
    }

    public function Blogs()
    {
        $query = QuerySetting::find(1);

        if ($query->blogpage_blogs == 'limit()') {

            $blogs = Blog::Select('blogs.*', 'categories.name as category')
                ->leftjoin('categories', 'categories.id', 'blogs.category_id')->limit($query->blogpage_blogs_limit)->get();
        } else if ($query->blogpage_blogs == 'paginate()') {
            $blogs = Blog::Select('blogs.*', 'categories.name as category')
                ->leftjoin('categories', 'categories.id', 'blogs.category_id')->paginate($query->blogpage_blogs_limit);
        } else if ($query->blogpage_blogs == 'inRandomOrder()') {
            $blogs = Blog::Select('blogs.*', 'categories.name as category')
                ->leftjoin('categories', 'categories.id', 'blogs.category_id')->inRandomOrder()->get();
        } else if ($query->blogpage_blogs == 'inRandomOrder()->limit()') {
            $blogs = Blog::Select('blogs.*', 'categories.name as category')
                ->leftjoin('categories', 'categories.id', 'blogs.category_id')->inRandomOrder()->limit($query->blogpage_blogs_limit)->get();
        } else if ($query->blogpage_blogs == 'Orderby()') {
            $blogs = Blog::Select('blogs.*', 'categories.name as category')
                ->leftjoin('categories', 'categories.id', 'blogs.category_id')->orderby($query->blogpage_blogs_orderby_key1, $query->blogpage_blogs_orderby_key2)->get();
        } else if ($query->blogpage_blogs == 'Orderby()->limit()') {
            $blogs = Blog::Select('blogs.*', 'categories.name as category')
                ->leftjoin('categories', 'categories.id', 'blogs.category_id')->orderby($query->blogpage_blogs_orderby_key1, $query->blogpage_blogs_orderby_key2)->limit($query->categorypage_categories_limit)->get();
        } else {
            $blogs = Blog::Select('blogs.*', 'categories.name as category')
                ->leftjoin('categories', 'categories.id', 'blogs.category_id')->get();
        }
        return view('user.pages.blogs', compact('blogs'));
    }

    public function BlogProfile($slug)
    {
        $blog = Blog::where('slug', $slug)->first();
        $categories = Category::orderby('id','asc')->limit(5)->get();
        $blogs = Blog::inRandomOrder()->limit(5)->where('status','publish')->get();
        $popularblogs = Blog::Select('blogs.*', 'categories.name as category')
            ->leftjoin('categories', 'categories.id', 'blogs.category_id')->inRandomOrder()->limit(8)->where(['blogs.type'=>'popular', 'blogs.status' => 'publish'])->get();
        $shareComponent = \Share::page(
            url()->current()
        )
            ->facebook()
            // ->instagram()
            ->twitter()
            ->linkedin()
            ->telegram()
            ->whatsapp()
            ->pinterest()
            ->reddit();
        $comments = Comment::with(['user', 'reply'])->orderby('id', 'desc')->where('blog_id', $blog->id)->get();
        $comment_count = $comments->count();
        // dd($comments); 
        return view('user.pages.blog-details', get_defined_vars());
    }

    public function Page($slug)
    {
        $page = Page::where('slug', $slug)->first();
        $categories = Category::orderby('id','asc')->limit(5)->get();
        $blogs = Blog::inRandomOrder()->limit(5)->where('status','publish')->get();
        return view('user.pages.info-page',get_defined_vars());
    }

    public function getstores(Request $request)
    {
        if (!empty($request->key)) {

            $blogs = Blog::where('title', 'like', '%' . $request->key . '%')->get();
            $stores = Store::where('name', 'like', '%' . $request->key . '%')->get();
            $key = $request->key;

            return view('user.pages.autocomplete', compact('blogs', 'stores', 'key'));

        }
    }




    public function update_coupon_used(Request $request)
    {
        $used = Coupon::where('id', $request->id)->first();
        if (!empty($used)) {
            $coupon = Coupon::where('id', $request->id)->update(array('total_use' => intval($used->total_use) + 1));

            return response()->json(['data' => $coupon, 'success' => true]);
        }
    }

    public function BlogsByCategory($slug)
    {
        $category = Category::select('id', 'name')->where('slug', $slug)->first();
        $categories = Category::orderby('id','asc')->limit(5)->get();
        $blogs = Blog::orderby('id','desc')->limit(5)->where('status','publish')->get();
        $subcategories = SubCategory::select('name', 'id')->where('category_id', $category->id)->get();
        $blogsbycategory = Blog::with(['category:id,name', 'sub_category:id,name'])
            ->where(['blogs.category_id'=> $category->id, 'blogs.status' =>'publish'])
            ->get();
        // dd($blogs);

        return view('user.pages.blogs-by-category', get_defined_vars());
    }

    public function BlogsBySubCategory($categoryslug, $subcategoryslug)
    {
        // dd($categoryslug);

        $category = Category::select('id', 'name')->where('slug', $categoryslug)->first();
        $categories = Category::orderby('id','asc')->limit(5)->get();
        $blogs = Blog::orderby('id','desc')->limit(5)->where('status','publish')->get();
        $subcategory = SubCategory::select('id', 'name')->where('slug', $subcategoryslug)->first();
        $blogsbysubcategory = Blog::with(['category:id,name', 'sub_category:id,name'])
            ->where(['blogs.sub_category_id'=> $subcategory->id, 'blogs.status' =>'publish'])
            ->get();

        return view('user.pages.blogs-by-subcategory', get_defined_vars());
    }

    public function getblogs(Request $request)
    {

        if (!empty($request->key)) {

            $blogs = Blog::where('title', 'like', '%' . $request->key . '%')->where('status','publish')->get();
            $stores = Store::where('name', 'like', '%' . $request->key . '%')->get();
            $key = $request->key;

            return view('user.pages.autocomplete', get_defined_vars());

        }
    }

    public function PrayerTimes()
    {
        $categories = Category::orderby('id','asc')->limit(5)->get();
        $blogs = Blog::inRandomOrder()->limit(5)->where('status','publish')->get();

        return view('user.pages.prayer-times', get_defined_vars());
    }
    public function GoldRates()
    {
         $data = array(    
                'INR',
                'PKR',
                'USD',
                'AED'
            );
            foreach ($data as $key => $code) {
                $currency_code = $code;
                $unit_type = "gram";
                $currency_code = strtolower($currency_code);
                $unit_type = strtolower($unit_type);
                $URL = "https://goldpricez.com/api/rates/currency/" . $currency_code . "/measure/" . $unit_type;
                $apiKey = "de3062c124177b4889b61d8d26896807de3062c1";
                $URL = strtolower($URL);
                
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $URL);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    //curl_setopt($ch,CURLOPT_HEADER, false); 
                    curl_setopt(
                        $ch,
                        CURLOPT_HTTPHEADER,
                        array(
                            'X-API-KEY: ' . $apiKey
                        )
                    );
                    $output = curl_exec($ch);
                    curl_close($ch);
                    
                $result = $output;
                $array1 = json_decode($result, true);
    
                $result = json_decode($array1, true);
                // dd($result);
    
                $current_gold_price = $result[$unit_type . '_in_' . $currency_code];  //Price in the currency of your choice (e.g., CAD)
                $ounce_gold_rate = $result['gram_in_usd'];
    
                if ($currency_code == 'usd') {
                    $gmt_datetime_gold_updated = $result['gmt_ounce_price_' . $currency_code . '_updated'];  //GMT time of gold price updation online (e.g., when the rates are updated)
                } else {
                    $gmt_datetime_gold_updated = $result['gmt_' . $currency_code . '_updated'];  //GMT time of gold price updation online (e.g., when the rates are updated)
                }
                $currency_rate = 1;
                $gmt_datetime_currency_updated = $gmt_datetime_gold_updated;
                if ($currency_code != 'usd') {
                    $currency_rate = $result['usd_to_' . $currency_code]; //Currrency conversion. 1 usd to currency of your choice (e.g., 1 USD = ... CAD)
                    //['usd_to_cad']
    
                    $gmt_datetime_currency_updated = $result['gmt_' . $currency_code . '_updated'];    //GMT time of gold price updation online (e.g., when the rates are updated)
                    //['gmt_pkr_updated'];
                }
                $result_array = serialize($result);
    
                // dd($result);
                $check = GoldRate::where('currency_code', $code)->whereDate('created_at',now()->today())->first();
                if ($check) {
                    $goldrate = GoldRate::find($check->id);
                    $goldrate->currency_code = $currency_code;
                    $goldrate->unit_type = $unit_type;
                    $goldrate->gold_rate = $current_gold_price;
                    $goldrate->ounce_gold_rate = $ounce_gold_rate;
                    $goldrate->currency_rate = $currency_rate;
                    $goldrate->karat24_rate = $currency_rate;
                    $goldrate->karat22_rate = ($currency_rate * 0.916);
                    $goldrate->karat21_rate = ($currency_rate * 0.875);
                    $goldrate->karat18_rate = ($currency_rate * 0.750);
                    $goldrate->gmt_datetime_gold_updated = $gmt_datetime_currency_updated;
    
                    $goldrate->update();
                } else {
                    $goldrate = new GoldRate;
                    $goldrate->currency_code = $currency_code;
                    $goldrate->unit_type = $unit_type;
                    $goldrate->gold_rate = $current_gold_price;
                    $goldrate->ounce_gold_rate = $ounce_gold_rate;
                    $goldrate->currency_rate = $currency_rate;
                    $goldrate->karat24_rate = $currency_rate;
                    $goldrate->karat22_rate = ($currency_rate * 0.916);
                    $goldrate->karat21_rate = ($currency_rate * 0.875);
                    $goldrate->karat18_rate = ($currency_rate * 0.750);
                    $goldrate->gmt_datetime_gold_updated = $gmt_datetime_currency_updated;
    
                    $goldrate->save();
                }
    
            }
         
        $categories = Category::orderby('id','asc')->limit(5)->get();
        $blogs = Blog::inRandomOrder()->limit(5)->where('status','publish')->get();
        $goldrates = GoldRate::whereDate('created_at', now()->today())->get();

        return view('user.pages.gold', get_defined_vars());
    }

    public function ForexCrypto()
    {
        $categories = Category::inRandomOrder()->limit(5)->get();
        $blogs = Blog::inRandomOrder()->limit(5)->where('status','publish')->get();
        return view('user.pages.forex-crypto', get_defined_vars());
    }

    public function BlogSave(Request $request)
    {
        $blogsave = BlogSavedByUser::where(['user_id' => \Auth::id(), 'blog_id' => $request->blog_id])->first();
        if (!$blogsave) {
            $blogsave = new BlogSavedByUser;
            $blogsave->user_id = \Auth::id();
            $blogsave->blog_id = $request->blog_id;
            if ($blogsave->save()) {
                
                return response()->json(['success' => 'Blog added on wishlist!']);
            } else {

                return response()->json(['success' => 'Something went wrong!']);
            }
        }
        else
        {
          $blogsave->delete();
          return response()->json(['success' => 'Blog removed from wishlist!']);
        }
    }

    public function StoreComment(Request $request)
    {
        $comment = new Comment([
            'blog_id' => $request->input('blog_id'),
            'user_id' => $request->input('user_id'),
            'comment' => $request->input('comment'),

        ]);
        $comment->save();
        return response()->json(['success' => 'Commented!']);
    }

    public function StoreReply(Request $request)
    {
        $reply = new Reply([
            'user_id' => $request->input('user_id'),
            'comment_id' => $request->input('comment_id'),
            'reply' => $request->input('reply'),

        ]);
        $reply->save();
        return response()->json(['success' => 'Replied!']);
    }

    public function LikeComment(Request $request)
    {
        // dd($request->all());
        $comment = Comment::find($request->comment_id);
        $like = CommentLikeByUser::where(['user_id' => \Auth::id(), 'comment_id' => $comment->id])->first();
        if (!$like) {
            $like = new CommentLikeByUser;
            $like->user_id = \Auth::id();
            $like->comment_id = $comment->id;
            $like->likes = 1;
            $like->save();
            return response()->json(['success' => 'Comment Liked!']);

        } else {

            $like->delete();
            return response()->json(['success' => 'Comment Unlike!']);

        }
    }

    public function LikeReply(Request $request)
    {
        $reply = Reply::find($request->reply_id);
        $like = ReplyLikeByUser::where(['user_id' => \Auth::id(), 'reply_id' => $reply->id])->first();
        if (!$like) {
            $like = new ReplyLikeByUser;
            $like->user_id = \Auth::id();
            $like->reply_id = $reply->id;
            $like->likes = 1;
            $like->save();

            return response()->json(['success' => 'Reply Liked!']);
        } else {

            $like->delete();
            return response()->json(['success' => 'Reply Unlike!']);
        }
    }

    public function DeleteComment(Request $request)
    {
        // dd($request->all());
        $comment = Comment::find($request->comment_id);
        $comment->delete();
        return response()->json(['success' => 'Comment Deleted!']);
    }

    public function DeleteReply(Request $request)
    {
        $reply = Reply::find($request->reply_id);
        $reply->delete();
        return response()->json(['success' => 'Reply Deleted!']);
    }
}

