<?php

use App\User;
use App\Setting;
use App\Language;
use App\Category;
use App\Newsletter;
use App\VideoCategory;
use App\WbSetting;
use App\WbSettingDescription;
use App\Service;
use App\Package;
use App\Project;
use App\Payment;
use App\Forms;
use App\ServiceMembers;
use App\ServiceDescriptions;
use App\PackageDescriptions;
use App\AboutDescriptions;
use App\FormDescriptions;
use App\ProjectForms;
use App\Field;
use App\Slider;
use App\SliderDescription;
use Illuminate\Support\Facades\DB;
use App\Providers\AppServiceProvider;
use Illuminate\Support\LazyCollection;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Illuminate\Support\Facades\Auth;

if (!function_exists('project_per')){
function project_per($id){
    
$project = Project::find($id);
        
        if(!$project){
            return redirect()->back();
        }
        if(\Auth::guard('member')->user()->id != $project->member_id){
             return redirect()->back();
        }
        $begin_service = Service::take(4)->get();
        $progress = 0;
        $forms_count = 0 ;
        $count = Service::count();
        if($count >= 4){
        $services = Service::skip(4)->take($count-4)->get();
        }
        else{
            $services = Service::take(0)->get();
        }
        if(\Auth::guard('member')->user()){
        $forms_all = Forms::count();
        $forms_count = ProjectForms::where('project_id',$id)->count();
        
        $progress =number_format(($forms_count / $forms_all)*100,'1');
        }
        
        $all_count = Forms::count();
        if($forms_count == $all_count){
        return true;
        }
        return false;
}
}
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('currentLanguageid')){

    /**
     * Return current language from database
     * @return mixed
     */
    function currentLanguageid($data)
    {
        $languages = Language::where('status', 1)->where('name', 'LIKE', '%'.$data.'%')->pluck('id');
        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();
        return $current['local'];
    }
}

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('packageid')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function packageid($data)
    {
       $package = Package::where('cost',$data)->pluck('id');
       return $package;
    }

}

if (!function_exists('packagedescription')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function packagedescription($data)
    {
       $package = PackageDescriptions::where('package_id',$data)->where('language_id',currentLanguage()['id'])->first();
       return $package['description'];
    }

}




if (!function_exists('packagesearchdescription')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function packagesearchdescription($data)
    {
       $package = PackageDescriptions::where('description', 'LIKE', '%'.$data.'%')->where('language_id',currentLanguage()['id'])->pluck('package_id');
       return $package;
    }

}



if (!function_exists('packagesearchname')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function packagesearchname($data)
    {
       $package = PackageDescriptions::where('name', 'LIKE', '%'.$data.'%')->where('language_id',currentLanguage()['id'])->pluck('package_id');
       return $package;
    }

}



if (!function_exists('packagename')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function packagename($data)
    {
       $package = PackageDescriptions::where('package_id',$data)->where('language_id',currentLanguage()['id'])->first();
       return $package['name'];
    }

}
if (!function_exists('packagelangname')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function packagelangname($data,$lang)
    {
       $package = PackageDescriptions::where('package_id',$data)->where('language_id',$lang)->first();
       return $package['name'];
    }

}

