<?php
use App\Models\Ad;
use Carbon\Carbon;
use App\Models\Tag;
use App\Models\Menu;
use App\Models\Page;
use App\Models\Post;
use App\Models\User;
use App\Models\Event;
use App\Models\Photo;
use App\Models\Client;
use App\Models\Design;
use App\Models\Member;
use App\Models\Slider;
use App\Models\Partner;
use App\Models\Product;
use App\Models\Service;
use App\Models\Category;
use App\Models\Magazine;
use App\Constants\Status;
use App\Models\Photobody;
use App\Models\SubCategory;
use App\Models\Testimonial;
use Illuminate\Support\Str;
use App\Models\VideoGallery;
use App\Models\DesignContent;
use App\Models\GeneralSetting;
use App\Models\ParentCategory;
use Illuminate\Support\Facades\Route;

function view_date_format($date,$format='d-m-Y'){
    return Carbon::parse($date)->format($format);
}
function store_date_format($date){
    return Carbon::parse($date)->format('Y-m-d');
}


function getStatusBadge($status)
{
    $badges = [
        Status::PENDING => 'warning',
        Status::DELIVERED => 'success',
        Status::FAILED => 'danger',
    ];

    $badgeClass = $badges[$status] ?? 'secondary';

    return '<span class="badge badge-' . $badgeClass . '">' . ucfirst($status) . '</span>';
}

//BD number validation
function isValidBangladeshiNumber($number)
{
    return preg_match('/^(?:\+?88)?01[3-9]\d{8}$/', $number);
}


