<?php

namespace App\Http\Controllers;

use App\Models\DeviceToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Kreait\Firebase\Exception\MessagingException;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;

class PushNotificationController extends Controller
{

    public function sendPushNotification(Request $request)
    {
        // Validate the incoming request
        $request->validate([
            'title' => 'required|string|max:255',
            'body' => 'required|string|max:1000',
            'key1' => 'nullable|string',
            'key2' => 'nullable|string',
        ]);

        // Prepare the payload for OneSignal
        $payload = [
            'app_id' => 'e6997c82-3b2b-496e-8b70-d70701d4996e',  // Ensure this is set in your .env file
            'contents' => [
                'en' => $request->input('body'),
            ],
            'headings' => [
                'en' => $request->input('title'),
            ],
            'data' => [
                'key1' => $request->input('key1', 'default_value1'),
                'key2' => $request->input('key2', 'default_value2'),
            ],
            'included_segments' => ['Total Subscriptions'],  // Target the 'Subscribed Users' segment
        ];

        try {
            // Send the notification via OneSignal API
            $response = Http::withHeaders([
                'Authorization' => 'Basic NmY2ZjZlZGEtZTNlYS00ZTlhLThhYmItYmMyZDI4MTQ3YWFk',  // Ensure this is set in your .env file
                'Content-Type' => 'application/json; charset=utf-8',
            ])->post('https://api.onesignal.com/notifications', $payload);

            if ($response->successful()) {
                return response()->json(['message' => 'Notification sent successfully', 'response' => $response->json()]);
            } else {
                return response()->json(['error' => 'Failed to send notification', 'response' => $response->json()], $response->status());
            }
        } catch (\Exception $e) {
            return response()->json(['error' => 'An error occurred: ' . $e->getMessage()], 500);
        }
    }




    public function storeToken(Request $request)
    {
        $request->validate([
            'device_token' => 'required|string',
        ]);

        // Update or create the device token
        DeviceToken::updateOrCreate(
            ['device_token' => $request->device_token],
            ['device_token' => $request->device_token]
        );

        return response()->json(['message' => 'Device token stored successfully']);
    }


}
