<?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 SendMessageFCM {
    private $credentialskeyPath;
    private $scopes = 'https://www.googleapis.com/auth/firebase.messaging';
    
    function __construct() {
        $this->credentialskeyPath = __DIR__ . '/tabatech-367c1-6e41a815b1b4.json';
    }
    
    private function getAccessToken() {
        $jsonKey = file_get_contents($this->credentialskeyPath);
        $serviceAccount = new ServiceAccountCredentials($this->scopes, $this->credentialskeyPath);
        $accessTokenArray = $serviceAccount->fetchAuthToken(HttpHandlerFactory::build());
        if (!isset($accessTokenArray['access_token'])) {
            throw new Exception('Failed to get the access token.');
        }
        return $accessTokenArray['access_token'];
    }

    public function sendGCM($message, $token, $deviceName) {
        $url = 'https://fcm.googleapis.com/v1/projects/tabatech-367c1/messages:send';

        // Structure the payload according to v1 API
        $fields = array(
            'message' => array(
                'token' => $token,
                'data' => array(
                    'message' => $message,
                    'deviceName' => $deviceName
                )
            )
        );

        $fields = json_encode($fields);

        $accessToken = $this->getAccessToken();

        $headers = array(
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        );

        $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_POSTFIELDS, $fields);

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

        return $result;
    }

    public function sendMessageFromPost() {
        // Getting message, token, and device name from Android side
        $message = $_POST['message'];
        $token = $_POST['token'];
        $deviceName = $_POST['deviceName'];

        // Sending a message
        $response = $this->sendGCM($message, $token, $deviceName);
        echo "Send message response: " . $response;
    }
}

// Usage Example:
$sendMessageFCM = new SendMessageFCM();
$sendMessageFCM->sendMessageFromPost();
?>