if(!function_exists('activeMenu')) {
    function activeMenu($routeName=''){
        $route = Route::currentRouteName(); 
        if($route == $routeName){
            return 'active';
        }else{
            return '';
        }
    }
}
function active_event(){
    return Event::where('status',1)->orderBy('id','desc')->first();
}
function partner_query($take=20, $skip=0, $order='asc'){
    return Partner::OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function partner_url($partner) {
    return route('single.partner', ['slug' => make_slug($partner->slug)]);
}
function event_url($event) {
    return route('single.event', ['id' => $event->id, 'title' => make_slug($event->headline)]);
}
function setting($col='') {
    if($col != null){
        return GeneralSetting::OrderBy('id','desc')->first()->$col; 
    }{
        return GeneralSetting::OrderBy('id','desc')->first();
    }
}
function slider_query($take=10, $skip=0, $order='desc'){
    return Slider::OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function testimonial_query($take=10, $skip=0, $order='asc'){
    return Testimonial::OrderBy('order',$order)->skip($skip)->take($take)->get();
}
function highlight_member_query($take=10, $skip=0, $order='asc'){
    return Member::where('highlight',1)->OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function member_without_highlight_query($take=10, $skip=0, $order='asc'){
    return Member::where('highlight',0)->OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function member_by_type_query($take=10, $skip=0, $order='asc',$type='executive-committee'){
    return Member::where('member_type',$type)->OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function member_query($take=10, $skip=0, $order='asc'){
    return Member::OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function member_url($member){
      $page = Member::find($member->id);
    if ($page){
        return route('single.member', ['id'=>$page->id, 'name'=> make_slug($page->name)]);
    }
    return null;   
}
function client_query($take=10, $skip=0, $order='asc'){
    return Client::OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function upcoming_service_query($take=20, $skip=0, $order='asc'){
    return Service::where('upcoming',1)->OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function service_query($take=20, $skip=0, $order='asc'){
    return Service::where('upcoming',0)->OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function products($take=10,$skip=0){
    return Product::where('status',1)->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
}
function product_url($product){
    if(!empty($product)){
        $product = Product::where([['slug',$product->slug],['id',$product->id]])->first();
        return route('single.product',['slug'=>$product->slug,'id'=>$product->id]);
    }
    return null;
}
function product_parent_category_url($pslug){
    $cat = ParentCategory::where('slug',$pslug)->first();
    if ($cat){
        return route('parent.category.product',['pslug'=>$cat->slug ]);
    }
    return null;
}
// function product_category_url($pslug, $cslug){
//     $category = Category::where('slug',$cslug)->first();
//     if($category->slug == $cslug){
//         $cat = Category::where('slug',$cslug)->first();
//     }else{
//         $cat = null;
//     }
//     $parentCat = ParentCategory::findOrFail($category->parent_category_id);
//     if($parentCat->slug == $pslug){
//         $pCat = ParentCategory::where('slug',$pslug)->first();
//     }else{
//         $pCat = null;
//     }
//     if ($pCat && $cat != null){
//         return route('category.product',['slug'=>$pCat->slug,'slug'=>$cat->slug]);
//     }
//     return null;
// }
function product_category_url($cat){
    $cat = Category::where('slug',$cat->slug)->first();
    if ($cat){
        return route('category.product',['cat'=>$cat->slug ]);
    }
    return null;
}
function product_subcategory_url($cat){
    $subcat = SubCategory::where('slug',$cat->slug)->first();
    $cat = Category::where('id',$cat->category_id)->first();
    if ($cat){
        return route('subcategory.product',['cat'=>$cat->slug, 'subCat'=>$subcat->slug]);
    }
    return null;
}
function category_product($category_id, $take = 10, $skip = 0){
    if ($take == 1) {
        $products = Product::where([['category_id',$category_id],['status',1]])->orderBy('created_at', 'desc')->skip($skip)->take($take)->first();
        return $products;
    }else{
        $products = Product::where([['category_id',$category_id],['status',1]])->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
        return $products;
    }
    return $products = null;
}
function active_user(){
    return User::select("*")->whereNotNull('last_seen')->orderBy('last_seen', 'DESC')->get();
}
function magazine($take=10,$skip=0){
    if($take == 1){
        return Magazine::orderBy('id','desc')->skip($skip)->first();
    }
    return Magazine::orderBy('id','desc')->skip($skip)->take($take)->get();
}
function magazine_url($magazine){
    return route('single.magazine',['id'=>$magazine->id]);
}
function menu_query($take = 5, $skip = 0, $order='asc'){
    if($take == 1){
        $menu = Menu::OrderBy('position', $order)->skip($skip)->take($take)->first();
    } else {
        $menu = Menu::OrderBy('position', $order)->skip($skip)->take($take)->get();
    }
    return $menu;
}
function all_post_with_pagination($take=10){
    return Post::where('status','1')->orderBy('id','desc')->paginate($take);
}
function latest_post($take=10,$skip=0){
    if($take == 1){
        return Post::where('status', '1')->orderBy('id','desc')->skip($skip)->first();
    }
    return Post::where('status','1')->orderBy('id','desc')->skip($skip)->take($take)->get();
}
function post_updated_by($id = 0){
    $user_name = null;
    $user = User::where('id',$id)->first();
    if ($user != null) {
        $user_name = $user->name;
    }else{
        $user_name = '';
    }
    return $user_name;
}
function post_updated_time($time = 0){
    if ($time != null) {
        return Carbon::createFromFormat('Y-m-d H:i:s', $time)->format('H:i/d M Y');
    }else{
        return '';
    }
}
function category_page_query($category_id, $take = 10, $skip = 0){
    if ($take == 1) {
        $page = Page::where([['pagecategory_id',$category_id],['status',1]])->orderBy('created_at', 'desc')->skip($skip)->take($take)->first();
        return $page;
    }else{
        $page = Page::where([['pagecategory_id',$category_id],['status',1]])->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
        return $page;
    }
    return $page = null;
}
function page_query($take = 0, $skip = 0, $order='desc'){
    if($take == 1){
        $Pages = Page::OrderBy('id', $order)->skip($skip)->take($take)->first();
    } else {
        $Pages = Page::OrderBy('id', $order)->skip($skip)->take($take)->get();
    }
    return $Pages;
}
function page_url($slug){
      $page = Page::where('slug',$slug)->first();
    if ($page){
        return route('single.page', ['slug' => $page->slug ]);
    }
    return null;   
}
//design query
function design_query($amount=1, $skip = 0, $order = 'desc'){   
    if($amount == 1){
        $design = Design::orderBy('id', $order)->select('id','title','slug','featured_image')->skip($skip)->take($amount)->first();
    } else {
        $design = Design::orderBy('id', $order)->select('id','title','slug','featured_image')->skip($skip)->take($amount)->get();
    }
    return $design;
}
function design_content($design_id = null){
    if(!empty($design_id)){
        return DesignContent::where('design_id',$design_id)->select('id','design_id','thumbnail','caption')->get();
    }
    return null; 
}

function photo_query($amount, $skip = 0, $order = 'desc'){   
    if($amount == 1){
        $photo = Photo::orderBy('id', $order)->skip($skip)->take($amount)->first();
    } else {
        $photo = Photo::orderBy('id', $order)->skip($skip)->take($amount)->get();
    }
    return $photo;
}
function multiple_photo($photo_id){
    return Photobody::where('photo_id',$photo_id)->get();
}
function post_query($amount, $order_by = 'desc', $skip = 0){
    return Post::where('status', '1')->orderBy('id', $order_by)->skip($skip)->take($amount)->get();
}
function ad_by_position($position = 1){
    $ad = Ad::where('position', $position)->first();
    return $ad;
}
function ad_query($amount = 1, $skip = 0, $order_by = 'asc'){
    $ads = null;
    if($amount == 1){
        $ads = Ad::orderBy('position', $order_by)->skip($skip)->take($amount)->first();
    } else {
        $ads = Ad::orderBy('position', $order_by)->skip($skip)->take($amount)->get();
    }
    return $ads;
}
function posts_by_category($category_id, $take = 10, $skip = 0){
    if ($take == 1) {
        $posts = Category::find($category_id)->posts()->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
        foreach ($posts as $item) {
            $posts_by_category = $item;
        }
    } else {
        $posts_by_category = Category::find($category_id)->posts()->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
    }
    if (!empty($posts_by_category)) {
        return $posts_by_category;
    }
    return $posts_by_category = null;
}
function posts_by_sub_category($sub_category_id, $take = 10, $skip = 0){
    if ($take == 1) {
        $posts = SubCategory::find($sub_category_id)->posts()->orderBy('created_at', 'desc')->skip($skip)->first();
    } else{
        $posts = SubCategory::find($sub_category_id)->posts()->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
    }
    return $posts;
}
function posts_by_tag($tag_id, $take = 8, $skip = 0){
    if ($take == 1) {
        $posts = Tag::find($tag_id)->Posts()->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
        foreach ($posts as $item) {
            $posts_by_tag = $item;
        }
    } else {
        $posts_by_tag = Tag::find($tag_id)->Posts()->orderBy('created_at', 'desc')->skip($skip)->take($take)->get();
    }
    if (!empty($posts_by_tag)) {
        return $posts_by_tag;
    }
    return $posts_by_tag = null;
}
function popular_post_by_category($category_id, $take){
    $current_date = date("Y-m-d H:i:s");
    $date = date_create(date("Y-m-d H:i:s")); 
    date_sub($date,date_interval_create_from_date_string("30 days"));

    $popular_by_date =  Category::find($category_id)->Posts()->orderBy('view_count','desc')->take($take)->get();
        // Post::whereBetween('created_at', [$date , $current_date])
        // ->orderBy('view_count','desc')
        // ->where('status', 1)
        // ->Category()
        // ->find('1')
        // ->take($take)
        // ->get();
    return $popular_by_date;
}
function category_slug($id){
    return Category::find($id)->slug;
}
function category_name($id){
    $name =  Category::findOrFail($id)->name;
    if ($name){
        return $name;
    }
    return null;
}
function category_url($id){
    $cat = Category::find($id);
    if ($cat){
        return route('category.posts', ['slug' => $cat->slug ]);
    }
    return null;
}
function all_category($order='asc'){
    return Category::orderBy('position',$order)->get();
}
function category_query($take=20, $skip=0, $order='asc'){
    return Category::OrderBy('position',$order)->skip($skip)->take($take)->get();
}
function sub_category($take=10, $skip=0, $category=0,$order='asc'){
    if($category != null){
        return SubCategory::where('category_id',$category)->orderBy('position',$order)->skip($skip)->take($take)->get();
    }else{
        return SubCategory::orderBy('position',$order)->skip($skip)->take($take)->get();
    }
    return null;
}
function sub_category_url($sub_cat){
    $sub_cat = SubCategory::where('slug',$sub_cat)->first();
    $cat = Category::where('id', $sub_cat->category_id)->first();
    if ($sub_cat){
        return route('sub_cat.post', ['cat' => $cat->slug,'sub_cat' => $sub_cat->slug]);
    }
    return null;
}
function tag_url($slug){
    return route('tag.posts',['slug'=>$slug]);
}
function sticky_post($take = 1, $skip = 0){
    $sticky_post = null;
    if ($take == 1) {
        $posts = Post::where('status', '1')->where('sticky', 1)->orderBy('position', 'asc')->take($take)->get();

        foreach ($posts as $item) {
            $sticky_post = $item;
        }
    } else {
        $sticky_post = Post::where('status', '1')->orderBy('created_at', 'desc')->where('sticky', 1)->skip($skip)->take($take)->get();
    }
    return $sticky_post;
}
function sticky_posts_by_position($take = null, $skip = null){
    if ($take == null) {
        $sticky_post = Post::join('lead_posts', 'posts.id', '=', 'lead_posts.post_id')->select('posts.*')->orderBy('lead_posts.position', 'ASC')->where('status', 1)->get();
    } else {
        if ($skip == null) {
            $sticky_post = Post::join('lead_posts', 'posts.id', '=', 'lead_posts.post_id')->select('posts.*')->orderBy('lead_posts.position', 'ASC')->where('status', 1)->take($take)->skip(0)->get();

        } else {
            $sticky_post = Post::join('lead_posts', 'posts.id', '=', 'lead_posts.post_id')->select('posts.*')->orderBy('lead_posts.position', 'ASC')->where('status', 1)->take($take)->skip($skip)->get();
        }
    }
    if ($take == 1) {
        $sticky_post = Post::join('lead_posts', 'posts.id', '=', 'lead_posts.post_id')->select('posts.*')->orderBy('lead_posts.position', 'ASC')->where('status', 1)->first();
    }
    return $sticky_post;
}
function make_slug($title){
    $title = preg_replace('[\‘]', '', $title);
    $title = preg_replace('[\’]', '', $title);
    $title = preg_replace('[/]', '', $title);
    $title = preg_replace('[,]', '', $title);
    $title = preg_replace('[\?]', '', $title);
    $title = preg_replace('[\!]', '', $title);
    $title = preg_replace('[\']', '', $title);
    $title = preg_replace('[\"]', '', $title);
    $title = preg_replace('[\:]', '', $title);
    $title = preg_replace('[\.]', '', $title);
    $title = preg_replace('[\)]', '', $title);
    $title = preg_replace('[\(]', '', $title);
    $title = str_replace(' ', '-', $title);
    $title = str_replace('|', '-', $title);
    $title = preg_replace('[-+]', '-', $title);
    $title = rtrim($title, "-");
    $title = strip_tags($title);
    $title = strtolower($title);
    return $title;
}
function video_query($amount, $skip = 1, $order_by = 'desc'){
    $videos = null;
    if ($amount == 1) {
        $videos = VideoGallery::orderBy('created_at', $order_by)->skip($skip)->take($amount)->first();
    } else {
        $videos = VideoGallery::orderBy('created_at', $order_by)->skip($skip)->take($amount)->get();
    }
    return $videos;
}
function all_video_query($order = 'desc', $show = 24){
    $video = VideoGallery::orderBy('id', $order)->paginate($show);
    return $video;
}
function single_video_query(){
    $videos = VideoGallery::orderBy('created_at', 'desc')->take(1)->first();
    return $videos;
}
function popular_post_by_date($take){
    $date= date_create(date("Y-m-d")); 
    date_sub($date,date_interval_create_from_date_string("7 days"));
    $popular_by_date = Post::where('created_at', '>=', $date)->where('view_count', '>', 100)->orderBy('view_count','desc')->take($take)->get();
    return $popular_by_date;
}
function Percent($total, $ans_count){
    if ($total == 0 or $ans_count == 0) {
        return 0;
    } else {
        $x = $total / $ans_count;
        $x = 100 / $x;
        $x = (int)$x;
        return $x;
    } 
}
function todays_date() {
    // $enDate = new \EasyBanglaDate\Types\BnDateTime('now', new \DateTimeZone('Asia/Dhaka'));
    // $bdDate = new \EasyBanglaDate\Types\BnDateTime('now', new \DateTimeZone('Asia/Dhaka'));
    // $bdDate = $bdDate->modify('+0 day');
    // echo $enDate->getDateTime()->format('l, jS F Y, ') . $bdDate->format('jS F Y');
}
function e_to_b_int($input){
    $bn_digits=array('০','১','২','৩','৪','৫','৬','৭','৮','৯');
    return str_replace(range(0, 9),$bn_digits, $input);
}
function news_url($post_id, $cat = null) {
    $post = Post::where('id',$post_id)->first();
    $category = $post->category()->first();
    if($category){
        return route('single.post', ['category' => $category->slug, 'id' => $post->id]);
    }
    // If no category found, handle accordingly
    return route('single.post', ['category' => 'default-category', 'id' => $post->id]); // Or some fallback logic
}

// function news_url($post, $cat = null){
//     if($cat == null){
//         $cat_slug = $post->Category()->first()->slug;
//     }else{
//         $cat_slug = $cat->slug;
//     }
//     return route('single.post', ['category' => $cat_slug, 'id' => $post->id]);
// }
function user_url($id){
    $user = User::findOrfail($id);
    if(!empty($user)){
        $name =  Str::slug($user->name,"-");
        return route('user.posts', ['name'=>$name,'id'=>$user->id]);
    }
    return null;
}
function photo_url($photo) {
    $cat = Photo::find($photo->id)->Category()->first()->slug;
    return route('single.photo.gallery', ['category' => $cat, 'id' => $photo->id, 'title' => make_slug($photo->title)]);
}
function photo_category_url($category){
    $cat = Category::find($category->id);
    return route('category.photo.gallery', ['category' => $cat->slug]);
}
function video_url($video) {
    return route('single.video.gallery', ['id'=>$video->id]);
}
function video_category_url($category) {
    $cat = Category::find($category->id);
    return route('category.video.gallery', ['category' => $cat->slug]);
}
function publisher_photo($post) {
    if ($post->reporter_photo) {
        $img = '<img src="'. $post->reporter_photo .'" alt="" style="width: 70px">';
        return $img;
    }
    return '';
}
function embed_video($video) {
    if ($video->streaming_site == 'youtube') {
        $embed_code = '<div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item" src="https://www.youtube.com/embed/'. $video->video_id.'" frameborder="0" allow="encrypted-media" allowfullscreen></iframe></div>';
    } elseif( $video->streaming_site == 'facebook') {
        $embed_code = '<div class="embed-responsive embed-responsive-16by9">
                                <iframe
                                        src="https://www.facebook.com/plugins/video.php?href=https%3A%2F%2Fwww.facebook.com%2FPlayStation%2Fvideos%2F'. $video->video_id . '%2F&show_text=0&width=560"

                                        style="border:none;overflow:hidden"
                                        scrolling="no" allowTransparency="true" allowFullScreen="true"
                                ></iframe>
                            </div>';
    } else {
        $embed_code = "Sorry, Something is Wrong. Please play another video.";
    }
    return $embed_code;
}
if (! function_exists('words')) {
    function words($value, $words = 100, $end = ''){
        return \Illuminate\Support\Str::words($value, $words, $end);
    }
}
function special_news($take){
    $special = Post::where('status', '1')->where('special', 1)->orderBy('id', 'desc')->take($take)->get();
    return $special;    
}
function engMonth_to_banMonth_replace($input){
    $ban_month=array("জানুয়ারী", "ফেব্রুয়ারী", "মার্চ", "এপ্রিল", "মে", "জুন", "জুলাই", "আগষ্ট", "সেপ্টেম্বার", "অক্টোবার", "নভেম্বার", "ডিসেম্বার");
    $eng_month=array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return str_replace($eng_month,$ban_month, $input);
}
function bangla_published_time($time) {
    return e_to_b_int( engMonth_to_banMonth_replace($time->format('j F Y') ) );
}
function bn_ago_time($timestamp){
    $time_ago = strtotime($timestamp);
    $current_time = time();
    $time_deff = $current_time - $time_ago;
    $seconds = $time_deff;
    $minutes = round($seconds / 60);
    $hours = round($seconds / 3600);
    $days = round($seconds / 86400);
    $weeks = round($seconds / 604800);
    $months = round($seconds / 2629440);
    $years = round($seconds / 31553280);
    if($seconds <= 60){
        return 'একটু আগে';
    }else if($minutes <= 60){
        if($minutes == 1){
            return 'এক মিনিট আগে';
        }else{
            return $minutes.'মিনিট আগে';
        }
    }else if($hours <= 24){
        if($hours == 1){
            return 'এক ঘন্টা আগে';
        }else{
            return $hours.' ঘন্টা আগে';
        }
    }else if($days <= 7){
        if($days == 1){
            return 'এক দিন আগে';
        }elseif($days == 7){
            return 'এক সপ্তাহ আগে';
        }
        else{
            return $days.' দিন আগে';
        }
    }else if($weeks <= 4.3){
        if($weeks == 1){
            return 'এক সপ্তাহ আগে';
        }else{
            return $weeks.' সপ্তাহ আগে';
        }
    }else if($months <= 12){
        if($months == 1){
            return 'এক মাস আগে';
        }else{
            return $months.' মাস আগে';
        }
    }else{
        if($years == 1){
            return 'এক বছর আগে';
        }else{
            return $years.' বছর আগে';
        }
    }
}