<?php

namespace App\Http\Controllers\Admin;

use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Notification;
use Morilog\Jalali;
use DB;
use Kavenegar;
use Auth;

class NotificationController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if(Auth::user()->access_notification ==1 || Auth::user()->role == 'admin')
                return $next($request);
            else
                abort(404);
        });
    }

    public function index(){

        $functions = new \App\functions;
        $notifications = \App\Notification::select('id','title','message','sms','head_fix','head_close','notification','email','category','created_at','updated_at','color')
            ->latest('updated_at')
            ->get();
        foreach ($notifications as $notification) {
            $notification->created_at = Jalali\CalendarUtils::strftime('H:i Y/m/d', strtotime($notification->created_at));
            $notification->updated_at = Jalali\CalendarUtils::strftime('H:i Y/m/d', strtotime($notification->updated_at));
        }

       return view('admin.notification',['notifications'=>$notifications]);
    }

    public function notification(Request $request)
    {
        $functions = new \App\functions;

        $result = (object)array();
        $Notifi = new Notification;
        $Notifi->title = $request->subject;
        $Notifi->message = $request->message;
        $Notifi->color = $request->color;
        $Notifi->category = $request->category;
        if(isset($request->head_fix)){
            $Notifi->head_fix = 1;
        }
        if(isset($request->head_close)){
            $Notifi->head_close = 1;
        }
        if(isset($request->sms)){
            $Notifi->sms = 1;
        }
        if(isset($request->notification)){
            $Notifi->notification = 1;
        }
        if(isset($request->email)){
            $Notifi->email = 1;
        }

        switch ($request->category) {
            case -1:
                if(isset($request->notification)){
                    $functions->send_notification($request->subject,$request->message,'/topics/all');
                }
                $users = User::select('id','mobile','email')->get();
                break;
            case 0:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id!=arzland_orders.id_user Group By arzland_users.id');
                break;
            case 1:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user Group By arzland_users.id');
                break;
            case 2:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="PSVouchers" Group By arzland_users.id');
                break;
            case 3:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="paypal" Group By arzland_users.id');
                break;
            case 4:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email,firebase_token from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="skrill" Group By arzland_users.id');
                break;
            case 5:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="webmoney" Group By arzland_users.id');
                break;
            case 6:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="perfectmoney" Group By arzland_users.id');
                break;
            case 11:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="PMvoucher" Group By arzland_users.id');
                break;
            case 7:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="bitcoin" Group By arzland_users.id');
                break;
            case 8:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="ethereum" Group By arzland_users.id');
                break;
            case 9:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="ripple" Group By arzland_users.id');
                break;
            case 10:
                $users = DB::select('select arzland_users.id as id,mobile,firebase_token,email from arzland_users,arzland_orders where arzland_users.id=arzland_orders.id_user and orders_model="tether" Group By arzland_users.id');
                break;

        }

       if(isset($request->sms)){
           $arrlist = array();
           foreach($users as $user){
               if(isset($request->kavenegar)){
				   try{\Kavenegar::VerifyLookup($user->mobile,'.',null,null,$request->kavenegar);}
					catch (\Exception $ex){}
			   }
               else
                   array_push($arrlist,$user->mobile);
           }
           if(!isset($request->kavenegar)){
               $sender = "10004346";
               Kavenegar::Send($sender,$arrlist,$request->message);
           }
       }

        if(isset($request->email)){
            $date = Jalali\Jalalian::forge('today')->format('%d %B %Y');
            $data = array('date'=>$date, 'title'=>$request->subject, 'body'=>$request->message);
            foreach($users as $user){
                if (isset($user->email) && $user->email != ""):
                    \Mail::send('emails.notification', $data, function($message) use ($user)
                    {
                        $message->to($user->email, $user->email)->subject('اطلاعیه از طرف'. env('APP_NAME_FARSI'));
                    });
                endif;
            }

        }

        if(isset($request->notification) && $request->category != -1){
            $count = count($users);
            $array = ceil($count/1000);
            $step = 0;

            $success = 0;
            $failure = 0;
            for($i=1;$i<=$array;$i++){

                $registrationIDs = array();
                for($j=$step;$j<($step+1000);$j++){
                    if(!empty($users[$j]) && isset($users[$j]->firebase_token))
                        array_push($registrationIDs,$users[$j]->firebase_token);
                }

                define( 'API_ACCESS_KEY', env('FirebaseToken'));

                $fcmMsg = array(
                    'body' 	=> $request->message,
                    'title'		=> $request->subject,
                    'icon' => asset('')."app-assets/images/icon.png",
                );

                $fcmFields = array(
                    'registration_ids' => $registrationIDs,
                    'priority' => 'high',
                    'notification' => $fcmMsg,
                );

                $headers = array(
                    'Authorization: key=' . API_ACCESS_KEY,
                    'Content-Type: application/json'
                );
                $ch = curl_init();
                curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
                curl_setopt( $ch,CURLOPT_POST, true );
                curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
                curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
                curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
                curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fcmFields ) );
                $response = curl_exec($ch );
                curl_close( $ch );
                $response = json_decode($response );


                $success=$success+ $response->success;
                $failure=$failure+$response->failure;
                $step=$step+1000;

            }
        }

        $functions->LogAdmin('ارسال اطلاعیه','notification');


        $Notifi->save();

        $result->status = true;
        $result->message = 'با موفقیت ثبت شد';
        //$result->user = $user;
        //$result->success = $success;
        //$result->registrationIDs = $registrationIDs;
        return response()->json($result);
    }

    public function delete(Request $request){
        $notify = \App\Notification::find($request->id);
        try {
            if($notify->delete()){
                $result = array('status' => true , 'messege' => 'با موفقیت حذف شد');
            }
        } catch (\Illuminate\Database\QueryException $e) {
            $result = array('status' => false , 'messege' => 'حذف امکان پذیر نیست');
        }
        return response()->json($result);
    }
}
