<?php
require_once __DIR__ . '/comp/vendor/autoload.php';
use Google\Auth\CredentialsLoader;
use Google\Auth\OAuth2;
use GuzzleHttp\Client;
use App\Models\Configuration;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\HttpHandler\HttpHandlerFactory;
class FCMNotifier {
    private $serviceAccountKeyFile;
    private $scope = "https://www.googleapis.com/auth/firebase.messaging";
    function __construct()
    {
        $this->serviceAccountKeyFile = __DIR__ . '/auth/s_key.json';
    }
    private function getAccessToken()
    {
        $jsonKey = file_get_contents($this->serviceAccountKeyFile);
        $creadentials = new ServiceAccountCredentials($this->scope, $this->serviceAccountKeyFile);
        $token = $creadentials->fetchAuthToken(HttpHandlerFactory::build());
        return $token['access_token'];
    }

public function sendFCMMessage($fcmToken, $title, $body, $type, $userEmail)
{
    $url = 'https://fcm.googleapis.com/v1/projects/magician-apps/messages:send';
    $accessToken = $this->getAccessToken();
    $headers = [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ];
    $payload = [
        'message' => [
            'token' => $fcmToken,
            'data' => [
                'title' =>$title,
                'body' => $body,
                'type' => $type,
                'userEmail' => $userEmail
            ]
        ]
    ];



    $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);    
    // Set payload
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    // Execute the request
    $result = curl_exec($ch);
    // Check for errors
    if (curl_errno($ch)) {
        $error = 'cURL error: ' . curl_error($ch);
        curl_close($ch);
        throw new Exception($error);
    }
    // Check HTTP status code
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpCode != 200) {
        throw new Exception('FCM server returned HTTP status ' . $httpCode . ': ' . $result);
    }
    return $result;
}
    public function handlePostRequest()
    {
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $fcmToken = $_POST['fcmToken'];
            $title = $_POST['title'];
            $body = $_POST['body'];
            $type = $_POST['type'];
            $userEmail = $_POST['userEmail'];
            try {
                $response = $this->sendFCMMessage($fcmToken, $title, $body, $type,$userEmail);
                echo $response;
            } catch (Exception $e) {
                echo "Error: " . $e->getMessage();
            }
        } else {
            echo "Invalid request method. Received method: " . $_SERVER["REQUEST_METHOD"];
        }
    }
}
// Example usage:
$notifier = new FCMNotifier();
$notifier->handlePostRequest();
?>