<?php

use App\Models\NotificationLog;
use App\Models\User;

// if (!function_exists('sendTestRequestNotification')) {

//     function sendTestRequestNotification($title = '', $msg = '',$userIds = false)
//     {

//         //dd($userIds);
//         // $deviceTokens = User::where('auth_level', '!=', '1')
//         //                     ->whereNotNull('device_id')
//         //                     ->pluck('device_id')
//         //                     ->toArray();
//         $query = User::where('auth_level', '!=', 1)
//             ->whereNotNull('device_id');

//         if (!empty($userIds)) {
//             $query->whereIn('id', $userIds);
//         }

//         $deviceTokens = $query->pluck('device_id')->toArray();

//         if (empty($deviceTokens)) {
//             return ['error' => 'No device tokens found'];
//         }
//         $results = [];
//         foreach ($deviceTokens as $token) {
//             $payload = [
//                 'message' => [
//                     'token' => $token,
//                     // 'notification' => [
//                     //     'title' => $title,
//                     //     'body'  => $msg
//                     // ],
//                     'data' => [
//                         'title'    => $title,
//                         'message'  => $msg

//                     ],
//                     'android' => [
//                         "priority" => "HIGH",
//                     ]
//                 ]
//             ];

//             $headers = [
//                 'Authorization: Bearer ' . getAccessToken(),
//                 'Content-Type: application/json',
//             ];

//             $ch = curl_init();

//             curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/findflicker-bec16/messages:send');
//             curl_setopt($ch, CURLOPT_POST, true);
//             curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//             curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

//             $response = curl_exec($ch);
//             curl_close($ch);

//             $results[] = json_decode($response, true);
//         }

//         return $results;
//     }
// }
if (!function_exists('sendTestRequestNotification')) {

    function sendTestRequestNotification($title = '', $msg = '', $userIds = false)
    {
        try {

            // ---------------- Fetch Device Tokens ----------------
            $query = User::where('auth_level', '!=', 1)
                ->whereNotNull('device_id');

            if (!empty($userIds)) {
                $query->whereIn('id', $userIds);
            }

            $users = $query->get(); // we need user_id + token

            if ($users->isEmpty()) {
                return ['error' => 'No device tokens found'];
            }

            $results = [];

            foreach ($users as $user) {

                $token = $user->device_id;

                // --------------- Prepare Payload ---------------
                $payload = [
                    'message' => [
                        'token' => $token,
                        'data' => [
                            'title'   => $title,
                            'message' => $msg
                        ],
                        'android' => [
                            "priority" => "HIGH",
                        ]
                    ]
                ];

                $headers = [
                    'Authorization: Bearer ' . getAccessToken(),
                    'Content-Type: application/json',
                ];

                // --------------- CURL INIT ---------------
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/findflicker-bec16/messages:send');
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

                $response = curl_exec($ch);
                $curlError = curl_error($ch);
                curl_close($ch);

                // --------------- Logging to DB ---------------
                $log = NotificationLog::create([
                    'user_id'      => $user->id,
                    'device_token' => $token,
                    'title'        => $title,
                    'message'      => $msg,
                    'status'       => $response ? 'success' : 'failed',
                    'response'     => $response ?: $curlError,
                ]);

                // --------------- Return Result ---------------
                $results[] = [
                    'user_id'  => $user->id,
                    'token'    => $token,
                    'response' => json_decode($response, true),
                    'log_id'   => $log->id,
                ];
            }

            return $results;
        } catch (\Exception $e) {

            return [
                'error' => true,
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ];
        }
    }
}

if (!function_exists('sendRequestNotification')) {

    function sendRequestNotification($title = '', $msg = '', $type, $userIds = false)
    {

        //dd($userIds);
        // $deviceTokens = User::where('auth_level', '!=', '1')
        //                     ->whereNotNull('device_id')
        //                     ->pluck('device_id')
        //                     ->toArray();
        $query = User::where('auth_level', '!=', 1)
            ->whereNotNull('device_id');

        if (!empty($userIds)) {
            $query->whereIn('id', $userIds);
        }

        $deviceTokens = $query->pluck('device_id')->toArray();

        if (empty($deviceTokens)) {
            return ['error' => 'No device tokens found'];
        }
        $results = [];
        foreach ($deviceTokens as $token) {
            $payload = [
                'message' => [
                    'token' => $token,
                    // 'notification' => [
                    //     'title' => $title,
                    //     'body'  => $msg
                    // ],
                    'data' => [
                        'title'    => $title,
                        'message'  => $msg,
                        'type' => $type
                    ],
                    'android' => [
                        "priority" => "HIGH",
                    ]
                ]
            ];

            $headers = [
                'Authorization: Bearer ' . getAccessToken(),
                'Content-Type: application/json',
            ];

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/v1/projects/findflicker-bec16/messages:send');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

            $response = curl_exec($ch);
            curl_close($ch);

            $results[] = json_decode($response, true);
        }

        return $results;
    }
}


function getAccessToken()
{
    $credentialsPath = storage_path('app/firebase-service-account.json');
    $client = new Google_Client();
    $client->setAuthConfig($credentialsPath);
    $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
    $token = $client->fetchAccessTokenWithAssertion();
    return $token['access_token'];
}