if (!function_exists('packagelangdescription')){

    /**
     * Return package description to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function packagelangdescription($data,$lang)
    {
       $package = PackageDescriptions::where('package_id',$data)->where('language_id',$lang)->first();
       return $package['description'];
    }

}


if (!function_exists('memberservice')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function memberservice($data)
    {
       $user = Auth::guard('member')->user();
       $service = ServiceMembers::where('member_id',$user['id'])->where('service_forms_id',$data)->first();
       return $service['description'];
    }

}
if (!function_exists('idealang')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function idealang($data)
    {
       
       $idea = Idea::where('id',$data)->where('language_id',currentLanguage()['id'])->first();
       return $idea['name'];
    }

}

if (!function_exists('servicelang')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function servicelang($data)
    {
       
       $service = ServiceDescriptions::where('service_id',$data)->where('language_id',currentLanguage()['id'])->first();
       
       return $service['name'];
    }

}


if (!function_exists('servicelangid')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function servicelangid($data)
    {
       
       $service = ServiceDescriptions::where('name', 'LIKE', '%'.$data.'%')->where('language_id',currentLanguage()['id'])->pluck('service_id');
       
       return $service;
    }

}

if (!function_exists('servicedescription')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function servicedescription($service_id , $lang)
    {
       
       $service = ServiceDescriptions::where('service_id',$service_id)->where('language_id',$lang)->first();
       
       return $service['description'];
    }

}
if (!function_exists('servicename')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function servicename($service_id , $lang)
    {
       
       $service = ServiceDescriptions::where('service_id',$service_id)->where('language_id',$lang)->first();
       
       return $service['name'];
    }

}


if (!function_exists('formlang')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function formlang($form_id , $lang)
    {
       
       $service = FormDescriptions::where('form_id',$form_id)->where('language_id',$lang)->first();
       
       return $service['question'];
    }

}
if (!function_exists('aboutkey')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function aboutkey($data)
    {
       
       $about = AboutDescriptions::where('about_id',$data)->where('language_id',currentLanguage()['id'])->first();
       
       return $about['key'];
    }

}
if (!function_exists('aboutvalue')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function aboutvalue($data)
    {
       
       $about = AboutDescriptions::where('about_id',$data)->where('language_id',currentLanguage()['id'])->first();
       
       return $about['value'];
    }

}

if (!function_exists('aboutkeydescription')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function aboutkeydescription($data)
    {
       
       $about = AboutDescriptions::where('key','LIKE', '%'.$data.'%')->first();
       
       return $about['about_id'];
    }

}
if (!function_exists('aboutvaluedescription')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function aboutvaluedescription($data)
    {
       
       $about = AboutDescriptions::where('value','LIKE', '%'.$data.'%')->first();
       
       return $about['about_id'];
    }

}


if (!function_exists('aboutkeylang')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function aboutkeylang($data,$lang)
    {
       
       $about = AboutDescriptions::where('about_id',$data)->where('language_id',$lang)->first();
       
       return $about['key'];
    }

}
if (!function_exists('aboutvaluelang')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function aboutvaluelang($data,$lang)
    {
       
       $about = AboutDescriptions::where('about_id',$data)->where('language_id',$lang)->first();
       
       return $about['value'];
    }

}
if (!function_exists('formquestion')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function formquestion($data)
    {
       
       $about = FormDescriptions::where('form_id',$data)->where('language_id',currentLanguage()['id'])->first();
       
       return $about['question'];
    }

}

if (!function_exists('projectformisset')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function projectformisset($data,$project)
    {
       
       $project = ProjectForms::where('form_id',$data)->where('project_id',$project)->first();
       if($project){
           return true;
       }
       return false;
       
    }

}

if (!function_exists('projectdescription')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function projectdescription($data,$project_id)
    {
       $user = \Auth::guard('member')->user();
       $project = ProjectForms::where('form_id',$data)->where('project_id',$project_id)->first();
       
       return $project['description'];
       
    }

}
if (!function_exists('projectpackage')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function projectpackage($data)
    {
       $user = \Auth::guard('member')->user();
       $project = Project::where('package_id',$data)->where('id',$user->project_id)->first();
       if($project){
           return true;
       }
       return false;
       
    }

}


if (!function_exists('countrow')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function countrow($data, $project_id)
    {
       $forms = Forms::where('service_id',$data)->pluck('id');
       $projects = ProjectForms::whereIn('form_id',$forms)->where('project_id',$project_id)->get();
       
       return count($projects);
       
    }

}


if (!function_exists('projectformscheck')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function projectformscheck($data,$project_id)
    {
       $user = \Auth::guard('member')->user();
       $forms = Forms::where('service_id',$data)->pluck('id');
       $projectforms = ProjectForms::where('project_id',$project_id)->whereIn('form_id',$forms)->get(); 
       if(count($projectforms) == count($forms) ){
          return true; 
       }
       return false;
       
    }

}

if (!function_exists('checkproject')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function checkproject()
    {
       $user = \Auth::guard('member')->user();
       $project = Project::find($user->project_id); 
       if($project['done'] == '1' ){
          return true; 
       }
       return false;
       
    }

}

if (!function_exists('paid')){

    /**
     * Return package name to package by package path from packages table
     * most used in blades views
     * @param $modulePath
     * @param null $local
     * @return mixed
     */
    function paid($id)
    {
       $user = \Auth::guard('member')->user();
       $data = Payment::where('member_id',$user->id)->first(); 
       if($data ){
          return true; 
       }
       return false;
       
    }

}
if (!function_exists('sliderurl')){

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

if (!function_exists('slidername')){

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

if (!function_exists('sliderdescription')){

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

if (!function_exists('aboutname')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function aboutname($data)
    {
    $target = AboutDescriptions::where('about_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $target['key'];
    }
}

if (!function_exists('aboutdescription')){

    /**
     * Return product categories
     * @return LazyCollection
     */
    function aboutdescription($data)
    {
    $target = AboutDescriptions::where('about_id',$data)->where('language_id',currentLanguage()['id'])->first();
        return $target['value'];
    }
}
if (!function_exists('wbsetting')){

    function wbsetting($data)
    {
        $row = WbSetting::where('key',$data)->pluck('id');
         $setting = WbSettingDescription::where('wbsetting_id',$row)->where('language_id',currentLanguage()['id'])->first();
         return $setting['value'];
   
        
    }
}