<?php
// INCLUDE YOUR FCM FILE
include_once 'db_connect.php';

require_once __DIR__ . '/vendor/autoload.php';
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\HttpHandler\HttpHandlerFactory;

class FCMNotifier {
    private $serviceAccountKeyFile;
    private $scope = "https://www.googleapis.com/auth/firebase.messaging";

    public function __construct() {
        $this->serviceAccountKeyFile = __DIR__ . '/auth/service_key.json';
    }

    private function getAccessToken() {
        $jsonKey = file_get_contents($this->serviceAccountKeyFile);
        $credentials = new ServiceAccountCredentials($this->scope, $this->serviceAccountKeyFile);
        $token = $credentials->fetchAuthToken(HttpHandlerFactory::build());
        return $token['access_token'];
    }
    
    public function handlePostRequest() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $token = $_POST['token'] ?? '';
            $latitude = $_POST['latitude'] ?? '';
            $longitude = $_POST['longitude'] ?? '';
            $title = $_POST['title'] ?? '';

            if ($token && $latitude && $longitude && $title) {
                $this->sendGCM($title, $token, $latitude, $longitude);
            } else {
                $this->sendResponse(['error' => 'Missing required parameters']);
            }
        } else {
            $this->sendResponse(['error' => 'Invalid request method']);
        }
    }

    private function sendGCM($title, $token, $latitude, $longitude) {
        $url = 'https://fcm.googleapis.com/v1/projects/turbo-tribuzz-apps/messages:send'; // Update with your project ID
        $accessToken = $this->getAccessToken();
        $headers = [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        ];

        require_once('Notifications.php');
        $notification = new Notifications();
        $notification->setTitle($title);
        $notification->setLatitude($latitude);
        $notification->setLongitude($longitude);
        $requestData = $notification->getNotification();

        $fields = [
            'message' => [
                'token' => $token,
                'data' => $requestData,
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // Ensure the SSL certificate is valid

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        if ($result === FALSE) {
            $this->sendResponse(['error' => 'Curl failed: ' . curl_error($ch)]);
        } else {
            $this->sendResponse(['msg' => 'Notification sent successfully', 'response' => $result]);
        }

        curl_close($ch);
    }

    private function sendResponse($response) {
        header('Content-Type: application/json');
        echo json_encode($response);
        exit();
    }
}

$notifier = new FCMNotifier();
$notifier->handlePostRequest();
mysqli_close($con);
?>
