<?php

use App\User;
use App\Setting;
use App\Language;
use App\Category;
use App\Reservation;
use App\Cobon;
use App\Report;
use App\Rate;
use App\Newsletter;
use App\CobonItem;
use App\BranchDescription;
use App\QuestionDescription;
use App\TypeDescription;
use App\ProductDescription;
use App\CategoryDescription;
use App\CountryDescription;
use App\MethodDescription;
use App\ExperienceDescription;
use App\CertificationDescription;
use App\SliderDescription;
use App\ServiceDescription;
use App\ProductPhoto;
use App\PageDescription;
use App\ReasonDescription;
use App\VideoCategory;
use Illuminate\Support\Facades\DB;
use App\Providers\AppServiceProvider;
use Illuminate\Support\LazyCollection;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;


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 = 'AAAAd7AV5kY:APA91bGh0jbMpB7g4E_X22c0WWT-UhtLC86e33LqCOrm_N1xwS_OOlbwmK9t6lFHkeiMYvNdfWP-m2NZiUxrPQAfbdhT9gapLDPl4vReLNgMrsy5nTZHgY4vNYeQIYE53jf9Wg_3ukRg';
        // 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 upload($image, $width= 200, $height= 200)
    {
        $newFileName = time().'.'.$image->extension();

        // Resize image and upload to Thumbnail path
        $destinationPath = public_path('/uploads/images/thumbs');
        $img = ImageResize::make($image->path());
        
        $img->resize($width, $height, function ($constraint) {
            $constraint->aspectRatio(); // to save the ratio
        })->save($destinationPath.'/'.$newFileName);

        // upload file to  Original path
        $destinationPath = public_path('/uploads/images');
        $image->move($destinationPath, $newFileName);

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

    function workhour($data)
    {
       $conditions =  Setting::where('key','workhours')->first();
       $arr = json_decode($conditions->value,true);
       
       $name = $arr[$data];
      
    return $name;
        
    }
}

if (!function_exists('rates')){

    function rates($id)
    {
       $rates =  Rate::where('target_id',$id)->get();
       if(count($rates) == 0){
           return ['rate'=>0,'count'=>0];
       }
       $count = 0;
       foreach($rates as $rate){
           $count = $count + $rate->rate;
       }
       
       $allcount = $count / count($rates);
      
      
        return ['rate'=>$allcount,'count'=>count($rates)];
    }
}
if (!function_exists('timedatesid')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function timedatesid($date,$num)
    {
      
    $date = Reservation::where('date',$date)->skip($num)->where('type','free')->first();
    
    return $date['id'];
    
    }
}
if (!function_exists('timedates')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function timedates($date,$num)
    {
      
    $date = Reservation::where('date',$date)->skip($num)->where('type','free')->first();
    if(!$date){
        return null;
    }
    return $date['time'];
    
    }
}
if (!function_exists('datesget')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function datesget($date,$num)
    {
      
    $date = Reservation::where('date',$date)->skip($num)->where('type','free')->first();
    if(!$date){
        return false;
    }
    return true;
    
    }
}

if (!function_exists('contdates')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function contdates($date)
    {
        $arr = array();
     for($i=0 ;$i < 7; $i++){ 
                                                    
    $date = date( "Y-m-d", strtotime( "+$i days" ) );
    $dates = Reservation::where('date',$date)->where('type','free')->count();
    array_push($arr,$dates);
    } 
    
    $max = max($arr);
    
    return $max;
    
    }
}



if (!function_exists('reported')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function reported($id,$user)
    {
    $data = Report::where('channel_id',$id)->where('user_id',$user)->first();
        if($data){
            return true;
        }
        return false;
    }
}
if (!function_exists('aboutname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function aboutname($id)
    {
    $data = PageDescription::where('page_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['title'];
    }
}
if (!function_exists('aboutmeta')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function aboutmeta($id)
    {
    $data = PageDescription::where('page_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['meta_description'];
    }
}
if (!function_exists('aboutdescription')){

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

if (!function_exists('rating')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function rating($id)
    {
    $data = Rate::where('channel_id',$id)->first();
    if(!$data){
        return 0;
    }
        return $data->rate;
    }
}
if (!function_exists('rated')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function rated($id,$user)
    {
    $data = Rate::where('channel_id',$id)->where('user_id',$user)->first();
    if(!$data){
        return false;
    }
        return true;
    }
}
if (!function_exists('ratedconsult')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function ratedconsult($id)
    {
    $data = Rate::where('channel_id',$id)->first();
    if(!$data){
        return false;
    }
        return true;
    }
}

if (!function_exists('methoddescription')){

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


if (!function_exists('branchaddress')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function branchaddress($id)
    {
    $data = BranchDescription::where('branch_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['address'];
    }
}

if (!function_exists('branchname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function branchname($id)
    {
    $data = BranchDescription::where('branch_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['name'];
    }
}
if (!function_exists('servicename')){

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

if (!function_exists('servicedescription')){

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

if (!function_exists('question')){

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

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

if (!function_exists('slidername')){

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

if (!function_exists('methodname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function methodname($id)
    {
    $data = MethodDescription::where('method_id',$id)->where('language_id',currentLanguage()['id'])->first();
        return $data['name'];
    }
}
if (!function_exists('reasonname')){

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

    /**
     * Return product categories
     * @return LazyCollection
     */
    function experincenamelang($id,$lang)
    {
    $name = ExperienceDescription::where('experience_id',$id)->where('language_id',$lang)->first();
    if(!$name){
        return null;
    }
        return $name['name'];
    }
}
if (!function_exists('certificationnamelang')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function certificationnamelang($id,$lang)
    {
    $name = CertificationDescription::where('certification_id',$id)->where('language_id',$lang)->first();
    if(!$name){
        return null;
    }
        return $name['name'];
    }
}

if (!function_exists('countryname')){

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

    /**
     * Return product categories
     * @return LazyCollection
     */
    function typename($data)
    {
    $name = TypeDescription::where('type_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $name['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('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('productphoto')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function productphoto($data)
    {

    $product = ProductPhoto::where('product_id',$data)->first();
   
        return $product['image'];
    }
}