<?php

use App\User;
use App\Setting;
use App\Language;
use App\Category;
use App\Cobon;
use App\Choise;
use App\Attribute;
use App\Models;
use App\Product;
use App\ChoiseDescription;
use App\Auction;
use App\Newsletter;
use App\Chat;
use App\AccountDescription;
use App\WriterDescription;
use App\QuestionDescription;
use App\Like;
use App\Tax;
use App\Country;
use App\Subscribe;
use App\DayDescription;
use App\ReasonDescription;
use App\Rating;
use App\SliderDescription;
use App\PackageDescription;
use App\CobonItem;
use App\ProductDescription;
use App\ProductAttribute;
use App\TypeDescription;
use App\CategoryDescription;
use App\AttributeDescription;
use App\CityDescription;
use App\CountryDescription;
use App\Follow;
use App\Favorite;
use App\AboutDescription;
use App\VideoCategory;
use App\ModelDescription;
use Illuminate\Support\Facades\DB;
use App\Providers\AppServiceProvider;
use Illuminate\Support\LazyCollection;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
function fake_ids()
{

    $ids = ProductDescription::pluck('product_id');
    $products = Product::whereNotIn('id',$ids)->pluck('id');
    return $products;
}

function calculate($float)
{
    if ($float < -0.0000001){
        return ceil($float - 0.0000001);
    }
    else{
        return floor($float + 0.0000001);
    }
}
function sendNotification($data = '', $target = '') {
        //FCM API end-point
        $url = 'https://fcm.googleapis.com/fcm/send';
        //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
        $server_key = 'AAAAvjEHZXU:APA91bF0yGnJHtmcvyjQCrhZgkrsfEfK7jrlVpjEL4bl4fCC54IIqvAxFDZLatqBNeG_QwsxIHwxqCg2StJ-h7Gw_V62UJam5IcP9fiXrKTuwqPNGfur7hY7PrHo9aMFPaSZZkjjbpYd';
        // dd($server_key);
        $data['data'] = isset($data['notification']) ? $data['notification'] : $data;
        $fields = array_merge($target, $data);
        $headers = array(
            'Content-Type:application/json',
            'Authorization:key=' . $server_key
        );
        //CURL request to route notification to FCM connection server (provided by Google)
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Oops! FCM Send Error: ' . curl_error($ch));
        }
        curl_close($ch);
        
        return $result;
    }
    function Meladi2Hijri($day, $month, $year)
{
    $day   = (int) $day;
    $month = (int) $month;
    $year  = (int) $year;
    
    if (($year > 1582) or (($year == 1582) and ($month > 10)) or (($year == 1582) and ($month == 10) and ($day > 14))){
        $jd = calculate((1461*($year+4800+calculate(($month-14)/12)))/4)+calculate((367*($month-2-12*(calculate(($month-14)/12))))/12)-
        calculate( (3* (calculate(  ($year+4900+    calculate( ($month-14)/12)     )/100)    )   ) /4)+$day-32075;
    }
    else{
        $jd = 367*$year-calculate((7*($year+5001+calculate(($month-9)/7)))/4)+calculate((275*$month)/9)+$day+1729777;
    }

    $l = $jd-1948440+10632;
    $n = calculate(($l-1)/10631);
    $l = $l-10631*$n+354;
    $j = (calculate((10985-$l)/5316))*(calculate((50*$l)/17719))+(calculate($l/5670))*(calculate((43*$l)/15238));
    $l = $l-(calculate((30-$j)/15))*(calculate((17719*$j)/50))-(calculate($j/16))*(calculate((15238*$j)/43))+29;
    
    $month = calculate((24*$l)/709);
    $day   = $l-calculate((709*$month)/24);
    $year  = 30*$n+$j-30;
    
    $date = array();
    $date['year']  = $year;
    $date['month'] = $month;
    $date['day']   = $day;

    
        return $date;
    
}

