<?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() {
        if (!file_exists($this->serviceAccountKeyFile)) {
            $this->sendResponse(['error' => 'Service key file does not exist']);
        }

        $jsonKey = file_get_contents($this->serviceAccountKeyFile);
        if ($jsonKey === false) {
            $this->sendResponse(['error' => 'Unable to read service key file']);
        }

        $credentials = new ServiceAccountCredentials($this->scope, $this->serviceAccountKeyFile);
        $token = $credentials->fetchAuthToken(HttpHandlerFactory::build());

        if (isset($token['access_token'])) {
            return $token['access_token'];
        } else {
            $this->sendResponse(['error' => 'Unable to fetch access token']);
        }
    }
    
    public function handlePostRequest() {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if (isset($_POST['token']) && isset($_POST['title'])) {
                $token = $_POST['token'];
                $title = $_POST['title'];
                $this->sendGCM($title, $token);
            } else {
                $this->sendResponse(['error' => 'Missing token or title']);
            }
        } else {
            $this->sendResponse(['error' => 'Invalid request method']);
        }
    }

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

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

        $fields = [
            'message' => [
                'token' => $token,
                'notification' => $requestData,
                'data' => $requestData, // If you also want to send data payload
            ]
        ];

        $fieldsJson = json_encode($fields);
        error_log("Fields JSON: $fieldsJson"); // Log the JSON payload for debugging

        $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);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsJson);

        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($result === FALSE) {
            error_log('Curl failed: ' . curl_error($ch)); // Log curl error
            $this->sendResponse(['error' => 'Curl failed: ' . curl_error($ch)]);
        } else {
            error_log("Response: $result"); // Log API response
            $this->sendResponse(['msg' => $result, 'http_code' => $httpCode]);
        }

        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); // Ensure $con is defined and open before closing
?>
