<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Language;
use App\User;
use App\Setting;
use App\Article;
use App\Product;
use App\Slider;
use App\Channel;
use App\Contact;
use App\Report;
use App\Rate;
use App\ChannelFile;
use App\Type;
use App\Notification;
use App\NotificationDescription;
use App\Page;
use App\Country;
use App\Category;
use App\Reason;
use App\Http\Resources\ReasonResource;
use App\Models;
use App\ProductAttribute;
use Illuminate\Http\JsonResponse;
use App\Http\Resources\SettingResource;
use App\Http\Resources\PageResource;
use App\Http\Resources\QuestionResource;
use App\Http\Resources\ArticleResource;
use App\Http\Resources\ChannelResource;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\CountryResource;
use App\Http\Resources\RateResource;
use App\Http\Resources\ConsultResource;
use App\Http\Resources\TypeResource;
use App\Http\Requests\Api\ChannelRequest;
use App\Http\Requests\Api\RateRequest;
use App\Http\Resources\SliderResource;
use App\Http\Requests\Api\ContactRequest;
use App\Question;

use App\Http\Requests\Api\ReportRequest;


class MainController extends Controller
{
    /**
     * Filter  Ads.
     * @param Request $request
     * @return JsonResponse
     */
     public function sliders(Request $request) :JsonResponse
    {
        $sliders = Slider::all();
        
         return response()->json(['message'=>'','data'=>SliderResource::collection($sliders)], 200);
         
         
    }
     public function settings(Request $request) :JsonResponse
    {
         $settings = Setting::all();
        
        $pages = Page::where('id','<=','3')->get();
        $intro = Page::where('id','>','3')->where('id','<','8')->get();
         
         return response()->json(['message'=>'','data'=>['settings'=>new SettingResource($settings),'pages'=>PageResource::collection($pages),'intro'=>PageResource::collection($intro)]], 200);
         
         
    }
    
    public function types(Request $request) :JsonResponse
    {
         $types = Type::all();
        
        
         
         return response()->json(['message'=>'','data'=>['types'=>TypeResource::collection($types)]], 200);
         
         
    }
    public function reasons(Request $request) :JsonResponse
    {
         $reasons = Reason::all();
        
        
         
         return response()->json(['message'=>'','data'=>['reasons'=>ReasonResource::collection($reasons)]], 200);
         
         
    }
    
    public function categories(Request $request) :JsonResponse
    {
         $categories = Category::with('consults')->get();
        
        
         
         return response()->json(['message'=>'','data'=>['categories'=>CategoryResource::collection($categories)]], 200);
         
         
    }
     public function singlecategory(Request $request,$id) :JsonResponse
    {
         $categories = Category::with('consults')->find($id);
        if(!$categories){
            if(getCurrentLocale() == 'ar')
        {
            $msg = 'غير موجود';
        }
        else
        {
            $msg = 'Not Exist';
        }
            return response()->json(['message'=>$msg,'data'=>''], 200); 
        }
        
         
         return response()->json(['message'=>'','data'=>['categories'=>new CategoryResource($categories)]], 200);
         
         
    }
    
    public function countries(Request $request) :JsonResponse
    {
         $countries = Country::all();
        
        
         
         return response()->json(['message'=>'','data'=>['countries'=>CountryResource::collection($countries)]], 200);
         
         
    }
    public function questions(Request $request) :JsonResponse
    {
         $questions = Question::all();
        
        
         
         return response()->json(['message'=>'','data'=>['questions'=>QuestionResource::collection($questions)]], 200);
         
         
    }
    public function showarticle(Request $request,$id) :JsonResponse
    {
         $article = Article::find($id);
        if(!$article){
            if(getCurrentLocale() == 'ar')
            {
                $msg = 'غير موجود';
            }
            else
            {
                $msg = 'Not Exist';
            }
             return response()->json(['message'=>$msg,'data'=>''],200);
        }
        
         
         return response()->json(['message'=>'','data'=>['article'=>new ArticleResource($article)]], 200);
         
         
    }
    public function contactus(ContactRequest $request) :JsonResponse
    {
         $contact = Contact::create($request->all());
         if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        
         
         return response()->json(['message'=>$msg,'data'=>$contact], 200);
         
         
    }
    