function sendNotificationss($data = '', $target = '') {
        //FCM API end-point
        $url = 'https://fcm.googleapis.com/fcm/send';
        //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
         //$server_key = config('firebase_server_key');
         //dd($server_key, config('FIREBASE_SENDER_ID'), );
        $server_key = 'AAAAvjEHZXU:APA91bF0yGnJHtmcvyjQCrhZgkrsfEfK7jrlVpjEL4bl4fCC54IIqvAxFDZLatqBNeG_QwsxIHwxqCg2StJ-h7Gw_V62UJam5IcP9fiXrKTuwqPNGfur7hY7PrHo9aMFPaSZZkjjbpYd';
         
        $fields = array_merge($target, $data);
        $headers = array(
            'Content-Type:application/json',
            'Authorization:key=' . $server_key
        );
        //CURL request to route notification to FCM connection server (provided by Google)
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Oops! FCM Send Error: ' . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
    
function favorite($product_id,$device_id){
    $fav = Favorite::where('product_id',$product_id)->where('device_id',$device_id)->first();
    if($fav){
        return true; 
    }
    return false;
}
function devicecat($cat_id,$device_id){
    $follow = Follow::where('type','1')->where('target_id',$cat_id)->where('device_id',$device_id)->first();
    if($follow){
        return true; 
    }
    return false;
}
function devicemodel($model_id,$device_id){
    $follow = Follow::where('type','2')->where('target_id',$model_id)->where('device_id',$device_id)->first();
    if($follow){
        return true; 
    }
    return false;
}
function modelscategory($id){
    $models = Models::where('category_id',$id)->orderBy('num','ASC')->get();
    return $models;
}
function ResponseJson($status = 400 ,$msg,$data =null)
{
	$response =[
		'message'=>$msg,
	];
	return response()->json($response);
}

if (!function_exists('categorynews')){

    function categorynews($data)
    {
       $data =  Product::where('category_id',$data)->count();
       
    return $data;
        
    }
}
if (!function_exists('hangrid')){

    function hangrid($data)
    {
       $data =  User::where('id',$data)->first();
       
    return $data->hanqr;
        
    }
}
if (!function_exists('adauction')){

    function adauction($data)
    {
       $data =  Auction::where('product_id',$data)->get();
       
    return $data;
        
    }
}
if (!function_exists('packageexpired')){

    function packageexpired()
    {
       $user_id =  \Auth::user()->id;
       $sub = Subscribe::where('user_id',$user_id)->orderBy('id','desc')->first();
       if($sub){
           if($sub->type == '0'){
               return false;
           }
           $newEndingDate = date("Y-m-d", strtotime(date("Y-m-d", strtotime($sub->created_at)) . " + 365 day"));
           if(date('Y-m-d') < date("Y-m-d", strtotime($sub->created_at)) || date('Y-m-d') > $newEndingDate){
               return true;
           }
       }
       else{
            return true;
       }
    return false;
        
    }
}

if (!function_exists('condition')){

    function condition($data)
    {
       $conditions =  Setting::where('key','conditions')->first();
       $arr = json_decode($conditions->value,true);
       
       $name = $arr[$data];
    return $name;
        
    }
}
if (!function_exists('diff')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function diff($data)
    {
        $time = (strtotime($data) - time()) / 60;
        $time = abs($time);
        $time_hour = $time/60;
        if($time >= 60 && $time <= 1440){
             
            return __('web.since').' '.number_format($time_hour,0).' ' . __('web.hour');
        }
        elseif($time > 1440){
            $time_day = $time_hour / 24;
            return __('web.since').' '.number_format($time_day,0) .' '. __('web.day');
        }
return __('web.since').' '.number_format($time,0) .' '. __('web.minute');
    } 
}



if (!function_exists('imageproduct')){

    function imageproduct($id)
    {
       $product =  Product::withTrashed()->find($id);
   
   
    return $product['image'];
        
    }
}
if (!function_exists('imageuser')){

    function imageuser($id)
    {
       $user =  User::withTrashed()->find($id);
   
   
    return $user['photo'];
        
    }
}

if (!function_exists('usernames')){

    function usernames($id)
    {
       $user =  User::withTrashed()->find($id);
   
   
    return $user->name;
        
    }
}

if (!function_exists('chat')){

    function chat()
    {
        $user = \Auth::user()->id;
    $chats = Chat::where('user_1_id',$user)->get();
    $chats_2 = Chat::where('user_2_id',$user)->get();
    $merged = $chats->merge($chats_2);
   
    return $merged;
        
    }
}



if (!function_exists('username')){

    function username($id)
    {
        $user = \Auth::user()->id;
    $chat = Chat::find($id);
    if($chat->user_1_id == $user){
    $userid = $chat->user_2_id;
    $data = User::where('id',$userid)->first();
    }
    else{
        $userid = $chat->user_1_id;
        $data = User::withTrashed()->where('id',$userid)->first();
    }
    
   
    return $data['name'];
        
    }
}

if (!function_exists('userid')){

    function userid($id)
    {
        $user = \Auth::user()->id;
    $chat = Chat::find($id);
    if($chat->user_1_id == $user){
    $data = $chat->user_2_id;
    }
    else{
        $data = $chat->user_1_id;
    }
    
   
    return $data;
        
    }
}
if (!function_exists('userphoto')){

    function userphoto($id)
    {
        $user = \Auth::user()->id;
    $chat = Chat::find($id);
    if($chat->user_1_id == $user){
    $userid = $chat->user_2_id;
    $data = User::where('id',$userid)->first();
    }
    else{
        $userid = $chat->user_1_id;
        $data = User::where('id',$userid)->first();
    }
    
   
    return $data['photo'];
        
    }
}

function threecategory(){
    $categories = Category::paginate(3);
    return $categories;
}
function issetpack(){
    $sub = Subscribe::orderBy('id','DESC')->where('user_id',\Auth::user()->id)->first();
    if(!$sub){
        return false;
    }
    if($sub->package_id == '1'){
        return false;
    }
    if($sub->type == '1'){
        return false;
    }
    return true;
}
function userpackagevid(){
    $sub = Subscribe::orderBy('id','DESC')->where('user_id',\Auth::user()->id)->first();
    if(!$sub){
        return false;
    }
    if($sub->type == '0'){
        return false;
    }
    if($sub->package_id == '1'){
        return false;
    }
    return true;
}
function subscribes($id){
    $members = User::where('role','member')->get();
    
    $arr = array();
    foreach($members as $row){
        $datas = Subscribe::where('user_id',$row->id)->where('type','1')->orderBy('id','DESC')->first();
        if($datas){
        if($datas->package_id == $id ){
            array_push($arr,$row->id);
        }
        }
    }
    return $arr;
}
function taxpaid($id){
     $subscribe = Tax::where('user_id',\Auth::user()->id)->where('product_id',$id)->first();
   if(!$subscribe){
       return false;
   }
   else{
       return true;
   }
}
function lastsubscribe($id){
     $subscribe = Subscribe::where('user_id',$id)->where('type','1')->orderBy('id','DESC')->first();
   if(!$subscribe){
       return false;
   }
   else{
       return $subscribe->package_id;
   }
}
function lastsubscribedate($id){
     $subscribe = Subscribe::where('user_id',$id)->where('type','1')->orderBy('id','DESC')->first();
   if(!$subscribe){
       return false;
   }
   else{
      
       return  date('Y-m-d',strtotime($subscribe->created_at));
   }
}
function subscribed($data){
    if(!\Auth::user()){
        return false;
    }
    $subscribe = Subscribe::where('user_id',\Auth::user()->id)->where('type','1')->orderBy('id','DESC')->first();
    if(!$subscribe){
        return false;
    }
    if($subscribe->package_id == $data){
        return true;
    }
    return false;
}
/**
     * Helper to upload and resize Images
     * @param $image File to upload
     * @param int $width
     * @param int $height
     * @return string
     */
     function modelsub($id){
         $models = Models::where('model_id',$id)->get();
         return $models;
     }
     function favorited($id){
         $fav = Favorite::where('user_id',\Auth::user()->id)->where('product_id',$id)->first();
         if($fav){
         return true;
         }else{
             return false;
         }
     }
     function liked($id){
         $fav = Like::where('user_id',\Auth::user()->id)->where('product_id',$id)->first();
         if($fav){
         return true;
         }else{
             return false;
         }
     }
      function followed($user){
         $rate = Follow::where('follwer_id',\Auth::user()->id)->where('follow_id',$user)->first();
         if($rate){
         return true;
         }else{
             return false;
         }
     }
     function rating($user,$target){
         $rate = Rating::where('user_id',$user)->where('target_id',$target)->first();
         return $rate['rate'];
     }
     function ratings($target){
         $rate = Rating::where('target_id',$target)->get();
         if(count($rate)>0){
             $count = 0;
             foreach($rate as $row){
                 $count = $count +$row->rate;
             }
             $count = $count/count($rate);
         }
         else{
             $count = 0;
         }
         return $count;
     }
    function upload($image, $width= 200, $height= 200)
    {
        $newFileName = time().'.'.$image->extension();

       
        $destinationPath = public_path('/uploads/images/daily');
        $image->move($destinationPath, $newFileName);

        return '/uploads/images/daily/'.$newFileName;
    }
    if (!function_exists('accountname')){

    /**
     * Return about categories
     * @return LazyCollection
     */
    function accountname($data)
    {
    $accountname = AccountDescription::where('account_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $accountname['image'];
    }
}
    if (!function_exists('packagename')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function packagename($id)
    {
        $data = PackageDescription::where('package_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['name'];
    }
}
if (!function_exists('slidername')){
 function slidername($id)
    {
        $data = SliderDescription::where('slider_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['name'];
    }
}
if (!function_exists('sliderdescription')){
 function sliderdescription($id)
    {
        $data = SliderDescription::where('slider_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['description'];
    }
}

 
    if (!function_exists('packagedescription')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function packagedescription($id)
    {
        $data = PackageDescription::where('package_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['description'];
    }
}


if (!function_exists('aboutname')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function aboutname($id)
    {
        $data = AboutDescription::where('about_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['name'];
    }
}
if (!function_exists('aboutdescription')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function aboutdescription($id)
    {
        $data = AboutDescription::where('about_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['description'];
    }
}

if (!function_exists('mainmodels')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function mainmodels($id)
    {
        $rows = Models::where('category_id',$id)->where('model_id',null)->get();
        
        
        return $rows;
    }
}


if (!function_exists('attributechoises')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function attributechoises($id)
    {
        $rows = Choise::where('attribute_id',$id)->get();
        
        
        return $rows;
    }
}

if (!function_exists('attributecheck')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function attributecheck($id)
    {
        $rows = Attribute::where('category_id',$id)->where('type','choise')->get();
        
        
        return $rows;
    }
}


if (!function_exists('attributeselect')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function attributeselect($id)
    {
        $rows = Attribute::where('category_id',$id)->where('type','select')->get();
        
        
        return $rows;
    }
}

if (!function_exists('choisesdescs')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function choisesdescs($id)
    {
        $rows = Choise::where('attribute_id',$id)->pluck('id');
        $data = ChoiseDescription::whereIn('choise_id', $rows)->get();
        
        return $data;
    }
}

if (!function_exists('choisesdesc')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function choisesdesc($id)
    {
        $data = ChoiseDescription::where('choise_id', $id)->get();
        
        return $data;
    }
}

if (!function_exists('selectchoise')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function selectchoise($product,$choise)
    {
        $data = ProductAttribute::where('product_id', $product)->where('choise_id', $choise)->first();
        if($data){
            return true;
        }
        return false;
    }
}

if (!function_exists('choisename')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function choisename($id)
    {
        $data = ChoiseDescription::where('choise_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['name'];
    }
}

if (!function_exists('questionquestion')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function questionquestion($data)
    {
    $city = QuestionDescription::where('question_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $city['question'];
    }
}
if (!function_exists('questionanswer')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function questionanswer($data)
    {
    $city = QuestionDescription::where('question_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $city['answer'];
    }
}
if (!function_exists('choises')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function choises($id)
    {
        $data = Choise::where('attribute_id', $id)->get();
        return $data;
    }
}

if (!function_exists('languages')){

    /**
     * Return list of languages from database
     * @return mixed
     */
    function languages()
    {
        $languages = Language::where('status', 1)->cursor();
        return $languages;
    }
}

if (!function_exists('currentLanguage')){

    /**
     * Return current language from database
     * @return mixed
     */
    function currentLanguage()
    {
        $languages = Language::where('status', 1)->where('local', LaravelLocalization::getCurrentLocale())->first();
        return $languages;
    }
}

if (!function_exists('getCurrentLocale')){

    /**
     * Return current current locale from database
     * @return mixed
     */
    function getCurrentLocale()
    {
        $current = Language::where('status', 1)->where('local', LaravelLocalization::getCurrentLocale())->first()->local;
        return $current;
    }
}

if (!function_exists('descriptions')){

    /**
     * Return description for model
     * @param $model
     * @return mixed
     */
    function descriptions($model)
    {
        $description = $model->descriptions->where('language_id', currentLanguage()->id)->first();
        return $description ?? null;
    }
}


if (!function_exists('parseExternalVideoLink')){

    /**
     * Parse youtube|vimo|etc link to get video ID, video embed link, video thumbnails
     * @param $link
     * @return array
     */
    function parseExternalVideoLink($link) :array
    {

        /**
         * Links to test
         * https://youtu.be/N6wn8zMRlVE
         * https://www.youtube.com/watch?v=zlnau3yk0oU
         * https://www.youtube.com/watch?v=zlnau3yk0oU&features=adsdsd
         * https://www.youtube.com/embed/OC9zn5BKlC0
         */

        $linkPattern = '/^(https:\/\/(www\.)?(youtu|youtube){1}.([a-z]{1,4}))(\/watch\?v=|\/embed\/|\/){0,1}([a-zA-z0-9]{2,15})(&.)*/';

        $m= preg_match($linkPattern, $link, $linkMatches);

        // dd($m, $linkMatches);
        if (count($linkMatches) && $linkMatches[6]){
            $code = $linkMatches[6];
            $video_url = 'https://www.youtube.com/embed/'.$code;
            $image = "https://img.youtube.com/vi/$code/hqdefault.jpg";
        } else {
            $video_url = $link;
        }

        // $public = asset('/uploads/images/'.time().'.jpg');

        // Download images from remote server
        // $in=    fopen($image, "rb");
        // $out=   fopen($public, "wb");
        // while ($chunk = fread($in,8192))
        // {
        //     fwrite($out, $chunk, 8192);
        // }
        // fclose($in);
        // fclose($out);


        return [
            'code' => $code,
            'url' => $video_url,
            'image' => $image
        ];

    }
}

if (!function_exists('videoCategories')){

    /**
     * Return video categories
     * @return LazyCollection
     */
    function videoCategories() :LazyCollection
    {
        $videoCategories = VideoCategory::with('descriptions')->cursor();
        return $videoCategories;
    }
}

if (!function_exists('articleCategories')){

    /**
     * Return article categories
     * @return LazyCollection
     */
    function articleCategories() :LazyCollection
    {
        $articleCategories = Category::with('descriptions')->cursor();
        return $articleCategories;
    }
}

if (!function_exists('newsletters')){

    /**
     * Return all newsletters email
     * @return LazyCollection
     */
    function newsletters() :LazyCollection
    {
        $newsletters = Newsletter::cursor();
        return $newsletters;
    }
}

if (!function_exists('getUser')){

    /**
     * Return admin by id
     * @param $id
     * @return mixed
     */
    function getUser($id)
    {
        $user = User::find($id);
        return $user;
    }
}

if (!function_exists('settings')){

    /**
     * Return settings
     * @param null $key
     * @return mixed
     */
    function settings($key = null)
    {
        $settings = [];
        if ($key){
            $settings = Setting::where('key', $key)->first()->value;
        } else {
            $allSettings = Setting::cursor()->toArray();
            foreach ($allSettings as $setting) {
                $settings[$setting['key']] = $setting['value'];
            }
        }
        return $settings;
    }

}

if (!function_exists('meta')){

    /**
     * Return meta fields from module table
     * by field name and local language
     * this functions used mostly in blades views
     * to get meta field to each path individually
     * @param $field
     * @param $local
     * @return mixed
     */
    function meta($field, $local)
    {
        return AppServiceProvider::getMeta()->fields->{$local}->{$field} ?? null;
    }

}

if (!function_exists('metaFields')){

    /**
     * Return meta field to module by module path from modules table
     * most used in blades views
     * @param $modulePath
     * @param null $fieldName
     * @param null $local
     * @return mixed|null
     */
    function metaFields($modulePath, $fieldName = null, $local = null)
    {
        $meta = DB::table('modules')->where('path', $modulePath)->pluck('meta')->toArray();
        $meta = json_decode(array_first($meta));
        $meta = $fieldName && $local ? $meta->fields->{$local}->{$fieldName} ?? null : $meta->fields;
        return $meta ?? null;
    }

}

if (!function_exists('moduleName')){

    /**
     * Return module name to module by module path from modules table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function moduleName($modulePath, $local = null)
    {
        $meta = DB::table('modules')->where('path', $modulePath)->pluck('meta')->toArray();
        $meta = json_decode(array_first($meta));
        $meta = $local ? $meta->module_name->{$local} : $meta->module_name;
        return $meta ?? null;
    }

}



if (!function_exists('productCategories')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function productCategories() :LazyCollection
    {
        $productCategories = Category::with('descriptions')->cursor();
        return $productCategories;
    }
}


if (!function_exists('productname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function productname($data)
    {
    $productname = ProductDescription::where('product_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $productname['name'];
    }
}

if (!function_exists('productnamecheck')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function productnamecheck($data)
    {
    $productname = ProductDescription::where('product_id',$data)->where('language_id',currentLanguage()['id'])->first();
    if (!$productname) {
        return 'تم مسح العنصر';
    }
        return $productname['name'];
    }
}

if (!function_exists('productnamelang')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function productnamelang($data,$lang)
    {
    $productname = ProductDescription::where('product_id',$data)->where('language_id',$lang)->first();
        return $productname['name'];
    }
}


if (!function_exists('productdescription')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function productdescription($data)
    {
    $productname = ProductDescription::where('product_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $productname['description'];
    }
}

if (!function_exists('dayname')){

    /**
     * Return day categories
     * @return LazyCollection
     */
    function dayname($data)
    {
    $dayname = DayDescription::where('day_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $dayname['name'];
    }
}

if (!function_exists('categoryname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function categoryname($data)
    {
    $categoryname = CategoryDescription::where('category_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $categoryname['name'];
    }
}

if (!function_exists('categorynamecheck')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function categorynamecheck($data)
    {
    $productname = CategoryDescription::where('category_id',$data)->where('language_id',currentLanguage()['id'])->first();
    if (!$productname) {
        return 'تم مسح العنصر';
    }
        return $productname['name'];
    }
}

if (!function_exists('modelnamecheck')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function modelnamecheck($data)
    {
    $productname = ModelDescription::where('model_id',$data)->where('language_id',currentLanguage()['id'])->first();
    if (!$productname) {
        return 'تم مسح العنصر';
    }
        return $productname['name'];
    }
}
if (!function_exists('modelname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function modelname($data)
    {
    $modelname = ModelDescription::where('model_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $modelname['name'];
    }
}

if (!function_exists('cobonitem')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function cobonitem($cobon_id,$item_id)
    {
    $item = CobonItem::where('cobon_id',$cobon_id)->where('item_id',$item_id)->first();
    if ($item) {
        return true;
    }
        return false;
    }
}


if (!function_exists('cobonitemsedit')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function cobonitemsedit($cobon_id,$item_id,$type)
    {

    $cobon = Cobon::find($cobon_id);
    if($cobon->type != $type){
        return false;
    }
    $item = CobonItem::where('cobon_id',$cobon_id)->where('item_id',$item_id)->first();
    if ($item) {
        return true;
    }
        return false;
    }
}

if (!function_exists('countrykey')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function countrykey($data)
    {
    $country = Country::find($data);
    dd($data);
        return $country['key'];
    }
}
if (!function_exists('countryname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function countryname($data)
    {
    $country = CountryDescription::where('country_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $country['name'];
    }
}
if (!function_exists('cityname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function cityname($data)
    {
    $city = CityDescription::where('city_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $city['name'];
    }
}

if (!function_exists('reasonname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function reasonname($data)
    {
    $city = ReasonDescription::where('reason_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $city['name'];
    }
}

if (!function_exists('attributename')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function attributename($data)
    {
    $city = AttributeDescription::where('attribute_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $city['name'];
    }
}
if (!function_exists('writername')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function writername($data)
    {
    $row = WriterDescription::where('writer_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $row['name'];
    }
}


if (!function_exists('typename')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function typename($data)
    {
    $row = TypeDescription::where('type_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $row['name'];
    }
}
