<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Firebase {

    private $projectId;
    private $privateKey;
    private $clientEmail;
    private $accessToken;
    private $serviceAccountPath;

    public function __construct() {
        $this->serviceAccountPath = APPPATH . 'config/firebase_service_account.json';

        if (!file_exists($this->serviceAccountPath)) {
            show_error('Firebase service account file missing.');
        }

        $this->loadServiceAccount();
        $this->accessToken = $this->generateAccessToken();
    }

    private function loadServiceAccount() {
        $json = json_decode(file_get_contents($this->serviceAccountPath), true);
        $this->projectId = $json['project_id'];
        $this->clientEmail = $json['client_email'];
        $this->privateKey = $json['private_key'];
    }

   private function generateAccessToken() {
    $now = time();
    $jwtHeader = ['alg' => 'RS256', 'typ' => 'JWT'];
    $jwtClaim = [
        'iss' => $this->clientEmail,
        'scope' => 'https://www.googleapis.com/auth/firebase.messaging',
        'aud' => 'https://oauth2.googleapis.com/token',
        'iat' => $now,
        'exp' => $now + 3600
    ];

    $base64UrlHeader = $this->base64UrlEncode(json_encode($jwtHeader));
    $base64UrlClaim = $this->base64UrlEncode(json_encode($jwtClaim));
    $signature = '';
    $data = $base64UrlHeader . '.' . $base64UrlClaim;

    openssl_sign($data, $signature, $this->privateKey, 'sha256');
    $jwt = $data . '.' . $this->base64UrlEncode($signature);

    // Use form-encoded format
    $postFields = http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]);

    $ch = curl_init('https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/x-www-form-urlencoded'
    ]);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        echo 'Curl error: ' . curl_error($ch);
        curl_close($ch);
        return false;
    }

    curl_close($ch);

    $decoded = json_decode($response, true);
    // print_r($decoded); // Shows access_token or error
    return $decoded['access_token'] ?? false;
}


    private function base64UrlEncode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    private function curlPost($url, $postFields, $headers = [], $jsonEncode = true) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($jsonEncode) {
            $postData = json_encode($postFields);
        } else {
            $postData = http_build_query($postFields);
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($ch);
        if ($response === false) {
            show_error('Curl error: ' . curl_error($ch));
        }
        curl_close($ch);
        return json_decode($response, true);
    }

    public function send($tokens, $title, $body, $data = [], $channel_id = 'default') {
        $url = "https://fcm.googleapis.com/v1/projects/{$this->projectId}/messages:send";

        if (!is_array($tokens)) {
            $tokens = [$tokens];
        }

        foreach ($tokens as $token) {
            $payload = [
				"message" => [
					"token" => $token,  // OR use "topic" => "your_topic"
					"notification" => [
						"title" => $title,
						"body" => $body,
						"image" => "https://wallpapercave.com/wp/wp9566386.jpg"
					],
					"data" => [  // This must be a map (associative array)
						"click_action" => "FLUTTER_NOTIFICATION_CLICK",
						"screen" => "ImageScreen",
						"image_url" => "https://wallpapercave.com/wp/wp9566386.jpg"
					]
				]
			];



            $headers = [
                'Authorization: Bearer ' . $this->accessToken,
                'Content-Type: application/json'
            ];

           return $this->curlPost($url, $payload, $headers);
        }
    }
	
	public function sendToTopic($topic, $title, $body, $image = null, $data = [], $channel_id = 'default') {
    $url = "https://fcm.googleapis.com/v1/projects/{$this->projectId}/messages:send";

    $message = [
        "topic" => $topic,
        "notification" => [
            "title" => $title,
            "body" => $body,
        ],
        "data" => array_merge([
            "click_action" => "FLUTTER_NOTIFICATION_CLICK",
        ], $data)
    ];

    if ($image) {
        $message['notification']['image'] = $image;
        $message['data']['image_url'] = $image;
    }

    $payload = [
        "message" => $message
    ];

    $headers = [
        'Authorization: Bearer ' . $this->accessToken,
        'Content-Type: application/json'
    ];

    return $this->curlPost($url, $payload, $headers);
}

}
	