    public function articles(Request $request) :JsonResponse
    {
         $articles = Article::all();
        
        
         
         return response()->json(['message'=>'','data'=>['articles'=>ArticleResource::collection($articles)]], 200);
         
         
    }
    public function rate(Request $request,$id) :JsonResponse
    {
         $rates = Rate::with(['member','consult'])->where('target_id',$id)->get();
        
        
         
         return response()->json(['message'=>'','data'=>['rates'=>RateResource::collection($rates)]], 200);
         
         
    }
    public function rates(Request $request) :JsonResponse
    {
        $user = \Auth::user();
         $rates = Rate::where('user_id',$user->id)->get();
        
        
         
         return response()->json(['message'=>'','data'=>['rates'=>RateResource::collection($rates)]], 200);
         
         
    }
    public function report(ReportRequest $request) :JsonResponse
    {
         Report::create(['comment'=>$request->comment,'channel_id'=>$request->id,'user_id'=>\Auth::user()->id,'reason_id'=>$request->reason_id]);
         if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        
         
         return response()->json(['message'=>$msg,'data'=>''], 200);
         
         
    }
    
    public function filter(Request $request) :JsonResponse
    {
         
        $consults = User::where('role','consult')->where(function ($query) use ($request) {
            
                    if(!is_null($request->type_id)){
                        $query->where('type_id', $request->type_id);
                   
                    }
                    if(!is_null($request->category_id)){
                        $query->where('category_id', $request->category_id);
                    }
                
            
        })->get();
         
         return response()->json(['message'=>'','data'=>ConsultResource::collection($consults)], 200);
         
         
    }
    
