<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\CategoryRequest;
use App\Http\Requests\Admin\NotificationRequest;
use App\Jobs\sendEmail;
use App\Jobs\SendNotifcation;
use App\Mail\sendUserNotifcation;
use App\Models\ActiveGuest;
use App\Models\Category;
use App\Models\Notification;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
use function Monolog\Formatter\format;
use App\Models\Services;
use Google\Client;
use Google\Auth\CredentialsLoader;
use Google\Auth\OAuth2;
use Google\Auth\Credentials\ServiceAccountCredentials;

class NotificationController extends Controller
{
    const  FIREBASE_MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';

    protected $viewPath = 'Admin.Notification';
    private $route = 'Notification';

    public function __construct(Notification $model)
    {
        $this->objectName = $model;
    }

    public function index()
    {
        return view($this->viewPath . '.index');
    }


    public function datatable(Request $request)
    {
        $data = $this->objectName::orderBy('id', 'desc')->where('type','admin');
        return DataTables::of($data)
            ->addColumn('checkbox', function ($row) {
                $checkbox = '';
                $checkbox .= '<div class="form-check form-check-sm form-check-custom form-check-solid">
                                    <input class="form-check-input selector checkbox" type="checkbox" value="' . $row->id . '" />
                                </div>';
                return $checkbox;
            })
            ->addColumn('user', function ($row) {
                $actions = $row->User->name ;
                return $actions;

            })
            ->addColumn('date', function ($row) {
                $actions = Carbon::parse($row->created_at)->format('Y-m-d H:i') ;
                return $actions;

            })
            ->rawColumns([ 'checkbox','date'])
            ->make();

    }

