<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Models\Admin\User;
use App\Models\Admin\NotificationHost;
use App\Models\Admin\NotificationTemplate;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\Auth;

use App\Traits\Permissions_trait;
use Spatie\Activitylog\Models\Activity;

class NotificationController extends Controller
{

    use Permissions_trait;
    var $url;
    public function __construct()
    {
        $this->middleware('auth');
        $this->url = request()->path();
    }

    public function index(){
        if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, 'Permission denied..');
        endif;
        activity('Notification Page Visited')
           ->causedBy(Auth::user())
            ->performedOn(new User())
            // ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Notification Page visited by ' . Auth::user()->name);
            return View('admin.notification.notification_index');
    }

    public function get_list(Request $request)
    {
        if (!$this->Permissions_trait('view', 'notification')) :
            abort(403, 'Permission denied..');
        endif;
        $record = User::where('status', 1)->where('type','!=', 'admin')->orderByDesc('id');
        return Datatables::of($record)
            ->filter(function ($record) use ($request) {
                if ($request->has('search')) {
                    $record->where('name', 'like', "%" . $request->get('search')['value'] . "%");
                }

                if ($request->has('user_filter') && $request->user_filter != "") {
                    $record->where('user_type', '=', $request->get('user_filter'));
                }

                if ($request->has('locale_filter') && $request->locale_filter != "") {
                    $record->where('locale', '=', $request->get('locale_filter'));
                }

                if ($request->has('device_filter') && $request->device_filter != "") {
                    if ($request->device_filter == 'ios') {
                        $record->where('ios_device_id', '!=', "");

                    }elseif ($request->device_filter == 'android') {
                        $record->where('android_device_id', '!=', "");

                    }
                }
            })
            ->addIndexColumn()
            ->setRowId(function ($row) {
                return $row->id;
            })
            ->addColumn('name', function($row){

              $btn = '
                <sapn class="fw-bold text-dark">'.$row->name.'</sapn><br>
                <span>'.getUserType($row->user_type).'</span>
              ';
              return $btn;
            })
            ->addColumn('language', function ($row) {
                return $row->locale;
            })
            ->addColumn('device', function ($row) {
                if ($row->ios_device_id != '' && $row->android_device_id != '') {
                    return "iOS & Android";

                }elseif ($row->ios_device_id != '') {
                    return "iOS";

                }elseif ($row->android_device_id != '') {
                    return "Android";

                }else{
                    return "-";
                }

            })
            ->addColumn('actions',function($row){

                $btn =  '
                    <label class="container1 p-0">
                        <input class="sub-check" type="checkbox" value="'.$row->id.'" name="users[]">
                        <span class="checkmark"></span>
                    </label>
                ';

                return $btn;
            })
            ->rawColumns(['name','language','actions'])
            ->make(true);
            activity('Notification Page Visited')
           ->causedBy(Auth::user())
            ->performedOn(new User())
            // ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Notification Page Visited by ' . Auth::user()->name);
    }


    public function send(Request $request){
        if (!$request->has('users')) {
            return redirect()->back()->with('error','Make sure all requested information are complete.')->withInput();
        }
        $validator = Validator::make($request->all(), [
            'users.*' => 'required|integer',
            'title' => 'required',
            'message' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();

        } else {
              /*host*/
              if (isset($request->hosts) && !empty($request->hosts)) {
                $host = NotificationHost::where('id', $request->hosts)->first();
              } else{
                $host = NotificationHost::where('is_default', '1')->first();
              }
              $serverkey = $host->serverkey;
              $msg = trim($request->message);
            // dd($request->all());
            foreach ($request->users as $value) {
                $username = getAny('name', 'users', 'id', $value);
                if (isset($request->template) && !empty($request->template)) {
                  $template = NotificationTemplate::where('id', $request->template)->first();
                  $params = explode(',', $template->params);
                  foreach ($params as $value) {
                    $msg = str_replace($value, $username, $msg);
                  }
                } else{
                  $msg = str_replace('{{username}}', $username, $msg);
                }
                /*notifying*/
                if ($request->has('devices') && $request->devices == '') {
                    $token = getToken($value, 'ios');
                    if ($token != "") {
                        sendNotification($token, $request->title, $msg, $serverkey);
                    }

                    $token = getToken($value, 'android');
                    if ($token != "") {

                        sendNotification($token, $request->title, $msg, $serverkey);
                    }

                }elseif ($request->has('devices') && $request->devices == 'ios') {
                    $token = getToken($value, 'ios');
                    if ($token != "") {
                        sendNotification($token, $request->title, $msg, $serverkey);
                    }

                }elseif ($request->has('devices') && $request->devices == 'android') {
                    $token = getToken($value, 'android');
                    if ($token != "") {
                        sendNotification($token, $request->title, $msg, $serverkey);
                    }

                }


            }
            activity('Notification Send ')
            ->causedBy(Auth::user())
            ->tap(function (Activity $activity) {
            $activity->route_link = $this->url;
            })
            ->log('Notification Send  by ' . Auth::user()->name);

            return redirect()->back()->with('success','Notification sent Successfully')->withInput();
        }
    }
    /*get templates*/
    public function get_template($id)
    {
        $data = NotificationTemplate::find($id);
        echo json_encode(array('title' => $data->title, 'params' => $data->params, 'text' => $data->text));
    }

    /*notification hosts starts from here*/
    public function host_list(Request $request)
    {
        if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, 'Permission denied..');
        endif;
        if ($request->ajax()) :
            $record = NotificationHost::select('*')->where('status', '!=', -1)->orderByDesc('id');
            return Datatables::of($record)
            ->setRowId(function ($row) {
                return $row->id;
            })
            ->addColumn('is_default',function ($row) {
                $checked = "";
                  if ($row->is_default == 1) { $checked = "checked"; }
                  $swtich = '
                  <div class="ps-5 text-center">
                      <label class="switch">
                          <input class="" type="checkbox" id="togBtn" onClick="is_default('.$row->id.')" '.$checked.'>
                          <div class="slider round">
                              <span class="on">ON</span>
                              <span class="off">OFF</span>
                          </div>
                      </label>
                  </div>
                  ';
                  return $swtich;
            })
            ->addColumn('status',function ($row) {
                $checked = "";
                  if ($row->status == 1) { $checked = "checked"; }
                  $swtich = '
                  <div class="ps-5 text-center">
                      <label class="switch">
                          <input class="" type="checkbox" id="togBtn" onClick="state_switch('.$row->id.')" '.$checked.'>
                          <div class="slider round">
                              <span class="on">ON</span>
                              <span class="off">OFF</span>
                          </div>
                      </label>
                  </div>
                  ';
                  return $swtich;
            })
            ->addColumn('actions',function($row){
                $btn =  '
                    <div class="text-center align-middle edit_M">
                        <span class="px-2">
                            <a class="text-decoration-none px-1" href="'.url('/notification_host/edit/'.$row->id).'">
                            <i class="bi bi-gear bg-light_c round1 circul"></i>
                                <span class="px-1 text-muted">Setting</span>
                            </a>
                        </span>
                    </div>
                ';
                return $btn;
            })
            ->filter(function ($record) use ($request) {
              $input="";
              if ($request->has('search_new') && $request->search_new != "") {
                  $input=$request->get("search_new");
                  $record->where('name', 'like', '%' . $input . '%');
              }

              if ($request->has('status_filter') && $request->status_filter != "") {
                  $record->where('status', '=', $request->get('status_filter'));
              }
            })
            ->rawColumns(['is_default', 'status','actions'])
            ->make(true);
        endif;
        activity('Notification host Page Visited')
           ->causedBy(Auth::user())
            ->performedOn(new NotificationHost())
            // ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Notification host Page visited by ' . Auth::user()->name);
        return View('admin.notification.notification_host');
    }

    /*public function create()
    {
        return View('admin.notification.notification_host_add');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'serverkey' => 'required|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            if(isset($request->default)){ $default = '1'; }else{ $default = '0'; }
            if(isset($request->status)){ $status = '1'; }else{ $status = '0'; }
            $data = [
                //'name' => $request->name,
                'serverkey' => $request->serverkey,
                'is_default' => $default,
                'status' => $status,
            ];
            $post = NotificationHost::insert($data);
            $update = NotificationHost::where('is_default', '1')->where('id', '!=', $post->id)->update([
                'is_default' => '0',
            ]);
            if ($post) {
                return redirect()->back()->with('success','Host added successfuly')->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        }
    }*/

    public function edit($id)
    {
        $post = NotificationHost::find($id);
        return View('admin.notification.notification_host_edit', compact('post'));
    }

    public function update(Request $request)
    {
        if(!$this->Permissions_trait('update','notification_host')):
            return redirect()->back()->with('error','Permission denied..')->withInput();
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:255',
            'serverkey' => 'required|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            if(isset($request->default)){ $default = '1'; $status = '1'; }else{ $default = '0'; }
            if(isset($request->status)){ $status = '1'; }else{ $status = '0'; }
            if ($default == 1) {
                $status = '1';
            }
            $data = [
                //'name' => $request->name,
                'serverkey' => $request->serverkey,
                'is_default' => $default,
                'status' => $status,
            ];
            $old = NotificationHost::where('id', $request->id)->first();
            $post = NotificationHost::where('id', $request->id)->update($data);
            $update = NotificationHost::where('is_default', '1')->where('id', '!=', $request->id)->update([
                'is_default' => '0',
            ]);
            // activity('User Data updated')
            // ->causedBy(Auth::user())
            //     ->performedOn(new user())
            //     ->withProperties(['old'  => $post, 'modified' => $data])
            //     ->tap(function (Activity $activity) {
            //         $activity->route_link = $this->url;
            //     })
            //     ->log('User data updated by ' . Auth::user()->name);
            activity('Notification Host edited')
               ->causedBy(Auth::user())
                ->performedOn(new NotificationHost())
                ->withProperties(['old'  => $old, 'modified'=>$data])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Notification Host edited by ' . Auth::user()->name);
            if ($post) {
                return redirect()->back()->with('success','Host Updated successfuly')->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        }
    }

    function status(Request $request)
    {
        if(!$this->Permissions_trait('update','notification_host')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $state = getAny("status", "notification_hosts", "id", $request->id);
        if ($state == 1) {
            $update_state = '0';
        }else{
            $update_state = '1';
        }
        $post = NotificationHost::find($request->id);
        $post->status = $update_state;
        $msg = $post->save();
        activity('Notification Host status Changed')
        ->causedBy(Auth::user())
            ->performedOn(new NotificationHost())
            ->withProperties(['old'  => ['status' =>$state], 'modified' => ['status' => $update_state]])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Notification Host status changed by ' . Auth::user()->name);
        if ($msg) {
          echo  json_encode(array('text' => trans('admin.Status_Changed'), 'cls' => 'success'));
        } else {
          echo  json_encode(array('text' => trans('admin.Error'), 'cls' => 'error'));
        }
    }

    function is_default(Request $request)
    {
        if(!$this->Permissions_trait('update','notification_host')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $is_default = getAny("is_default", "notification_hosts", "id", $request->id);
        $status = getAny("status", "notification_hosts", "id", $request->id);
        if ($is_default == 1) {
            $update_state = '0';
        }else{
            $update_state = '1';
            $status = '1';
        }
        $post = NotificationHost::find($request->id);
        $post->is_default = $update_state;
        $post->status = $status;
        $msg = $post->save();

        $update = NotificationHost::where('is_default', '1')->where('id', '!=', $request->id)->update([
            'is_default' => '0',
        ]);
        activity('Default notification host Changed')
        ->causedBy(Auth::user())
            ->performedOn(new NotificationHost())
            ->withProperties(['old'  => ['is_default' =>$is_default], 'modified' => ['is_default' => $update_state]])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Default notification host changed by ' . Auth::user()->name);
        if ($msg) {
            echo  json_encode(array('text' => trans('admin.Status_Changed'), 'cls' => 'success'));
        } else {
            echo  json_encode(array('text' => trans('admin.Error'), 'cls' => 'error'));
        }
    }

    /*public function destroy(Request $request)
    {
        //$msg = NotificationHost::where('id',$request->id)->delete();
        $post = NotificationHost::find($request->id);
        $post->status = '-1';
        $msg = $post->save();
        if ($msg) {
            return ['text' => trans('admin.Delete_successfully'), 'cls' => 'success'];
        } else {
            return ['text' => trans('admin.Somthing_went_wrong'), 'cls' => 'error'];
        }
    }*/

    /*notification templates code start from here*/
    public function notification_template(Request $request)
    {
        if (!$this->Permissions_trait('view', $this->url)) :
            abort(403, 'Permission denied..');
        endif;
        if ($request->ajax()) :
            $record = NotificationTemplate::select('*')->where('status', '!=', '-1')->orderBy('id', 'desc');
            return Datatables::of($record)
            ->setRowId(function ($row) {
                return $row->id;
            })
            ->addColumn('is_default',function ($row) {
                $checked = "";
                  if ($row->is_default == 1) { $checked = "checked"; }
                  $swtich = '
                  <div class="ps-5 text-center">
                      <label class="switch">
                          <input class="" type="checkbox" id="togBtn" onClick="temp_is_default('.$row->id.')" '.$checked.'>
                          <div class="slider round">
                              <span class="on">ON</span>
                              <span class="off">OFF</span>
                          </div>
                      </label>
                  </div>
                  ';
                  return $swtich;
            })
            ->addColumn('status',function ($row) {
                $checked = "";
                  if ($row->status == 1) { $checked = "checked"; }
                  $swtich = '
                  <div class="ps-5 text-center">
                      <label class="switch">
                          <input class="" type="checkbox" id="togBtn" onClick="temp_state_switch('.$row->id.')" '.$checked.'>
                          <div class="slider round">
                              <span class="on">ON</span>
                              <span class="off">OFF</span>
                          </div>
                      </label>
                  </div>
                  ';
                  return $swtich;
            })
            ->addColumn('actions',function($row){
                $btn =  '
                <div class="text-center">
                    <span class="px-2">
                        <a class="text-decoration-none px-1" href="'.url('/notification_template/edit/'.$row->id).'">
                            <span class="edit_icon">
                                <i class="bi bi-pen"></i>
                            </span>
                            <span class="px-1 e-text">Edit</span>
                        </a>
                    </span>
                    <span>
                        <a class="text-decoration-none px-1" onClick="temp_destroy('.$row->id.')">
                            <span class="delete_icon fw-bold"><i class="bi bi-backspace"></i></span>
                            <span class="px-1 tcancel e-text">Delete</span>
                        </a>
                    </span>
                </div>
                ';
                return $btn;
            })
            ->filter(function ($record) use ($request) {
              $input="";
              if ($request->has('search_new') && $request->search_new != "") {
                  $input=$request->get("search_new");
                  $record->where('name', 'like', '%' . $input . '%');
              }

              if ($request->has('status_filter') && $request->status_filter != "") {
                  $record->where('status', '=', $request->get('status_filter'));
              }
            })
            ->rawColumns(['name', 'is_default', 'status','actions'])
            ->make(true);
        endif;
        activity('Template Notification Page Visited')
           ->causedBy(Auth::user())
            ->performedOn(new NotificationTemplate())
            // ->withProperties(['old'  => [], 'modified'=>$data])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Template Notification Page visited by ' . Auth::user()->name);
        return view('admin/notification.notification_temp');
    }

    /*public function add_temp()
    {
        return View('admin.notification.notification_temp_add');
    }

    public function save_temp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            //'name' => 'required|max:255',
            'title' => 'required|max:255',
            'text' => 'required|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            $data = [
                //'name' => $request->name,
                'title' => $request->title,
                'text' => $request->text,
            ];
            $post = NotificationTemplate::insert($data);
            if ($post) {
                return redirect()->back()->with('success','Added successfuly')->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        }
    }*/

    public function edit_temp($id)
    {
        $post = NotificationTemplate::find($id);
        return View('admin.notification.notification_temp_edit', compact('post'));
    }

    public function update_temp(Request $request)
    {
        if(!$this->Permissions_trait('update','notification_template')):
            return redirect()->back()->with('error','Permission denied..')->withInput();
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $validator = Validator::make($request->all(), [
            //'name' => 'required|max:255',
            'title' => 'required|max:255',
            'text' => 'required|max:255',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        } else {
            $data = [
                //'name' => $request->name,
                'title' => $request->title,
                'text' => $request->text,
            ];
            $old = NotificationTemplate::where('id', $request->id)->first();
            $post = NotificationTemplate::where('id', $request->id)->update($data);
            activity('Notification Template updated')
            ->causedBy(Auth::user())
                ->performedOn(new User())
                ->withProperties(['old'  => $old, 'modified' => $data])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Notification Template updated by ' . Auth::user()->name);
            if ($post) {
                return redirect()->back()->with('success','Updated successfuly')->withInput();
            } else {
                return redirect()->back()->with('error','Somthing went wrong')->withInput();
            }
        }
    }

    function temp_status(Request $request)
    {
        if(!$this->Permissions_trait('update','notification_template')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $state = getAny("status", "notification_templates", "id", $request->id);
        if ($state == 1) {
            $update_state = '0';
        }else{
            $update_state = '1';
        }
        $post = NotificationTemplate::find($request->id);
        $post->status = $update_state;
        $msg = $post->save();
        activity('Default Notification Status Changed')
        ->causedBy(Auth::user())
            ->performedOn(new NotificationTemplate())
            ->withProperties(['old'  => ['status' =>$state], 'modified' => ['status' => $update_state]])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Default Notification Status Changed by ' . Auth::user()->name);
        if ($msg) {
          echo  json_encode(array('text' => trans('admin.Status_Changed'), 'cls' => 'success'));
        } else {
          echo  json_encode(array('text' => trans('admin.Error'), 'cls' => 'error'));
        }
    }

    function temp_is_default(Request $request)
    {
        if(!$this->Permissions_trait('update','notification_template')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
        $state = getAny("is_default", "notification_templates", "id", $request->id);
        if ($state == 1) {
            $update_state = 0;
        }else{
            $update_state = 1;
        }
        $post = NotificationTemplate::find($request->id);
        $post->is_default = $update_state;
        $msg = $post->save();
        $update = NotificationTemplate::where('is_default', 1)->where('id', '!=', $request->id)->update([
            'is_default' => '0',
        ]);
        activity('Default Notification Changed')
        ->causedBy(Auth::user())
            ->performedOn(new NotificationTemplate())
            ->withProperties(['old'  => ['is_default' =>$state], 'modified' => ['is_default' => $update_state]])
            ->tap(function (Activity $activity) {
                $activity->route_link = $this->url;
            })
            ->log('Default Notification changed by ' . Auth::user()->name);
        if ($msg) {
            echo  json_encode(array('text' => trans('admin.Status_Changed'), 'cls' => 'success'));
        } else {
            echo  json_encode(array('text' => trans('admin.Error'), 'cls' => 'error'));
        }
    }

    public function temp_destroy(Request $request)
    {
        if(!$this->Permissions_trait('delete','notification_template')):
            echo  json_encode(array('text' => trans('Permission denied..'), 'cls' => 'error'));
            //abort(403, 'Permission denied..');
            exit;
        endif;
        //$msg = NotificationTemplate::where('id',$request->id)->delete();
        $post = NotificationTemplate::find($request->id);
        $post->status = '-1';
        $msg = $post->save();
        activity('Notification Data Deleted')
            ->causedBy(Auth::user())
            ->performedOn(new NotificationTemplate())
            ->withProperties(['old'  => ['status' =>$post->status], 'modified' => ['status' => '-1']])
                ->tap(function (Activity $activity) {
                    $activity->route_link = $this->url;
                })
                ->log('Notification Template Deleted by ' . Auth::user()->name);
        if ($msg) {
            return ['text' => trans('admin.Delete_successfully'), 'cls' => 'success'];
        } else {
            return ['text' => trans('admin.Somthing_went_wrong'), 'cls' => 'error'];
        }
    }
}
