<?php


require_once 'fcm_helper.php';
class FCM {

    private static $firebaseFile = __DIR__ . "/prodis_fcm.json";


    /// AMBIL ACCESS TOKEN FIREBASE
    private static function getAccessToken(){

        $json = json_decode(file_get_contents(self::$firebaseFile), true);

        $jwtHeader = [
            "alg" => "RS256",
            "typ" => "JWT"
        ];

        $now = time();

        $jwtClaim = [
            "iss"   => $json['client_email'],
            "scope" => "https://www.googleapis.com/auth/firebase.messaging",
            "aud"   => $json['token_uri'],
            "iat"   => $now,
            "exp"   => $now + 3600
        ];

        $base64Header = rtrim(strtr(base64_encode(json_encode($jwtHeader)), '+/', '-_'), '=');
        $base64Claim  = rtrim(strtr(base64_encode(json_encode($jwtClaim)), '+/', '-_'), '=');

        $signatureInput = $base64Header . "." . $base64Claim;

        openssl_sign($signatureInput, $signature, $json['private_key'], 'sha256');

        $base64Signature = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

        $jwt = $base64Header . "." . $base64Claim . "." . $base64Signature;

        $postData = [
            "grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
            "assertion"  => $jwt
        ];

        $ch = curl_init($json['token_uri']);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));

        $response = curl_exec($ch);

        if(curl_errno($ch)){
            echo "TOKEN ERROR: " . curl_error($ch);
        }

        curl_close($ch);

        $data = json_decode($response,true);

        return $data['access_token'] ?? null;
    }



    /// KIRIM NOTIFIKASI KE TOPIC
    public static function sendTopic($topic,$title,$message,$type="general"){

        $json = json_decode(file_get_contents(self::$firebaseFile), true);

        $accessToken = self::getAccessToken();

      if(!$accessToken){
    file_put_contents("log_notif.txt", "ACCESS TOKEN NULL\n", FILE_APPEND);
    return;
}

        $url = "https://fcm.googleapis.com/v1/projects/".$json['project_id']."/messages:send";


        $payload = [

            "message" => [

                "topic" => $topic,

                "notification" => [
                    "title" => $title,
                    "body"  => $message
                ],

                /// DATA UNTUK ROUTING FLUTTER
                "data" => [
                    "type" => $type
                ],

                /// PRIORITY ANDROID
                "android" => [
                    "priority" => "HIGH",
                    "notification" => [
                        "click_action" => "FLUTTER_NOTIFICATION_CLICK"
                    ]
                ]

            ]

        ];


        $headers = [
            "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,json_encode($payload));

        $result = curl_exec($ch);

        if(curl_errno($ch)){
            echo "FCM ERROR: ".curl_error($ch);
        }

        curl_close($ch);

        return $result;
    }



    /// KIRIM NOTIFIKASI KE TOKEN DEVICE
    public static function sendToken($token,$title,$message,$type="general"){

    global $conn;

    $json = json_decode(file_get_contents(self::$firebaseFile), true);

    $accessToken = self::getAccessToken();

    if(!$accessToken){
        return;
    }

    $url = "https://fcm.googleapis.com/v1/projects/".$json['project_id']."/messages:send";

    $payload = [
        "message" => [
            "token" => $token,
            "notification" => [
                "title" => $title,
                "body"  => $message
            ],
            "data" => [
                "type" => $type
            ],
            "android" => [
                "priority" => "HIGH",
                "notification" => [
                    "click_action" => "FLUTTER_NOTIFICATION_CLICK"
                ]
            ]
        ]
    ];

    $headers = [
        "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,json_encode($payload));

    $result = curl_exec($ch);

    curl_close($ch);

    // =========================
    // 🔥 HANDLE TOKEN EXPIRE DI SINI
    // =========================
    $res = json_decode($result, true);

    if (isset($res['error'])) {

        $status = $res['error']['status'] ?? '';

        if (in_array($status, [
            'UNREGISTERED',
            'INVALID_ARGUMENT'
        ])) {

            mysqli_query($conn, "
                DELETE FROM user_devices 
                WHERE fcm_token = '" . mysqli_real_escape_string($conn, $token) . "'
            ");

            file_put_contents("log_notif.txt", "HAPUS TOKEN: $token\n", FILE_APPEND);
        }
    }

    return $result;
}


// =========================
// 🔥 INSERT NOTIFICATION
// =========================
function notif_insert($conn, $userId, $title, $message, $type = null, $refId = null)
{
    $id = uniqid();

    $titleSafe   = mysqli_real_escape_string($conn, $title);
    $messageSafe = mysqli_real_escape_string($conn, $message);
    $typeSafe    = $type ? "'".mysqli_real_escape_string($conn, $type)."'" : "NULL";
    $refSafe     = $refId ? "'".mysqli_real_escape_string($conn, $refId)."'" : "NULL";

    mysqli_query($conn, "
        INSERT INTO notifications (
            id, user_id, title, message, type, reference_id, created_at, is_synced
        ) VALUES (
            '$id',
            '$userId',
            '$titleSafe',
            '$messageSafe',
            $typeSafe,
            $refSafe,
            NOW(),
            0
        )
    ");
}


// =========================
// 🔥 AMBIL TOKEN USER
// =========================
function notif_get_tokens($conn, $userId)
{
    $tokens = [];

    $res = mysqli_query($conn, "
        SELECT fcm_token 
        FROM user_devices 
        WHERE user_id='$userId'
    ");

    if (!$res) return [];

    while ($row = mysqli_fetch_assoc($res)) {
        if (!empty($row['fcm_token'])) {
            $tokens[] = $row['fcm_token'];
        }
    }

    // 🔥 hapus duplicate
    return array_unique($tokens);
}

// =========================
// 🔥 SEND NOTIF KE 1 USER
// =========================
function notif_send_to_user($conn, $userId, $title, $message, $type = null, $refId = null)
{
    // 1. simpan ke DB
    notif_insert($conn, $userId, $title, $message, $type, $refId);

    // 2. ambil token
    $tokens = notif_get_tokens($conn, $userId);

    // 3. kirim FCM
    if (!empty($tokens)) {
        FCM::sendMultiple($tokens, $title, $message, $type);
    }
}

/// 🔥 KIRIM KE BANYAK TOKEN
public static function sendMultiple($tokens,$title,$message,$type="general"){

    $results = [];

    foreach($tokens as $t){
        $results[] = self::sendToken($t,$title,$message,$type);
    }

    return $results;
}

// =========================
// 🔥 SEND KE ROLE (OWNER DLL)
// =========================
function notif_send_to_role($conn, $role, $title, $message, $type = null, $refId = null)
{
    $users = mysqli_query($conn, "
        SELECT id FROM users WHERE role='$role'
    ");

    while ($u = mysqli_fetch_assoc($users)) {
        notif_send_to_user($conn, $u['id'], $title, $message, $type, $refId);
    }
}


// =========================
// 🔥 SEND KE GUDANG
// =========================
function notif_send_to_warehouse($conn, $warehouseId, $title, $message, $type = null, $refId = null)
{
    $users = mysqli_query($conn, "
        SELECT id FROM users WHERE warehouse_id='$warehouseId'
    ");

    while ($u = mysqli_fetch_assoc($users)) {
        notif_send_to_user($conn, $u['id'], $title, $message, $type, $refId);
    }
}
}