    public function table_buttons()
    {
        return view($this->viewPath . '.button');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // return view($this->viewPath . '.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */

    public function store(NotificationRequest $request)
    {
        $data = $request->validated();
//        $token = User::where('phone','96550550507')->pluck('fcm_token');
//        send($token,'مناسبة ( اشعار من قبل الادارة )',$data['name_ar'],null,'admin');
        $data['name_en']=$data['name_ar'];
        $token = [];
        $accessTokenService =  $this->getAccessToken();

//        dd($accessTokenService);
        if($request->user_type == 1){
            $users = $data['user_id'];
            $data['type']='admin';

            if($request->type = 1){
                if(in_array(0,$users)){

                    $idArray = User::whereNotNull('fcm_token')->pluck('fcm_token');
//                    $chunkSize = 1000;
// Chunk the array into arrays of $chunkSize
//                    $chunkedArray = array_chunk($idArray, $chunkSize);
                    foreach($idArray as $token){
                        SendNotifcation::dispatch($token,$data['name_ar'],$accessTokenService);
//                        $repo[] = send($object,'مناسبة ( اشعار من قبل الادارة )',$data['name_ar'],$accessTokenService,'admin');
                    }
                }else{
                    $tokens = User::whereIn('id',$users)->pluck('fcm_token');
                    foreach($tokens as $token ){
                        SendNotifcation::dispatch($token,$data['name_ar'],$accessTokenService);
                    }
//                    $repo[] =  send($tokens[0],'مناسبة ( اشعار من قبل الادارة )',$data['name_ar'],$accessTokenService,'admin');
//                    dd($repo);


                }
            }else{
                if(in_array(0,$users)){
                    $usersa = User::OrderBy('id','desc')->get();
                    foreach($usersa as $user){
                        dispatch(new sendUserNotifcation($user));
                    }
                }else{
                    $users = User::whereIn('id',$users)->get();
                    foreach($users as $user){
                        dispatch(new sendUserNotifcation($user));
                    }
                }
            }
        }elseif($request->user_type == 2) {
            $idArray = ActiveGuest::whereNotNull('fcm_token')->pluck('fcm_token');
//            $chunkSize = 1000;
// Chunk the array into arrays of $chunkSize
//            $chunkedArray = array_chunk($idArray, $chunkSize);
            foreach ($idArray as $token) {
                SendNotifcation::dispatch($token,$data['name_ar'],$accessTokenService);

//                $repo[] = send($object, 'مناسبة ( اشعار من قبل الادارة )', $data['name_ar'], null, 'admin');
            }
        }else{
            // users send notifcations
            $idArray = User::whereNotNull('fcm_token')->pluck('fcm_token');
//            $chunkSize = 1000;

// Chunk the array into arrays of $chunkSize
//            $chunkedArray = array_chunk($idArray, $chunkSize);
            foreach($idArray as $object){
                SendNotifcation::dispatch($object,$data['name_ar'],$accessTokenService);
//                $repo[] = send($object,'مناسبة ( اشعار من قبل الادارة )',$data['name_ar'],$accessTokenService,'admin');
            }

//            Guests Send Notifcation
            $idArray = ActiveGuest::whereNotNull('fcm_token')->pluck('fcm_token')->toArray();
//            $chunkSize = 1000;
// Chunk the array into arrays of $chunkSize
//            $chunkedArray = array_chunk($idArray, $chunkSize);
            foreach ($idArray as $object) {
                SendNotifcation::dispatch($object,$data['name_ar'],$accessTokenService);
//                $repo[] = send($object, 'مناسبة ( اشعار من قبل الادارة )', $data['name_ar'], $accessTokenService, 'admin');
            }


        }
//        createLog($result, 1, $this->route, "#", $result->ar_name);
        return redirect(route($this->route . '.index'))->with('message', trans('lang.added_s'));
    }


    /**
     * 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)
    {
        $data = $this->objectName::findOrFail($id);
        return view($this->viewPath . '.edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(CategoryRequest $request)
    {
        $data = $request->validated();
        if (is_file($request->image)) {
            $video = upload($request->image, 'categories');
            $data['image'] = $video;
        } else {
            $data['image'] = $request->image;
        }
        $result = $this->objectName::whereId($request->id)->first();
        $result->update($data);

//        editLog($result, 1, $this->route, "#", $result->ar_name);
        return redirect(route($this->route . '.index'))->with('message', trans('lang.updated_s'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        try {
//            $results = $this->objectName::whereIn('id', $request->id)->get();
//            foreach ($results as $key => $result) {
//                delLog($result, 1, $this->route, $result->ar_name);
//            }

            $this->objectName::whereIn('id', $request->id)->delete();
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed']);
        }
        return response()->json(['message' => 'Success']);
    }

    public function changeActive(Request $request)
    {
        $data['status'] = $request->status;
        $this->objectName::where('id', $request->id)->update($data);
        return 1;
    }

    public function getAccessToken()
    {

        $projectId = 'monasba-26b9f'; // Replace with your Firebase project ID
        $firebaseScope = 'https://www.googleapis.com/auth/firebase.messaging';

        try {
            // JSON key string for Google service account (from Firebase)
            $jsonKeyString = '{
                "type": "service_account",
                "project_id": "monasba-26b9f",
                "private_key_id": "6b49ba7bc4068912192a90534a2092f2b01fe7c2",
                "private_key": "-----BEGIN PRIVATE KEY-----\\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDCOz4vaHJ7sVak\\nV3SAJhu2lmqhj3h9tSS/IwsLgEgphyoVahp4XQSS7i0b+5uC/wuknBINrQjBvWIn\\nEXB+zOo+D/KDsO9GFIQpJNfUZAS8uKyE+jOuoyamhXErBMDkEhkFdfdhP9o/dTuh\\nxxIZPjxmDuKUvgp5GLxaKprpu2csa6QFdxoFQ/OvHckD3lgFWwOC20lpD06jhuOy\\n1K0+NcVRCBeJGFAcBcjUY80epCrtq81mKwhcbtOpuMRXmGFwlsKUM7/pPDBZNO0M\\nseSMJzaaMIJ1Rr8ImvzzNHgQLnt6ySJmXIB9G5APdCbsazWykZJdOCblvItVjHkR\\nzlFgVh+/AgMBAAECggEAPDIOILU3HdylJIOyKHEnD5xoaa/EQPld7RrYNnVIaA5q\\n3X4nu/vgCgVk15JP7PZMTnTMJ47j8t9VxxPhkHrDcf6RQ30Xetmq5/FyLnHdAfwe\\nA4xjbhFETkF3BEUR3t05AfdAdtRKOHaFx6qhkk82es7MLBsFtegTn8Iqhpu86wfa\\n8wxgZn7cIKqAGuYlstwWZaosDG0HqhvLRG3jyNBQXT7Mp/wR3wn14GfclncI3kE6\\n1C5w3iFBgz0C4UhY+S++1tR6X2KuwdvDqKOOQBXwe2X35gWvGSBG+THP5SUbDEwQ\\n7jaUmXOt53Ychg0L2hqNpQC9R9lRVz0yr+FmGLSNaQKBgQDfEn86wN8gzvhe2vy+\\nsp/ymBz0LHiPLz9qMPb805lYOUjYFB80Go8KBD23hoRASTvwnmlEN/MUNuJfIZgM\\nBVJjxw+65sVQh35boDbxXsokUSVmG/N+Y7HyrWbquvMqt3iEPMzFucXkHtJ7VehU\\nk/YKs92RmfNQNC8402OKwkFxvQKBgQDe5ubwdeyfwnsjLnYuFpMSAQhl0OYz0AsP\\nE4QSapWn0gUGYEffqAcmihlXfxkOSGa5NORACF/5Hkh/eVd2QiGSARCx8DaKqOHX\\n/Q7icY+7fWhJ1j+wiEgpTDvSy05YWHGwGCYcPfSdxXMzEP1kPLahuDjDV/qskm2S\\n9oKZA8/pKwKBgGguq101VwBrqXQjsocdxbX3dQ5U9rlox6VA2RmbebLKjkrcmvYq\\nsUNsV6avHHUpvuTSFzfVKaH3QCJN/kUe9yvCfIY94UmK/mismvx/2Mi9XUojI8WT\\nqjg85CQczBTXO2IHQ1vVN6ci/gq8RJW7xN2aw5CM5iY/OQ7BK2xS7V3BAoGAIFMb\\n6oMvbXumn9N9D/H2IgZEUX+Z4qmo8ObDoGgUi+HJGMOdqLGVV+FvC2FDIO8e9nzV\\nHPQZ9uaNXO8b3+p3M9Uztpo/TpxvJANuxSfy0B2/ofWQBum8jUCg7FDPa8BnvEHE\\nRRQ3BSo9KoqsNH0ZfxpYIPwBPkV93nIhPk9vN0ECgYBbpSLAnLEcTH5q4hNYbVoa\\nqDLzLAYBltIjNv6lzk/wOMA9gxYNix9rBdr4ijn5ukL4wkpEcsM0KXISpV5+pBgJ\\nQqHCs4JvC+3lZcEehOpRC68yIlW7MDU0ADpJRmDyWC+JYl0w3zLgd3+bXTczX6TJ\\n2wwUMOTEaYfOAFmdzMQ/rA==\\n-----END PRIVATE KEY-----\\n",
                "client_email": "firebase-adminsdk-l87v9@monasba-26b9f.iam.gserviceaccount.com",
                "client_id": "105752101940293655665",
                "auth_uri": "https://accounts.google.com/o/oauth2/auth",
                "token_uri": "https://oauth2.googleapis.com/token",
                "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
                "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-l87v9@monasba-26b9f.iam.gserviceaccount.com"
            }';

            // Decode JSON and get credentials
            $credentials = json_decode($jsonKeyString, true);

            // Create a scoped client for Firebase messaging
            $client = new Client();
            $client->setAuthConfig($credentials);
            $client->addScope($firebaseScope);

            // Get the access token
            $client->fetchAccessTokenWithAssertion();

            return $client->getAccessToken()['access_token'];
        } catch (\Exception $e) {
            return $e->getMessage();
        }


    }

}