    public function createChannel(ChannelRequest $request) :JsonResponse
    {
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
         $request->merge(['user_id'=>\Auth::user()->id]);
        $channel = Channel::create($request->all());
         $channel = Channel::with(['category','member','typing','consult'])->find($channel->id);
         
         
         if(!is_null($channel->target_id)){
         $title_ar  = 'تم وصول طلب استشارة '.$channel->name;
         $title_en  = 'New Consult Request '.$channel->name;
          $user = User::find($channel->target_id);
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
        $notify = Notification::create(['user_id'=>$user->id,'types'=>'request','target_id'=>$channel->id]);
         
            
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '1',
                'title'=> 'تم وصول طلب استشارة '.$channel->name,
                'description'=> 'تم وصول طلب استشارة '.$channel->name,
                ]);
                  
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '2',
                'title'=> 'New Consult Request '.$channel->name,
                'description'=> 'New Consult Request '.$channel->name,
                ]);
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'typing' => 'request',
        'provider_id'=> $channel->id,
        'title'=> $title,
        'vibrate' => 1,
        'priority' => 'high',
        'visibility'=> 1,
        'foreground'=> true,
        'no-cache' => 1,
        'force-start' => 1,

    );
    $data['notification'] = $data;

    $token['to'] = $user->device_token ;
     

    $res= sendNotification($data, $token);
         }
         return response()->json(['message'=>$msg,'data'=>new ChannelResource($channel)], 200);
         
        

    }
    
    public function consults(Request $request):JsonResponse
    {
        $all = Channel::with(['category','member','typing','consult'])->where('type','all')->where('status','proccess')->get();
        $special = Channel::with(['category','member','typing','consult'])->where('target_id',\Auth::user()->id)->where('status','proccess')->get();
         return response()->json(['message'=>'','data'=>['all'=>ChannelResource::collection($all),'special'=>ChannelResource::collection($special)]], 200);
    }
    public function showconsult(Request $request,$id):JsonResponse
    {
        
        $consult =User::with(['rates','experience','certification','country'])->find($id);
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'لا يوجد';
        }
        else
        {
            $msg = 'Not Exist';
        }
        if(!$consult){
            return response()->json(['message'=>$msg,'data'=>null], 200);
        }
        return response()->json(['message'=>'','data'=>new ConsultResource($consult)], 200);
    }
    

        
    public function rating(RateRequest $request):JsonResponse
    {
        $channel = Channel::find($request->channel_id);
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        $request->merge(['user_id'=>\Auth::user()->id,'target_id'=>$channel->target_id]);
        $rate = Rate::create($request->all());
        $user = User::find($channel->target_id);
        $title_ar  = ' تم تقييم الاستشارة '.$channel->name.' من قبل المستخدم'.\Auth::user()->name;
         $title_en  = 'Consult '.$channel->name.' had been rated by '.\Auth::user()->name;
          $notify = Notification::create(['user_id'=>$user->id,'types'=>'rate','target_id'=>$user->id]);
         
                
            
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '1',
                'title'=> ' تم تقييم الاستشارة '.$channel->name.' من قبل المستخدم'.\Auth::user()->name,
                'description'=> ' تم تقييم الاستشارة '.$channel->name.' من قبل المستخدم'.\Auth::user()->name,
                ]);
                  
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '2',
                'title'=> 'Consult '.$channel->name.' had been rated by '.\Auth::user()->name,
                'description'=> 'Consult '.$channel->name.' had been rated by '.\Auth::user()->name,
                ]);
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'typing' => 'rate',
        'provider_id'=> $user->id,
        'title'=> $title,
        'vibrate' => 1,
        'priority' => 'high',
        'visibility'=> 1,
        'foreground'=> true,
        'no-cache' => 1,
        'force-start' => 1,

    );
    $data['notification'] = $data;

    $token['to'] = $user->device_token ;
     

    $res= sendNotification($data, $token);
    
         return response()->json(['message'=>$msg,'data'=>['rate'=>new RateResource($rate)]], 200);
    }
    public function accept(Request $request,$id):JsonResponse
    {
        $channel = Channel::find($id);
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
       $channel->update(['target_id'=>\Auth::user()->id,'status'=>'accept']);
       $user = User::find($channel->user_id);
       
       $title_ar  = ' تم قبول الاستشارة  '.$channel->name.' من قبل المستشار'.\Auth::user()->name;
         $title_en  = 'Consult '.$channel->name.' had been accepted by '.\Auth::user()->name;
          $notify = Notification::create(['user_id'=>$user->id,'types'=>'rate','target_id'=>$channel->id]);
         
                
            
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '1',
                'title'=> ' تم قبول الاستشارة  '.$channel->name.' من قبل المستشار'.\Auth::user()->name,
                'description'=> ' تم قبول الاستشارة  '.$channel->name.' من قبل المستشار'.\Auth::user()->name,
                ]);
                  
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '2',
                'title'=> 'Consult '.$channel->name.' had been accepted by '.\Auth::user()->name,
                'description'=> 'Consult '.$channel->name.' had been accepted by '.\Auth::user()->name,
                ]);
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'typing' => 'accept',
        'provider_id'=> $channel->id,
        'title'=> $title,
        'vibrate' => 1,
        'priority' => 'high',
        'visibility'=> 1,
        'foreground'=> true,
        'no-cache' => 1,
        'force-start' => 1,

    );
    $data['notification'] = $data;

    $token['to'] = $user->device_token ;
     

    $res= sendNotification($data, $token);
       
         return response()->json(['message'=>$msg,'data'=>['rate'=>new ChannelResource($channel)]], 200);
    }
    public function uploadimage(Request $request):JsonResponse
    {
        
        
         $img=$request->file('image');
        
        $image='/uploads/images/'.mt_rand(1000000, 9999999).time().'img-'.'.'.$img->getClientOriginalExtension();
        
        $img->move(public_path('/uploads/images/'),$image);
        
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
       
         return response()->json(['message'=>$msg,'data'=>['link'=>asset('').$image,'name'=>$image]], 200);
    }
    public function upload(Request $request):JsonResponse
    {
        
        if($request->type == 'sound'){
            $img=$request->file('file');
        
        $file='/uploads/images/'.mt_rand(1000000, 9999999).time().'upload'.'.'.$img->getClientOriginalExtension();
        
        $img->move(public_path('/uploads/images/'),$file);
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
       
         return response()->json(['message'=>$msg,'data'=>['link'=>asset('').$file]], 200);
        }
        $channel = ChannelFile::create($request->all());
         $img=$request->file('file');
        
        $file='/uploads/images/'.mt_rand(1000000, 9999999).time().'upload'.'.'.$img->getClientOriginalExtension();
        
        $img->move(public_path('/uploads/images/'),$file);
        $channel->file = $file;
        $channel->save();
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
       
         return response()->json(['message'=>$msg,'data'=>['link'=>asset('').$channel->file]], 200);
    }
     public function finished(Request $request,$id):JsonResponse
    {
        $channel = Channel::find($id);
        if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
       $channel->update(['target_id'=>\Auth::user()->id,'status'=>'finished']);
    //   if(is_null($channel->target_id)){
    //       if(getCurrentLocale() == 'ar')
    //     {
    //         $msg = 'تم انهاء الاستشارة';
    //     }
    //     else
    //     {
    //         $msg = 'This Consult Had Been Finished';
    //     }
    //     return response()->json(['message'=>$msg,'data'=>''], 400);
    //   }
        $user = User::find($channel->user_id);
       $target = User::find($channel->target_id);
       $title_ar  = ' تم انهاء الاستشارة  '.$channel->name.' مع المستشار'.$target->name;
         $title_en  = 'Consult '.$channel->name.' had been finished with '.$target->name;
          
          $notify = Notification::create(['user_id'=>$user->id,'types'=>'end','target_id'=>$channel->id]);
         
                
            
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '1',
                'title'=> ' تم انهاء الاستشارة  '.$channel->name.' مع المستشار'.$target->name,
                'description'=> ' تم انهاء الاستشارة  '.$channel->name.' مع المستشار'.$target->name,
                ]);
                  
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '2',
                'title'=> 'Consult '.$channel->name.' had been finished with '.$target->name,
                'description'=> 'Consult '.$channel->name.' had been finished with '.$target->name,
                ]);
                
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'typing' => 'end',
        'provider_id'=> $channel->id,
        'title'=> $title,
        'vibrate' => 1,
        'priority' => 'high',
        'visibility'=> 1,
        'foreground'=> true,
        'no-cache' => 1,
        'force-start' => 1,

    );
    $data['notification'] = $data;

    $token['to'] = $user->device_token ;
     

    $res= sendNotification($data, $token);
    
         return response()->json(['message'=>$msg,'data'=>['rate'=>new ChannelResource($channel)]], 200);
    }
    
    public function sendNotification(Request $request){
        
        $channel = Channel::find($request->id);
          if($channel->status == 'finished'){
          if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم انهاء الاستشارة';
        }
        else
        {
            $msg = 'This Consult Had Been Finished';
        }
        return response()->json(['message'=>$msg,'data'=>''], 400);
      }
      
      
      if(getCurrentLocale() == 'ar')
        {
            $msg = 'تم بنجاح';
        }
        else
        {
            $msg = 'Saved Successfully';
        }
        
        
        if(\Auth::user()->role == 'member'){
            $user = User::find($channel->target_id);
        }
        else{
            $user = User::find($channel->user_id);
        }
        if(!$user){
            if(getCurrentLocale() == 'ar')
        {
            $msg = 'لم يتم الموافقة بعد';
        }
        else
        {
            $msg = 'not eaccepted yet';
        }
         return response()->json(['message'=>$msg,'data'=>''], 200);
        }
        $name = $channel['name'];
        $title_ar  = 'رسالة جديدة في الاستشارة  '.$name.' من '.\Auth::user()->name;
         $title_en  = 'new message from channel '.$name.' from '.\Auth::user()->name;
          $notify = Notification::create(['user_id'=>$user->id,'types'=>'chat','target_id'=>$channel->id]);
         
                
            
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '1',
                'title'=> 'رسالة جديدة في الاستشارة  '.$name.' من '.\Auth::user()->name,
                'description'=> 'رسالة جديدة في الاستشارة  '.$name.' من '.\Auth::user()->name,
                ]);
                  
            NotificationDescription::create([
                'notification_id'=> $notify->id,
                'language_id'=> '2',
                'title'=> 'new message from channel '.$name.' from '.$user->name,
                'description'=> 'new message from channel '.$name.' from '.$user->name,
                ]);
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'typing' => 'chat',
        'provider_id'=> $channel->id,
        'title'=> $title,
        'vibrate' => 1,
        'priority' => 'high',
        'visibility'=> 1,
        'foreground'=> true,
        'no-cache' => 1,
        'force-start' => 1,

    );
    $data['notification'] = $data;

    $token['to'] = $user->device_token ;
     

    $res= sendNotification($data, $token);
        return response()->json(['message'=>$msg,'data'=>''], 200);
    }
    
}
