<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Brian2694\Toastr\Facades\Toastr;
use App\Models\User;
use App\Models\PushNotification;
use Auth;
use Carbon\Carbon;
use Spatie\Permission\Models\Permission;

class PushNotificationController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:timely-push-notification-access', ['only' => ['index','create','store','show','edit','destroy']]);
        $this->middleware('permission:direct-push-notification-access', ['only' => ['pushNotificationDirect','pushNotificationDirectCreate','pushNotificationDirectStore','pushNotificationDirectDelete']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = PushNotification::where('sending_date', '!=', null)->orderBy('id','desc')->paginate(10);
    	return view('admin.pushNotification.index',compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.pushNotification.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'notification_title' => 'required',
            'sending_date' => 'required',
            'sending_time' => 'required',
            'notification_message' => 'required'
        ]);

        $data = $request->all();
        $data['is_scheduler'] = true;

        //To get current date & time...
        $dt = Carbon::now('Asia/Dhaka');
        $currentTime = $dt->hour.':'.$dt->minute;
        if($dt->toDateString() < Carbon::parse($request->sending_date)->format('Y-m-d')){
            $data['sending_date'] = Carbon::parse($request->sending_date)->format('Y-m-d');

            if(PushNotification::create($data)){
                Toastr::success('PushNotification created successfull.', '', ["progressbar" => true]);
                return redirect(route('push-notification.index'));
            }else{
                Toastr::error('Something is error there.!', '', ["progressbar" => true]);
                return redirect()->back();
            }
        }elseif($dt->toDateString() == Carbon::parse($request->sending_date)->format('Y-m-d')){
            //To check time...
            if($currentTime < $request->sending_time){
                if(PushNotification::create($data)){
                    Toastr::success('PushNotification created successfull.', '', ["progressbar" => true]);
                    return redirect(route('push-notification.index'));
                }else{
                    Toastr::error('Something is error there.!', '', ["progressbar" => true]);
                    return redirect()->back();
                }
            }else{
                Toastr::error('Time can not be less than current time.!', '', ["progressbar" => true]);
                return redirect()->back();
            }
        }else{
            Toastr::error('Date can not be less than current date.!', '', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $pushNotification = PushNotification::where('id', $id)->first();
        return view('admin.pushNotification.edit', compact('pushNotification'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'notification_title' => 'required',
            'sending_date' => 'required',
            'sending_time' => 'required',
            'notification_message' => 'required'
        ]);

        $data = $request->all();
        $pushNotification = PushNotification::where('id', $id)->first();

        //To get current date & time...
        $dt = Carbon::now('Asia/Dhaka');
        $currentTime = $dt->hour.':'.$dt->minute;
        if($dt->toDateString() <= Carbon::parse($request->sending_date)->format('Y-m-d') && $currentTime < $request->sending_time){
            $data['sending_date'] = Carbon::parse($request->sending_date)->format('Y-m-d');
            if($pushNotification->update($data)){
                Toastr::success('PushNotification updated successfull.', '', ["progressbar" => true]);
                return redirect(route('push-notification.index'));
            }else{
                Toastr::error('Something is error there.!', '', ["progressbar" => true]);
                return redirect()->back();
            }
        }else{
                dd($request->sending_time);
            Toastr::error('Time & date can not be less than current date & time.!', '', ["progressbar" => true]);
            return redirect()->back();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $pushNotification = PushNotification::where('id', $id)->first();
        if($pushNotification->delete()){
            Toastr::success('PushNotification deleted successfull.', '', ["progressbar" => true]);
            return redirect(route('push-notification.index'));
        }else{
            Toastr::error('Something is error there.!', '', ["progressbar" => true]);
            return redirect()->back();
        }
    }


    public function pushNotificationSend(Request $request, $id)
    {
        //To get single push notification...
        $pushNotification = PushNotification::where('id', $id)->first();

        $url = 'https://fcm.googleapis.com/fcm/send';
        $FcmToken = User::whereNotNull('device_token')->pluck('device_token')->all();
        $serverKey = 'AAAAcbRxdOs:APA91bGjVUnfD9AtXHzdUT4aJJE-hnEogDPGbVYrnVk1nvci8aFwzrxzHpeq_EUxqs9VBVt4MaSrFLcsqmNZucO8qUAroy5ynmJg2x9WylJ34jhAmPtB4mjxZP_60pKrJK48sR8xB5KQ'; // ADD SERVER KEY HERE PROVIDED BY FCM
    
        $data = [
            "registration_ids" => $FcmToken,
            "notification" => [
                "title" => $pushNotification->notification_title,
                "body" => $pushNotification->notification_message,  
            ]
        ];
        $encodedData = json_encode($data);
    
        $headers = [
            'Authorization:key=' . $serverKey,
            'Content-Type: application/json',
        ];
    
        $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_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedData);
        // Execute post
        $result = curl_exec($ch);
        
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
            return response()->json([
                'error' => 'Somethig is wrong.!'
            ]);
        }else{
            //To update push notification ststaus....
            $pushNotification->status = true;
            $pushNotification->save();
            curl_close($ch);
            return redirect()->route('push-notification.index');
        }   
    }



    // Direct Send -----------------------------------

    public function pushNotificationDirect()
    {
        $data = PushNotification::where('sending_date',null)->orderBy('id','desc')->paginate(10);
        return view('admin.directSentNotification.index',compact('data'));
    }

    public function pushNotificationDirectCreate()
    {
        return view('admin.directSentNotification.create');
    }

    public function pushNotificationDirectStore(Request $request)
    {    
        $request->validate([
            'notification_title' => 'required',
            'notification_message' => 'required'
        ]);

        $data = $request->all();
        $data['is_scheduler'] = false;
        if($data = PushNotification::create($data)){

            $pushNotification = PushNotification::where('id', $data->id)->first();
            
            if (isset($pushNotification) && $pushNotification !=  null) {

                $title = $pushNotification->notification_title;
                $message = $pushNotification->notification_message;

                // For Notification message...
                $tagRemovalNotificationMessage = strip_tags($message);
                $originalNotificationMessage = preg_replace("/\s|&nbsp;/"," ",$tagRemovalNotificationMessage);
                
                //To send push notification...
                PushNotification::pushNotificationSend($title, $originalNotificationMessage);

                //To update push notification ststaus....
                $pushNotification->status = true;
                $pushNotification->save();

                Toastr::success('PushNotification sent successfull.', '', ["progressbar" => true]);
                return redirect()->route('push-notification-direct');
            }else{
                $pushNotification->delete();
                return redirect()->back();
            }   

        }else{
            Toastr::error('Something is wrong.!', '', ["progressbar" => true]);
            return redirect()->back();
        }
    }



    public function pushNotificationDirectDelete($id)
    {
        $pushNotification = PushNotification::where('id', $id)->first();
        if($pushNotification->delete()){
            Toastr::success('PushNotification deleted successfull.', '', ["progressbar" => true]);
            return redirect()->route('push-notification-direct');
        }else{
            Toastr::error('Something is wrong.!', '', ["progressbar" => true]);
            return redirect()->back();
        }
    }

}