<?php

namespace App\Http\Controllers\Admin;

use App\Module;
use Exception;
use App\City;
use App\User;
use Illuminate\View\View;
use App\CityDescription;
use App\AreaDescription;
use Illuminate\Http\Request;
use App\Notification;
use App\NotificationDescription;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Redirector;
use App\Http\Controllers\Controller;
use App\Http\Requests\NotificationRequest;
use Illuminate\Http\RedirectResponse;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class NotificationController extends Controller
{

    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/admin/notifications';
    /** View folder */
    private $viewDirectory= 'admin.notifications.';

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
       $action= route('notifications.store');
        $members = User::all();
        $action= route('notifications.store');
        $head= __('notifications.new');
        return view( $this->viewDirectory.'form', compact('action', 'head','members','action') );
    }

    
    

    /**
     * Store a newly created resource in storage.
     *
     * @param NotificationRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(NotificationRequest $request) :RedirectResponse
    {
        
       if($request->type == 'all'){
        $users = User::whereIn('role',['consult','member'])->get();
             foreach($users as $user){
        $notification  =  Notification::create([
             
             'user_id'=>$user->id,
             'types'=>'management',
             
             ]);
             foreach (languages() as $lang) {
            $data=[
                'notification_id'=> $notification->id,
                'language_id'=> $lang->id,
                'title'=> $request['title_'.$lang->local],
                'description'=> $request['description_'.$lang->local],
                
            ];
            NotificationDescription::create($data);
        }
                 
                 /////-------send
                 
                $notify_ar =  NotificationDescription::where('notification_id',$notification->id)->where('language_id','1')->first();
                $notify_en =  NotificationDescription::where('notification_id',$notification->id)->where('language_id','2')->first();
         $title_ar  = $notify_ar->title;
         $title_en  = $notify_en->title;
          
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'typing' => 'management',
        'provider_id'=> null,
        '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);
                 
                 
             }
       }
       else{
           if($request->user == 'all'){
                $users = User::where('role',$request->type)->get();
             foreach($users as $user){
        $notification  =  Notification::create([
             
             'user_id'=>$user->id,
             
             
             ]);
             foreach (languages() as $lang) {
            $data=[
                'notification_id'=> $notification->id,
                'language_id'=> $lang->id,
                'title'=> $request['title_'.$lang->local],
                'description'=> $request['description_'.$lang->local],
                
            ];
            NotificationDescription::create($data);
        }
        
        $notify_ar =  NotificationDescription::where('notification_id',$notification->id)->where('language_id','1')->first();
                $notify_en =  NotificationDescription::where('notification_id',$notification->id)->where('language_id','2')->first();
         $title_ar  = $notify_ar->title;
         $title_en  = $notify_en->title;
          
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'provider_id'=> null,
        '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);
                 
             }
           }else{
           $user = User::find($request->user);
           
           
             $notification =  Notification::create([
             
             'user_id'=>$request->user,
             
             ]);
           
          foreach (languages() as $lang) {
            $data=[
                'notification_id'=> $notification->id,
                'language_id'=> $lang->id,
                'title'=> $request['title_'.$lang->local],
                'description'=> $request['description_'.$lang->local],
                
            ];
            NotificationDescription::create($data);
          }
          
          
          $notify_ar =  NotificationDescription::where('notification_id',$notification->id)->where('language_id','1')->first();
                $notify_en =  NotificationDescription::where('notification_id',$notification->id)->where('language_id','2')->first();
         $title_ar  = $notify_ar->title;
         $title_en  = $notify_en->title;
          
        if($user->language == 'en'){
            
            $title = $title_en;
        }
        else{
            $title = $title_ar;
        
        }
       
        $data =array(
        'type' => 'NEW_PROVIDER',
        'provider_id'=> null,
        '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 redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
        
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param City $area
     * @return View
     */
    public function edit(Area $area) :View
    {
        $action= route('notifications.update', $area->id);

        $query = AreaDescription::where('area_id', $area->id)
            ->join('languages', 'languages.id', 'area_descriptions.language_id')
            ->select(['area_descriptions.*', 'languages.local']);

        $areaDescription= $query->get();
        $cities = City::where('country_id','4')->get();
        foreach ($areaDescription as $row) {
            $area[$row->local]= $row;
        }

        return view( $this->viewDirectory.'form', compact('area','cities', 'action') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param NotificationRequest $request
     * @param City $area
     * @return RedirectResponse|Redirector
     */
    public function update(NotificationRequest $request, Area $area) :RedirectResponse
    {

        // Update image and category id if request has it
        $area->update($request->all());

        // update image to youtube api thumbnail if request have not image
       

        // Delete old description
        AreaDescription::where('area_id', $area->id)->delete();


        // Insert new description
        $this->saveData( $request, $area->id );

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Handle Save form data
     *
     * @param NotificationRequest $request
     * @param int $area_id
     * @return void
     */

    private function saveData(NotificationRequest $request, int $area_id ):void
    {
        $requestData= $request->all();
        foreach (languages() as $lang) {
            $data=[
                'area_id'=> $area_id,
                'language_id'=> $lang->id,
                'name'=> $requestData['name_'.$lang->local],
                
            ];
            
            AreaDescription::create($data);
        }

        

    }


    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $area = Area::withTrashed()->find($id);
        if ($area) {
            if ($area->deleted_at) {
                $area->forceDelete();
            } else {
                $area->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            Area::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            Area::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $area = Area::withTrashed()->find($id);

        if ($area){
            $area->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $area = Area::whereIn('id', $request->ids)->onlyTrashed();
        if ($area){
            $area->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}