<?php

use App\User;
use App\Setting;
use App\Language;
use App\Category;
use App\Reservation;
use App\Cobon;
use App\Newsletter;
use App\CobonItem;
use App\BranchDescription;
use App\ProductDescription;
use App\CategoryDescription;
use App\MethodDescription;
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;

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('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('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('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('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('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'];
    }
}